Moving project content to trunk as it should have been from the start.
This commit is contained in:
parent
057f3dc04c
commit
c2bdac23a6
119
src/org/ice4j/NetAccessPointDescriptor.java
Normal file
119
src/org/ice4j/NetAccessPointDescriptor.java
Normal file
@ -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());
|
||||
}
|
||||
}
|
||||
35
src/org/ice4j/ResponseCollector.java
Normal file
35
src/org/ice4j/ResponseCollector.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public 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();
|
||||
}
|
||||
105
src/org/ice4j/StackProperties.java
Normal file
105
src/org/ice4j/StackProperties.java
Normal file
@ -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
|
||||
* <tt>propertyName</tt>, 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, <tt>defaultValue</tt> 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;
|
||||
* <tt>defaultValue</tt> 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;
|
||||
}
|
||||
}
|
||||
157
src/org/ice4j/StunException.java
Normal file
157
src/org/ice4j/StunException.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2003</p>
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class 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;
|
||||
}
|
||||
|
||||
}
|
||||
89
src/org/ice4j/StunMessageEvent.java
Normal file
89
src/org/ice4j/StunMessageEvent.java
Normal file
@ -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).
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class 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;
|
||||
}
|
||||
}
|
||||
71
src/org/ice4j/Transport.java
Normal file
71
src/org/ice4j/Transport.java
Normal file
@ -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 <tt>Transport</tt> 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 <tt>Transport</tt>.
|
||||
*/
|
||||
private final String transportName;
|
||||
|
||||
/**
|
||||
* Creates a <tt>Transport</tt> instance with the specified name.
|
||||
*
|
||||
* @param transportName the name of the <tt>Transport</tt> instance we'd
|
||||
* like to create.
|
||||
*/
|
||||
private Transport(String transportName)
|
||||
{
|
||||
this.transportName = transportName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of this <tt>Transport</tt> (e.g. "udp" or
|
||||
* "tcp").
|
||||
*
|
||||
* @return the name of this <tt>Transport</tt> (e.g. "udp" or
|
||||
* "tcp").
|
||||
*/
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return transportName;
|
||||
}
|
||||
}
|
||||
264
src/org/ice4j/TransportAddress.java
Normal file
264
src/org/ice4j/TransportAddress.java
Normal file
@ -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.
|
||||
* <p>
|
||||
* A valid port value is between 0 and 65535.
|
||||
* A port number of <code>zero</code> will let the system pick up an
|
||||
* ephemeral port in a <code>bind</code> operation.
|
||||
* <P>
|
||||
* A <code>null</code> address will assign the <i>wildcard</i> address.
|
||||
* <p>
|
||||
* @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.
|
||||
* <p>
|
||||
* A valid port value is between 0 and 65535.
|
||||
* A port number of <code>zero</code> will let the system pick up an
|
||||
* ephemeral port in a <code>bind</code> operation.
|
||||
* <P>
|
||||
* A <code>null</code> address will assign the <i>wildcard</i> address.
|
||||
* <p>
|
||||
* @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.
|
||||
* <p>
|
||||
* A valid port value is between 0 and 65535.
|
||||
* A port number of <code>zero</code> will let the system pick up an
|
||||
* ephemeral port in a <code>bind</code> operation.
|
||||
* <P>
|
||||
* A <code>null</code> address will assign the <i>wildcard</i> address.
|
||||
* <p>
|
||||
* @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.
|
||||
* <p>
|
||||
* An attempt will be made to resolve the hostname into an InetAddress.
|
||||
* If that attempt fails, the address will be flagged as <I>unresolved</I>.
|
||||
* <p>
|
||||
* A valid port value is between 0 and 65535.
|
||||
* A port number of <code>zero</code> will let the system pick up an
|
||||
* ephemeral port in a <code>bind</code> operation.
|
||||
* <P>
|
||||
* @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 <TT>null</TT>.
|
||||
*/
|
||||
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.
|
||||
* <p>
|
||||
* 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 <TT>null</TT>.
|
||||
*/
|
||||
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.
|
||||
* <p/>
|
||||
* Two instances of InetSocketAddress represent the same address if both the
|
||||
* InetAddresses (or hostnames if it is unresolved) and port numbers are
|
||||
* equal.
|
||||
* <p/>
|
||||
* 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 <tt>InetAddress</tt> encapsulated by this
|
||||
* <tt>TransportAddress</tt>.
|
||||
*
|
||||
* @return the <tt>InetAddress</tt> encapsulated by this
|
||||
* <tt>TransportAddress</tt>.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
301
src/org/ice4j/attribute/AddressAttribute.java
Normal file
301
src/org/ice4j/attribute/AddressAttribute.java
Normal file
@ -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-ADDRESS <br/>
|
||||
* RESPONSE-ADDRESS <br/>
|
||||
* SOURCE-ADDRESS <br/>
|
||||
* CHANGED-ADDRESS <br/>
|
||||
* REFLECTED-FROM <br/>
|
||||
* ALTERNATE-SERVER <br/>
|
||||
* XOR-PEER-ADDRESS <br/>
|
||||
* XOR-RELAYED-ADDRESS <br/>
|
||||
*
|
||||
* The different attributes are distinguished by the attributeType of
|
||||
* org.ice4j.attribute.Attribute.
|
||||
*
|
||||
* Address attributes indicate the mapped IP address and
|
||||
* port. They consist 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 <br/>
|
||||
* 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 <br/>
|
||||
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
|
||||
* |x x x x x x x x| Family | Port | <br/>
|
||||
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
|
||||
* | Address | <br/>
|
||||
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
|
||||
* <br/>
|
||||
* 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 MAPPED-ADDRESS are ignored, for the purposes of
|
||||
* aligning parameters on natural boundaries. The IPv4 address is 32
|
||||
* bits.
|
||||
*
|
||||
*
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
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));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
53
src/org/ice4j/attribute/AlternateServerAttribute.java
Normal file
53
src/org/ice4j/attribute/AlternateServerAttribute.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2008</p>
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
|
||||
191
src/org/ice4j/attribute/Attribute.java
Normal file
191
src/org/ice4j/attribute/Attribute.java
Normal file
@ -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 3 <br/>
|
||||
* 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 <br/>
|
||||
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
|
||||
* | Type | Length | <br/>
|
||||
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
|
||||
* | Value .... <br/>
|
||||
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
|
||||
*<br/>
|
||||
* The following types are defined:<br/>
|
||||
*<br/>
|
||||
* STUN attributes:<br/>
|
||||
* 0x0001: MAPPED-ADDRESS <br/>
|
||||
* 0x0002: RESPONSE-ADDRESS <br/>
|
||||
* 0x0003: CHANGE-REQUEST <br/>
|
||||
* 0x0004: SOURCE-ADDRESS <br/>
|
||||
* 0x0005: CHANGED-ADDRESS <br/>
|
||||
* 0x0006: USERNAME <br/>
|
||||
* 0x0007: PASSWORD <br/>
|
||||
* 0x0008: MESSAGE-INTEGRITY <br/>
|
||||
* 0x0009: ERROR-CODE <br/>
|
||||
* 0x000a: UNKNOWN-ATTRIBUTES <br/>
|
||||
* 0x000b: REFLECTED-FROM <br/>
|
||||
* 0x0014: REALM <br/>
|
||||
* 0x0015: NONCE <br/>
|
||||
* 0x0020: XOR-MAPPED-ADDRESS <br/>
|
||||
* 0x8022: SOFTWARE <br/>
|
||||
* 0x8023: ALTERNATE-SERVER <br/>
|
||||
* 0x8028: FINGERPRINT <br/>
|
||||
* <br/>
|
||||
* TURN attributes:<br/>
|
||||
* 0x000C: CHANNEL-NUMBER <br/>
|
||||
* 0x000D: LIFETIME <br/>
|
||||
* 0x0012: XOR-PEER-ADDRESS <br/>
|
||||
* 0x0013: DATA <br/>
|
||||
* 0x0016: XOR-RELAYED-ADDRESS <br/>
|
||||
* 0x0018: EVEN-PORT <br/>
|
||||
* 0x0019: REQUESTED-TRANSPORT <br/>
|
||||
* 0x001A: DONT-FRAGMENT <br/>
|
||||
* 0x0022: RESERVATION-TOKEN <br/>
|
||||
*
|
||||
* ICE attributes:<br/>
|
||||
* 0x0024: PRIORITY <br/>
|
||||
* 0x0025: USE-CANDIDATE <br/>
|
||||
* 0x8029: ICE-CONTROLLED <br/>
|
||||
* 0x802A: ICE-CONTROLLING <br/>
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2003-2008</p>
|
||||
* <p> Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p> Network Research Team (http://www-r2.u-strasbg.fr)</p>
|
||||
* @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;
|
||||
|
||||
}
|
||||
132
src/org/ice4j/attribute/AttributeDecoder.java
Normal file
132
src/org/ice4j/attribute/AttributeDecoder.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2003-2008</p>
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @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;
|
||||
}
|
||||
|
||||
}
|
||||
518
src/org/ice4j/attribute/AttributeFactory.java
Normal file
518
src/org/ice4j/attribute/AttributeFactory.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2003-2008</p>
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
|
||||
215
src/org/ice4j/attribute/ChangeRequestAttribute.java
Normal file
215
src/org/ice4j/attribute/ChangeRequestAttribute.java
Normal file
@ -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 3 <br/>
|
||||
* 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 <br/>
|
||||
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
|
||||
* |0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A B 0| <br/>
|
||||
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
|
||||
*
|
||||
* The meaning of the flags is:
|
||||
*
|
||||
* A: 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.
|
||||
*
|
||||
* B: 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.
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2003</p>
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class 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);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
37
src/org/ice4j/attribute/ChangedAddressAttribute.java
Normal file
37
src/org/ice4j/attribute/ChangedAddressAttribute.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2003</p>
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class ChangedAddressAttribute extends AddressAttribute
|
||||
{
|
||||
public static final String NAME = "CHANGED-ADDRESS";
|
||||
|
||||
/**
|
||||
* Creates a CHANGED_ADDRESS attribute
|
||||
*/
|
||||
public ChangedAddressAttribute()
|
||||
{
|
||||
super(CHANGED_ADDRESS);
|
||||
}
|
||||
|
||||
}
|
||||
152
src/org/ice4j/attribute/ChannelNumberAttribute.java
Normal file
152
src/org/ice4j/attribute/ChannelNumberAttribute.java
Normal file
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
162
src/org/ice4j/attribute/DataAttribute.java
Normal file
162
src/org/ice4j/attribute/DataAttribute.java
Normal file
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
115
src/org/ice4j/attribute/DontFragmentAttribute.java
Normal file
115
src/org/ice4j/attribute/DontFragmentAttribute.java
Normal file
@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
398
src/org/ice4j/attribute/ErrorCodeAttribute.java
Normal file
398
src/org/ice4j/attribute/ErrorCodeAttribute.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2003</p>
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
public class 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());
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
156
src/org/ice4j/attribute/EvenPortAttribute.java
Normal file
156
src/org/ice4j/attribute/EvenPortAttribute.java
Normal file
@ -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 : <br/>
|
||||
* R : ask to reserve a second port.<br/>
|
||||
*
|
||||
* @author Sebastien Vincent
|
||||
* @version 0.1
|
||||
*/
|
||||
public class EvenPortAttribute extends Attribute
|
||||
{
|
||||
/**
|
||||
* Attribute name.
|
||||
*/
|
||||
public static final String NAME = "EVEN-PORT";
|
||||
|
||||
/**
|
||||
* The length of the data contained by this attribute.
|
||||
*/
|
||||
public static final char DATA_LENGTH = 1;
|
||||
|
||||
/**
|
||||
* R flag.
|
||||
*/
|
||||
boolean rFlag = false;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
EvenPortAttribute()
|
||||
{
|
||||
super(EVEN_PORT);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 EvenPortAttribute)
|
||||
|| obj == null)
|
||||
return false;
|
||||
|
||||
if (obj == this)
|
||||
return true;
|
||||
|
||||
EvenPortAttribute att = (EvenPortAttribute) obj;
|
||||
if (att.getAttributeType() != getAttributeType()
|
||||
|| att.getDataLength() != getDataLength()
|
||||
/* compare data */
|
||||
|| att.rFlag != rFlag
|
||||
)
|
||||
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)(rFlag ? 1 << 8 : 0);
|
||||
binValue[5] = 0x00; /* not used for the moment */
|
||||
binValue[6] = 0x00; /* not used for the moment */
|
||||
binValue[7] = 0x00; /* not used for the moment */
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
rFlag = (attributeValue[0] & 0x80) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the R flag.
|
||||
* @param rFlag true of false
|
||||
*/
|
||||
public void setRFlag(boolean rFlag)
|
||||
{
|
||||
this.rFlag = rFlag;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the R flag set
|
||||
* @return true if it is, false otherwise
|
||||
*/
|
||||
public boolean isRFlag()
|
||||
{
|
||||
return rFlag;
|
||||
}
|
||||
}
|
||||
|
||||
148
src/org/ice4j/attribute/FingerprintAttribute.java
Normal file
148
src/org/ice4j/attribute/FingerprintAttribute.java
Normal file
@ -0,0 +1,148 @@
|
||||
/*
|
||||
* 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 FINGERPRINT attribute is used to distinguish STUN packets
|
||||
* from packets of other protocols.
|
||||
*
|
||||
* @author Sebastien Vincent
|
||||
* @version 0.1
|
||||
*/
|
||||
public class FingerprintAttribute extends Attribute
|
||||
{
|
||||
/**
|
||||
* Attribute name.
|
||||
*/
|
||||
public static final String NAME = "FINGERPRINT";
|
||||
|
||||
/**
|
||||
* CRC value.
|
||||
*/
|
||||
private int crc = 0;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
FingerprintAttribute()
|
||||
{
|
||||
super(FINGERPRINT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of this attribute's body.
|
||||
* @return the length of this attribute's value.
|
||||
*/
|
||||
public char getDataLength()
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the human readable name of this attribute.
|
||||
* @return this attribute's name.
|
||||
*/
|
||||
public String getName()
|
||||
{
|
||||
return NAME;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 FingerprintAttribute) || obj == null)
|
||||
return false;
|
||||
|
||||
if (obj == this)
|
||||
return true;
|
||||
|
||||
FingerprintAttribute att = (FingerprintAttribute) obj;
|
||||
if (att.getAttributeType() != getAttributeType()
|
||||
|| att.getDataLength() != getDataLength()
|
||||
|| att.crc == crc)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a (cloned) byte array containg the data value of the CRC
|
||||
* attribute.
|
||||
* @return the binary array containing the CRC.
|
||||
*/
|
||||
public int getCrc()
|
||||
{
|
||||
return crc;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Copies the specified binary array into the the CRC value of the CRC
|
||||
* attribute.
|
||||
* @param crc the binary array containing the CRC.
|
||||
*/
|
||||
public void setCrc(int crc)
|
||||
{
|
||||
this.crc = crc;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/* CRC */
|
||||
binValue[4] = (byte)((crc >> 24) & 0xff);
|
||||
binValue[5] = (byte)((crc >> 16) & 0xff);
|
||||
binValue[6] = (byte)((crc >> 8) & 0xff);
|
||||
binValue[7] = (byte)(crc & 0xff);
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
crc = ((attributeValue[0] << 24) & 0xff000000) + ((attributeValue[1] << 16) & 0x00ff0000)
|
||||
+ ((attributeValue[2] << 8) & 0x0000ff00) + (attributeValue[3] & 0x000000ff);
|
||||
}
|
||||
}
|
||||
|
||||
168
src/org/ice4j/attribute/IceControlledAttribute.java
Normal file
168
src/org/ice4j/attribute/IceControlledAttribute.java
Normal file
@ -0,0 +1,168 @@
|
||||
package org.ice4j.attribute;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
|
||||
public class IceControlledAttribute
|
||||
extends Attribute
|
||||
{
|
||||
|
||||
/**
|
||||
* The length of the data contained in this attribute
|
||||
*/
|
||||
private static final char DATA_LENGTH_ICE_CONTROLLED = 8;
|
||||
|
||||
/**
|
||||
* The tie-breaker value represented in this attribute
|
||||
*/
|
||||
byte[] tieBreaker = null;
|
||||
|
||||
/**
|
||||
* Constructs an ICE-CONTROLLED attribute
|
||||
*/
|
||||
protected IceControlledAttribute()
|
||||
{
|
||||
super(ICE_CONTROLLED);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this attribute's fields according to attributeValue array.
|
||||
*
|
||||
* @param attributeValue a binary array containing this attribute's field
|
||||
* values and NOT containing the attribute header.
|
||||
* @param offset the position where attribute values begin (most often
|
||||
* offset is equal to the index of the first byte after
|
||||
* length)
|
||||
* @param length the length of the attribute data.
|
||||
*
|
||||
* @throws StunException if attributeValue contains invalid data.
|
||||
*/
|
||||
void decodeAttributeBody(byte[] attributeValue, char offset, char length)
|
||||
throws StunException
|
||||
{
|
||||
// initializing the byte arrays which holds the 64 bit value
|
||||
// after decoding
|
||||
tieBreaker = new byte[length];
|
||||
|
||||
System.arraycopy(attributeValue, offset, tieBreaker, 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 + DATA_LENGTH_ICE_CONTROLLED];
|
||||
|
||||
// Type
|
||||
binValue[0] = (byte)(type>>8);
|
||||
binValue[1] = (byte)(type&0x00FF);
|
||||
|
||||
// Length
|
||||
binValue[2] = (byte)(DATA_LENGTH_ICE_CONTROLLED>>8);
|
||||
binValue[3] = (byte)(DATA_LENGTH_ICE_CONTROLLED&0x00FF);
|
||||
|
||||
// Tie-Breaker, 64 bits stored in network byte order
|
||||
System.arraycopy(tieBreaker, 0, binValue, 4, tieBreaker.length);
|
||||
|
||||
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 IceControlledAttribute)
|
||||
|| obj == null)
|
||||
return false;
|
||||
|
||||
if(obj == this)
|
||||
return true;
|
||||
|
||||
IceControlledAttribute iceControlledAtt = (IceControlledAttribute)obj;
|
||||
if(iceControlledAtt.getAttributeType() != getAttributeType()
|
||||
|| iceControlledAtt.getDataLength() != DATA_LENGTH_ICE_CONTROLLED
|
||||
|| (tieBreaker != null
|
||||
&& !Arrays.equals(tieBreaker, iceControlledAtt.tieBreaker))
|
||||
)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the data length of this attribute
|
||||
*
|
||||
* @return the data length of this attribute
|
||||
*/
|
||||
public char getDataLength()
|
||||
{
|
||||
return DATA_LENGTH_ICE_CONTROLLED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the human readable name of this attribute.
|
||||
*
|
||||
* @return this attribute's name.
|
||||
*/
|
||||
public String getName()
|
||||
{
|
||||
return "ICE-CONTROLLED";
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Tie Breaker byte array to the specified byte array
|
||||
* An exact copy of the specified byte array is made
|
||||
*
|
||||
* @param tieBreaker the byte array containing the 64 bit tie-breaker
|
||||
* value
|
||||
*
|
||||
* @throws StunException if tieBreaker contains invalid data
|
||||
*/
|
||||
public void setTieBreaker(byte[] tieBreaker)
|
||||
throws StunException
|
||||
{
|
||||
if(tieBreaker.length != DATA_LENGTH_ICE_CONTROLLED)
|
||||
{
|
||||
throw new StunException(StunException.ILLEGAL_ARGUMENT,
|
||||
"The supplied byte array does not contain the correct number"
|
||||
+" of bytes");
|
||||
}
|
||||
else
|
||||
{
|
||||
//FIXME - uncomment.
|
||||
//this.tieBreaker = Arrays.copyOf(tieBreaker, tieBreaker.length);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a copy of the Tie Breaker byte array
|
||||
*
|
||||
* @return an exact copy of the Tie Breaker byte array
|
||||
*/
|
||||
public byte[] getTieBreaker()
|
||||
{
|
||||
if(tieBreaker == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
else
|
||||
{
|
||||
//FIXME uncomment
|
||||
//return Arrays.copyOf(tieBreaker, tieBreaker.length);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
160
src/org/ice4j/attribute/IceControllingAttribute.java
Normal file
160
src/org/ice4j/attribute/IceControllingAttribute.java
Normal file
@ -0,0 +1,160 @@
|
||||
package org.ice4j.attribute;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
|
||||
public class IceControllingAttribute
|
||||
extends Attribute
|
||||
{
|
||||
/**
|
||||
* The length of the data contained in this attribute
|
||||
*/
|
||||
private static final char DATA_LENGTH_ICE_CONTROLLING = 8;
|
||||
|
||||
/**
|
||||
* The tie-breaker value stored in this attribute
|
||||
*/
|
||||
byte[] tieBreaker = null;
|
||||
|
||||
/**
|
||||
* Constructs an ICE-CONTROLLING attribute
|
||||
*/
|
||||
protected IceControllingAttribute()
|
||||
{
|
||||
super(ICE_CONTROLLING);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this attribute's fields according to attributeValue array.
|
||||
*
|
||||
* @param attributeValue a binary array containing this attribute's field
|
||||
* values and NOT containing the attribute header.
|
||||
* @param offset the position where attribute values begin (most often
|
||||
* offset is equal to the index of the first byte after
|
||||
* length)
|
||||
* @param length the length of the attribute data.
|
||||
*
|
||||
* @throws StunException if attrubteValue contains invalid data.
|
||||
*/
|
||||
void decodeAttributeBody(byte[] attributeValue, char offset, char length)
|
||||
throws StunException {
|
||||
// initializing the byte arrays which holds the 64 bit value after decoding
|
||||
tieBreaker = new byte[length];
|
||||
|
||||
System.arraycopy(attributeValue, offset, tieBreaker, 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 + DATA_LENGTH_ICE_CONTROLLING];
|
||||
|
||||
// Type
|
||||
binValue[0] = (byte)(type>>8);
|
||||
binValue[1] = (byte)(type&0x00FF);
|
||||
|
||||
// Length
|
||||
binValue[2] = (byte)(DATA_LENGTH_ICE_CONTROLLING>>8);
|
||||
binValue[3] = (byte)(DATA_LENGTH_ICE_CONTROLLING&0x00FF);
|
||||
|
||||
// Tie-Breaker, 64 bits stored in network byte order
|
||||
System.arraycopy(tieBreaker, 0, binValue, 4, tieBreaker.length);
|
||||
|
||||
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 IceControllingAttribute)
|
||||
|| obj == null)
|
||||
return false;
|
||||
|
||||
if(obj == this)
|
||||
return true;
|
||||
|
||||
IceControllingAttribute iceControllingAtt = (IceControllingAttribute)obj;
|
||||
if(iceControllingAtt.getAttributeType() != getAttributeType()
|
||||
|| iceControllingAtt.getDataLength() != DATA_LENGTH_ICE_CONTROLLING
|
||||
|| !(Arrays.equals(getTieBreaker(),
|
||||
iceControllingAtt.getTieBreaker())))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the data length of this attribute
|
||||
*
|
||||
* @return the data length of this attribute
|
||||
*/
|
||||
public char getDataLength()
|
||||
{
|
||||
return DATA_LENGTH_ICE_CONTROLLING;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the human readable name of this attribute.
|
||||
*
|
||||
* @return this attribute's name.
|
||||
*/
|
||||
public String getName()
|
||||
{
|
||||
return "ICE-CONTROLLING";
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Tie Breaker byte array to the specified byte array
|
||||
* An exact copy of the specified byte array is made
|
||||
*
|
||||
* @param tieBreaker the byte array containing the 64 bit tie-breaker value
|
||||
*
|
||||
* @throws StunException if tieBreaker contains invalid data
|
||||
*/
|
||||
public void setTieBreaker(byte[] tieBreaker)
|
||||
throws StunException
|
||||
{
|
||||
if(tieBreaker.length != DATA_LENGTH_ICE_CONTROLLING)
|
||||
{
|
||||
throw new StunException(StunException.ILLEGAL_ARGUMENT,
|
||||
"The supplied byte array does not contain the correct number "
|
||||
+"of bytes");
|
||||
}
|
||||
else
|
||||
{
|
||||
//FIXME - uncomment
|
||||
//this.tieBreaker = Arrays.copyOf(tieBreaker, tieBreaker.length);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a copy of the Tie Breaker byte array
|
||||
*
|
||||
* @return an exact copy of the Tie Breaker byte array
|
||||
*/
|
||||
public byte[] getTieBreaker()
|
||||
{
|
||||
if(tieBreaker == null)
|
||||
return null;
|
||||
else
|
||||
{
|
||||
//FIXME -- uncomment
|
||||
//return Arrays.copyOf(tieBreaker, tieBreaker.length);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
153
src/org/ice4j/attribute/LifetimeAttribute.java
Normal file
153
src/org/ice4j/attribute/LifetimeAttribute.java
Normal file
@ -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.lang.*;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
* The LIFETIME attribute is used to know the lifetime
|
||||
* of TURN allocations.
|
||||
*
|
||||
* @author Sebastien Vincent
|
||||
* @version 0.1
|
||||
*/
|
||||
public class LifetimeAttribute extends Attribute
|
||||
{
|
||||
/**
|
||||
* Attribute name.
|
||||
*/
|
||||
public static final String NAME = "LIFETIME";
|
||||
|
||||
/**
|
||||
* The length of the data contained by this attribute.
|
||||
*/
|
||||
public static final char DATA_LENGTH = 4;
|
||||
|
||||
/**
|
||||
* Lifetime value.
|
||||
*/
|
||||
int lifetime = 0;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
LifetimeAttribute()
|
||||
{
|
||||
super(LIFETIME);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 LifetimeAttribute)
|
||||
|| obj == null)
|
||||
return false;
|
||||
|
||||
if (obj == this)
|
||||
return true;
|
||||
|
||||
LifetimeAttribute att = (LifetimeAttribute) obj;
|
||||
if (att.getAttributeType() != getAttributeType()
|
||||
|| att.getDataLength() != getDataLength()
|
||||
/* compare data */
|
||||
|| att.lifetime != lifetime
|
||||
)
|
||||
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)((lifetime >> 24) & 0xff);
|
||||
binValue[5] = (byte)((lifetime >> 16) & 0xff);
|
||||
binValue[6] = (byte)((lifetime >> 8) & 0xff);
|
||||
binValue[7] = (byte)((lifetime) & 0xff);
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
lifetime = ((attributeValue[0] << 24) & 0xff000000) + ((attributeValue[1] << 16) & 0x00ff0000)
|
||||
+ ((attributeValue[2] << 8) & 0x0000ff00) + (attributeValue[3] & 0x000000ff);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the lifetime.
|
||||
* @param lifetime lifetime
|
||||
*/
|
||||
public void setLifetime(int lifetime)
|
||||
{
|
||||
this.lifetime = lifetime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the lifetime.
|
||||
* @return lifetime
|
||||
*/
|
||||
public int getLifetime()
|
||||
{
|
||||
return lifetime;
|
||||
}
|
||||
}
|
||||
|
||||
44
src/org/ice4j/attribute/MappedAddressAttribute.java
Normal file
44
src/org/ice4j/attribute/MappedAddressAttribute.java
Normal file
@ -0,0 +1,44 @@
|
||||
/*
|
||||
* 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 MAPPED-ADDRESS attribute indicates the mapped IP address and
|
||||
* port. 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 MAPPED-ADDRESS are ignored, for the purposes of
|
||||
* aligning parameters on natural boundaries. The IPv4 address is 32
|
||||
* bits.
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2003</p>
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class MappedAddressAttribute extends AddressAttribute
|
||||
{
|
||||
public static final String NAME = "MAPPED-ADDRESS";
|
||||
|
||||
MappedAddressAttribute()
|
||||
{
|
||||
super(MAPPED_ADDRESS);
|
||||
}
|
||||
|
||||
}
|
||||
151
src/org/ice4j/attribute/NonceAttribute.java
Normal file
151
src/org/ice4j/attribute/NonceAttribute.java
Normal file
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
140
src/org/ice4j/attribute/OptionalAttribute.java
Normal file
140
src/org/ice4j/attribute/OptionalAttribute.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2003</p>
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*
|
||||
*/
|
||||
public class 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));
|
||||
}
|
||||
}
|
||||
171
src/org/ice4j/attribute/PriorityAttribute.java
Normal file
171
src/org/ice4j/attribute/PriorityAttribute.java
Normal file
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
153
src/org/ice4j/attribute/RealmAttribute.java
Normal file
153
src/org/ice4j/attribute/RealmAttribute.java
Normal file
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
39
src/org/ice4j/attribute/ReflectedFromAttribute.java
Normal file
39
src/org/ice4j/attribute/ReflectedFromAttribute.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2003</p>
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class ReflectedFromAttribute extends AddressAttribute
|
||||
{
|
||||
|
||||
public static final String NAME = "REFLECTED-FROM";
|
||||
|
||||
/**
|
||||
* Creates a REFLECTED-FROM attribute
|
||||
*/
|
||||
public ReflectedFromAttribute()
|
||||
{
|
||||
super(REFLECTED_FROM);
|
||||
}
|
||||
|
||||
}
|
||||
158
src/org/ice4j/attribute/RequestedTransportAttribute.java
Normal file
158
src/org/ice4j/attribute/RequestedTransportAttribute.java
Normal file
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
163
src/org/ice4j/attribute/ReservationTokenAttribute.java
Normal file
163
src/org/ice4j/attribute/ReservationTokenAttribute.java
Normal file
@ -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).
|
||||
*
|
||||
* <p>Organization Network Research Team, Louis Pasteur University</p>
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
|
||||
33
src/org/ice4j/attribute/ResponseAddressAttribute.java
Normal file
33
src/org/ice4j/attribute/ResponseAddressAttribute.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2003</p>
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class ResponseAddressAttribute extends AddressAttribute
|
||||
{
|
||||
public static final String NAME = "RESPONSE-ADDRESS";
|
||||
|
||||
/**
|
||||
* Creates a RESPONSE_ADDRESS attribute
|
||||
*/
|
||||
public ResponseAddressAttribute()
|
||||
{
|
||||
super(RESPONSE_ADDRESS);
|
||||
}
|
||||
|
||||
}
|
||||
158
src/org/ice4j/attribute/SoftwareAttribute.java
Normal file
158
src/org/ice4j/attribute/SoftwareAttribute.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Organization Network Research Team, Louis Pasteur University</p>
|
||||
* @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;
|
||||
}
|
||||
|
||||
}
|
||||
32
src/org/ice4j/attribute/SourceAddressAttribute.java
Normal file
32
src/org/ice4j/attribute/SourceAddressAttribute.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2003</p>
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class SourceAddressAttribute extends AddressAttribute
|
||||
{
|
||||
public static final String NAME = "SOURCE-ADDRESS";
|
||||
|
||||
/**
|
||||
* Creates a SOURCE-ADDRESS attribute
|
||||
*/
|
||||
SourceAddressAttribute()
|
||||
{
|
||||
super(SOURCE_ADDRESS);
|
||||
}
|
||||
}
|
||||
230
src/org/ice4j/attribute/UnknownAttributesAttribute.java
Normal file
230
src/org/ice4j/attribute/UnknownAttributesAttribute.java
Normal file
@ -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 ...
|
||||
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2003</p>
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class UnknownAttributesAttribute extends Attribute
|
||||
{
|
||||
/**
|
||||
* A list of attribute types that were not understood by the server.
|
||||
*/
|
||||
private ArrayList<Character> unknownAttributes = new ArrayList<Character>();
|
||||
|
||||
|
||||
UnknownAttributesAttribute()
|
||||
{
|
||||
super(UNKNOWN_ATTRIBUTES);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 String NAME = "UNKNOWN-ATTRIBUTES";
|
||||
|
||||
/**
|
||||
* Returns the length (in bytes) of this attribute's body.
|
||||
* 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.
|
||||
* @return the length of this attribute's value (a multiple of 4).
|
||||
*/
|
||||
public char getDataLength()
|
||||
{
|
||||
char len = (char)unknownAttributes.size();
|
||||
|
||||
if( (len % 2 ) != 0 )
|
||||
len++;
|
||||
|
||||
return (char)(len*2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the specified attribute type to the list of unknown attributes.
|
||||
* @param attributeID the id of an attribute to be listed as unknown in this
|
||||
* attribute
|
||||
*/
|
||||
public void addAttributeID(char attributeID)
|
||||
{
|
||||
//some attributes may be repeated for padding
|
||||
//(packet length should be divisable by 4)
|
||||
if(!contains(attributeID))
|
||||
unknownAttributes.add(new Character(attributeID));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies whether the specified attributeID is contained by this attribute.
|
||||
* @param attributeID the attribute id to look for.
|
||||
* @return true if this attribute contains the specified attribute id.
|
||||
*/
|
||||
public boolean contains(char attributeID)
|
||||
{
|
||||
return unknownAttributes.contains(new Character(attributeID));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an iterator over the list of attribute IDs contained by this
|
||||
* attribute.
|
||||
* @return an iterator over the list of attribute IDs contained by this
|
||||
* attribute.
|
||||
*/
|
||||
public Iterator getAttributes()
|
||||
{
|
||||
return unknownAttributes.iterator();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of attribute IDs contained by this class.
|
||||
* @return the number of attribute IDs contained by this class.
|
||||
*/
|
||||
public int getAttributeCount()
|
||||
{
|
||||
return unknownAttributes.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the attribute id with index i.
|
||||
* @param index the index of the attribute id to return.
|
||||
* @return the attribute id with index i.
|
||||
*/
|
||||
public char getAttribute(int index )
|
||||
{
|
||||
return (unknownAttributes.get(index)).charValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a binary representation of this attribute.
|
||||
* @return a binary representation of this attribute.
|
||||
*/
|
||||
public byte[] encode()
|
||||
{
|
||||
byte binValue[] = new byte[getDataLength() + HEADER_LENGTH];
|
||||
int offset = 0;
|
||||
|
||||
//Type
|
||||
binValue[offset++] = (byte) (getAttributeType() >> 8);
|
||||
binValue[offset++] = (byte) (getAttributeType() & 0x00FF);
|
||||
|
||||
//Length
|
||||
binValue[offset++] = (byte) (getDataLength() >> 8);
|
||||
binValue[offset++] = (byte) (getDataLength() & 0x00FF);
|
||||
|
||||
|
||||
Iterator attributes = getAttributes();
|
||||
while (attributes.hasNext()) {
|
||||
char att = ((Character)attributes.next()).charValue();
|
||||
binValue[offset++] = (byte)(att>>8);
|
||||
binValue[offset++] = (byte)(att & 0x00FF);
|
||||
}
|
||||
|
||||
// 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.
|
||||
if(offset < binValue.length)
|
||||
{
|
||||
char att = getAttribute(0);
|
||||
binValue[offset++] = (byte) (att >> 8);
|
||||
binValue[offset++] = (byte) (att & 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 UnknownAttributesAttribute)
|
||||
|| obj == null)
|
||||
return false;
|
||||
|
||||
if (obj == this)
|
||||
return true;
|
||||
|
||||
UnknownAttributesAttribute att = (UnknownAttributesAttribute) obj;
|
||||
if (att.getAttributeType() != getAttributeType()
|
||||
|| att.getDataLength() != getDataLength()
|
||||
|| !unknownAttributes.equals(att.unknownAttributes)
|
||||
)
|
||||
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
|
||||
{
|
||||
|
||||
if( (length % 2 ) != 0)
|
||||
throw new StunException("Attribute IDs are 2 bytes long and the "
|
||||
+"passed binary array has an odd length value.");
|
||||
char originalOffset = offset;
|
||||
for(int i = offset; i < originalOffset + length; i+=2)
|
||||
{
|
||||
char attributeID = (char)( (attributeValue[offset++]<<8) |
|
||||
(attributeValue[offset++]) );
|
||||
addAttributeID(attributeID);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
104
src/org/ice4j/attribute/UseCandidateAttribute.java
Normal file
104
src/org/ice4j/attribute/UseCandidateAttribute.java
Normal file
@ -0,0 +1,104 @@
|
||||
package org.ice4j.attribute;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
* This class implements the USE-CANDIDATE attribute
|
||||
* This attribute is an extension to the original STUN protocol
|
||||
* This is used only during an ICE implementation
|
||||
*
|
||||
* This attribute serves as only a flag, it does not have any data
|
||||
* so the data length is zero
|
||||
*/
|
||||
public class UseCandidateAttribute
|
||||
extends Attribute
|
||||
{
|
||||
private static final char DATA_LENGTH_USE_CANDIDATE = 0;
|
||||
|
||||
protected UseCandidateAttribute()
|
||||
{
|
||||
super(USE_CANDIDATE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes the USE-CANDIDATE attribute's body, which is empty
|
||||
*
|
||||
* @param attributeValue a binary array containing this attribute's
|
||||
* field values and NOT containing the attribute header.
|
||||
* @param offset the position where attribute values begin (most often
|
||||
* offset is equal to the index of the first byte after length)
|
||||
* @param length the length of the binary array.
|
||||
* @throws StunException if attrubteValue contains invalid data.
|
||||
*/
|
||||
void decodeAttributeBody(byte[] attributeValue, char offset, char length)
|
||||
throws StunException
|
||||
{
|
||||
// Do nothing, empty attribute body
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a binary representation of this attribute.
|
||||
*
|
||||
* @return a binary representation of this attribute.
|
||||
*/
|
||||
public byte[] encode()
|
||||
{
|
||||
char type = getAttributeType();
|
||||
byte[] binValue = new byte[HEADER_LENGTH + DATA_LENGTH_USE_CANDIDATE];
|
||||
|
||||
// Type
|
||||
binValue[0] = (byte)(type>>8);
|
||||
binValue[1] = (byte)(type&0x00FF);
|
||||
|
||||
// Length
|
||||
binValue[2] = (byte)(DATA_LENGTH_USE_CANDIDATE>>8);
|
||||
binValue[3] = (byte)(DATA_LENGTH_USE_CANDIDATE&0x00FF);
|
||||
|
||||
return binValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two STUN Attributes. Two attributes are considered equal when they
|
||||
* have the same type, length and value.
|
||||
*
|
||||
* @param obj the object to compare this attribute with.
|
||||
* @return true if the attributes are equal and false otherwise.
|
||||
*/
|
||||
public boolean equals(Object obj)
|
||||
{
|
||||
if(!(obj instanceof UseCandidateAttribute)
|
||||
|| obj == null)
|
||||
return false;
|
||||
|
||||
if(obj == this)
|
||||
return true;
|
||||
|
||||
UseCandidateAttribute useCandidateAtt = (UseCandidateAttribute)obj;
|
||||
if(useCandidateAtt.getAttributeType() != getAttributeType()
|
||||
|| useCandidateAtt.getDataLength() != getDataLength())
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of this attribute's body.
|
||||
*
|
||||
* @return the length of this attribute's value.
|
||||
*/
|
||||
public char getDataLength()
|
||||
{
|
||||
return DATA_LENGTH_USE_CANDIDATE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the human readable name of this attribute.
|
||||
*
|
||||
* @return this attribute's name.
|
||||
*/
|
||||
public String getName()
|
||||
{
|
||||
return "USE-CANDIDATE";
|
||||
}
|
||||
|
||||
}
|
||||
152
src/org/ice4j/attribute/UsernameAttribute.java
Normal file
152
src/org/ice4j/attribute/UsernameAttribute.java
Normal file
@ -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.util.*;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
* The USERNAME attribute is used for message integrity.
|
||||
* The value of USERNAME is a variable length value.
|
||||
*
|
||||
* @author Sebastien Vincent
|
||||
* @version 0.1
|
||||
*/
|
||||
public class UsernameAttribute extends Attribute
|
||||
{
|
||||
/**
|
||||
* Attribute name.
|
||||
*/
|
||||
public static final String NAME = "USERNAME";
|
||||
|
||||
/**
|
||||
* Username value.
|
||||
*/
|
||||
private byte username[] = null;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
UsernameAttribute()
|
||||
{
|
||||
super(USERNAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the value of the username 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
|
||||
{
|
||||
username = new byte[length];
|
||||
System.arraycopy(attributeValue, offset, username, 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);
|
||||
|
||||
/* username */
|
||||
System.arraycopy(username, 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)username.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 username
|
||||
* attribute.
|
||||
* @return the binary array containing the username.
|
||||
*/
|
||||
public byte[] getUsername()
|
||||
{
|
||||
if (username == null)
|
||||
return null;
|
||||
|
||||
byte[] copy = new byte[username.length];
|
||||
System.arraycopy(username, 0, copy, 0, username.length);
|
||||
return copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the specified binary array into the the data value of the username
|
||||
* attribute.
|
||||
* @param username the binary array containing the username.
|
||||
*/
|
||||
public void setUsername(byte[] username)
|
||||
{
|
||||
if (username == null)
|
||||
{
|
||||
this.username = null;
|
||||
return;
|
||||
}
|
||||
|
||||
this.username = new byte[username.length];
|
||||
System.arraycopy(username, 0, this.username, 0, username.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 UsernameAttribute) || obj == null)
|
||||
return false;
|
||||
|
||||
if (obj == this)
|
||||
return true;
|
||||
|
||||
UsernameAttribute att = (UsernameAttribute) obj;
|
||||
if (att.getAttributeType() != getAttributeType()
|
||||
|| att.getDataLength() != getDataLength()
|
||||
|| !Arrays.equals( att.username, username))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
105
src/org/ice4j/attribute/XorMappedAddressAttribute.java
Normal file
105
src/org/ice4j/attribute/XorMappedAddressAttribute.java
Normal file
@ -0,0 +1,105 @@
|
||||
/*
|
||||
* 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.*;
|
||||
|
||||
/**
|
||||
* The XOR-MAPPED-ADDRESS attribute is only present in Binding
|
||||
* Responses. It provides the same information that is present in the
|
||||
* MAPPED-ADDRESS attribute. However, the information is encoded by
|
||||
* performing an exclusive or (XOR) operation between the mapped address
|
||||
* and the transaction ID. Unfortunately, some NAT devices have been
|
||||
* found to rewrite binary encoded IP addresses and ports that are
|
||||
* present in protocol payloads. This behavior interferes with the
|
||||
* operation of STUN. By providing the mapped address in an obfuscated
|
||||
* form, STUN can continue to operate through these devices.
|
||||
*
|
||||
* The format of the XOR-MAPPED-ADDRESS is:
|
||||
*
|
||||
*
|
||||
* 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 | X-Port |
|
||||
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
* | X-Address (Variable)
|
||||
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
*
|
||||
* The Family represents the IP address family, and is encoded
|
||||
* identically to the Family in MAPPED-ADDRESS.
|
||||
*
|
||||
* X-Port is equal to the port in MAPPED-ADDRESS, exclusive or'ed with
|
||||
* most significant 16 bits of the transaction ID. If the IP address
|
||||
* family is IPv4, X-Address is equal to the IP address in MAPPED-
|
||||
* ADDRESS, exclusive or'ed with the most significant 32 bits of the
|
||||
* transaction ID. If the IP address family is IPv6, the X-Address is
|
||||
* equal to the IP address in MAPPED-ADDRESS, exclusive or'ed with the
|
||||
* entire 128 bit transaction ID.
|
||||
*
|
||||
* <p>Copyright: Copyright (c) 2005.</p>
|
||||
* <p>Organization: Network Research Team, Louis Pasteur University</p>
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
117
src/org/ice4j/attribute/XorOnlyAttribute.java
Normal file
117
src/org/ice4j/attribute/XorOnlyAttribute.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Organization: Net Research Team, Louis Pasteur University</p>
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
35
src/org/ice4j/attribute/XorPeerAddressAttribute.java
Normal file
35
src/org/ice4j/attribute/XorPeerAddressAttribute.java
Normal file
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
35
src/org/ice4j/attribute/XorRelayedAddressAttribute.java
Normal file
35
src/org/ice4j/attribute/XorRelayedAddressAttribute.java
Normal file
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
203
src/org/ice4j/ice/Agent.java
Normal file
203
src/org/ice4j/ice/Agent.java
Normal file
@ -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.
|
||||
* <p>
|
||||
* 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.
|
||||
* <p>
|
||||
*
|
||||
* @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<String, IceMediaStream> mediaStreams
|
||||
= new LinkedHashMap<String, IceMediaStream>();
|
||||
|
||||
/**
|
||||
* The candidate harvester that we use to gather candidate on the local
|
||||
* machine.
|
||||
*/
|
||||
private HostCandidateHarvester hostCandidateHarvester
|
||||
= new HostCandidateHarvester();
|
||||
|
||||
/**
|
||||
* We use the <tt>FoundationsRegistry</tt> to keep track of the foundations
|
||||
* we assign within a session (i.e. the entire life time of an
|
||||
* <tt>Agent</tt>)
|
||||
*/
|
||||
private FoundationsRegistry foundationsRegistry = new FoundationsRegistry();
|
||||
|
||||
/**
|
||||
* Creates an empty <tt>Agent</tt> with no streams, and no address
|
||||
*/
|
||||
public Agent()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new media stream and stores it
|
||||
*
|
||||
* @param mediaStreamName the name of the media stream
|
||||
*
|
||||
* @return a reference to the newly created <tt>IceMediaStream</tt>.
|
||||
*/
|
||||
public IceMediaStream createMediaStream(String mediaStreamName)
|
||||
{
|
||||
IceMediaStream mediaStream
|
||||
= new IceMediaStream(Agent.this, mediaStreamName);
|
||||
mediaStreams.put(mediaStreamName, mediaStream);
|
||||
|
||||
return mediaStream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@link Component} for the specified <tt>stream</tt> and
|
||||
* allocates all local candidates that should belong to it.
|
||||
*
|
||||
* @param stream the {@link IceMediaStream} that the new {@link Component}
|
||||
* should belong to.
|
||||
* @param transport the transport protocol used by the component
|
||||
* @param preferredPort the port number that should be tried first when
|
||||
* binding local <tt>Candidate</tt> sockets for this <tt>Component</tt>.
|
||||
* @param minPort the port number where we should first try to bind before
|
||||
* moving to the next one (i.e. <tt>minPort + 1</tt>)
|
||||
* @param maxPort the maximum port number where we should try binding
|
||||
* before giving up and throwinG an exception.
|
||||
*
|
||||
* @return the newly created {@link Component} and with a list containing
|
||||
* all and only local candidates.
|
||||
*
|
||||
* @throws IllegalArgumentException if either <tt>minPort</tt> or
|
||||
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort >
|
||||
* maxPort</tt>, or if <tt>transport</tt> is not currently supported.
|
||||
* @throws IOException if an error occurs while the underlying resolver lib
|
||||
* is using sockets.
|
||||
* @throws BindException if we couldn't find a free port between
|
||||
* <tt>minPort</tt> and <tt>maxPort</tt> before reaching the maximum allowed
|
||||
* number of retries.
|
||||
*/
|
||||
public Component createComponent( IceMediaStream stream,
|
||||
Transport transport,
|
||||
int preferredPort,
|
||||
int minPort,
|
||||
int maxPort)
|
||||
throws IllegalArgumentException,
|
||||
IOException,
|
||||
BindException
|
||||
{
|
||||
if(transport != Transport.UDP)
|
||||
throw new IllegalArgumentException("This implementation does not "
|
||||
+" currently support transport: " + transport);
|
||||
Component component = stream.createComponent(transport);
|
||||
|
||||
gatherCandidates(component, preferredPort, minPort, maxPort );
|
||||
return component;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses all <tt>CandidateHarvester</tt>s currently registered with this
|
||||
* <tt>Agent</tt> to obtain whatever addresses they can discover.
|
||||
* <p>
|
||||
* 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.
|
||||
* </p>
|
||||
* @param component the <tt>Component</tt> that we'd like to gather
|
||||
* candidates for.
|
||||
* @param preferredPort the port number that should be tried first when
|
||||
* binding local <tt>Candidate</tt> sockets for this <tt>Component</tt>.
|
||||
* @param minPort the port number where we should first try to bind before
|
||||
* moving to the next one (i.e. <tt>minPort + 1</tt>)
|
||||
* @param maxPort the maximum port number where we should try binding
|
||||
* before giving up and throwinG an exception.
|
||||
*
|
||||
* @throws IllegalArgumentException if either <tt>minPort</tt> or
|
||||
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort >
|
||||
* maxPort</tt>.
|
||||
* @throws IOException if an error occurs while the underlying resolver lib
|
||||
* is gathering candidates and we end up without even a single one.
|
||||
*/
|
||||
private void gatherCandidates( Component component,
|
||||
int preferredPort,
|
||||
int minPort,
|
||||
int maxPort)
|
||||
throws IllegalArgumentException,
|
||||
IOException
|
||||
{
|
||||
hostCandidateHarvester.harvest(
|
||||
component, preferredPort, minPort, maxPort);
|
||||
|
||||
//TODO: apply STUN and TURN harvesters now.
|
||||
|
||||
computeFoundations(component);
|
||||
|
||||
//make sure we compute priorities only after we have all candidates
|
||||
component.prioritizeCandidates();
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes and sets the foundations foundation for all <tt>Candidate</tt>s
|
||||
* currently found in <tt>component</tt>.
|
||||
*
|
||||
* @param component the component whose candidate foundations we'd like to
|
||||
* compute and assign.
|
||||
*/
|
||||
private void computeFoundations(Component component)
|
||||
{
|
||||
List<Candidate> candidates = component.getLocalCandidates();
|
||||
|
||||
for (Candidate cand : candidates)
|
||||
{
|
||||
foundationsRegistry.assignFoundation(cand);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes and sets the priorities for all <tt>Candidate</tt>s currently
|
||||
* found in <tt>component</tt>. This happens outside of the
|
||||
* <tt>Candidate</tt> class because some of the decisions made about the
|
||||
* priority of the candidates is made based on the number of candidates of
|
||||
* a certain type.
|
||||
*
|
||||
* @param component the component whose candidates we'd like to prioritize.
|
||||
*/
|
||||
private void computePriorities(Component component)
|
||||
{
|
||||
List<Candidate> candidates = component.getLocalCandidates();
|
||||
|
||||
for (Candidate cand : candidates)
|
||||
{
|
||||
cand.computePriority();
|
||||
}
|
||||
}
|
||||
}
|
||||
616
src/org/ice4j/ice/Candidate.java
Normal file
616
src/org/ice4j/ice/Candidate.java
Normal file
@ -0,0 +1,616 @@
|
||||
/*
|
||||
* 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.net.*;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
* A candidate represents a transport address that is a potential point of
|
||||
* contact for receipt of media. Candidates also have properties - their
|
||||
* type (server reflexive, relayed or host), priority, foundation,
|
||||
* and base.
|
||||
* <p>
|
||||
* 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.
|
||||
* </p>
|
||||
*
|
||||
* @author Emil Ivov
|
||||
*/
|
||||
public class Candidate
|
||||
{
|
||||
/**
|
||||
* The transport address represented by this candidate.
|
||||
*/
|
||||
private TransportAddress transportAddress = null;
|
||||
|
||||
/**
|
||||
* The type of this candidate. At this point the ICE specification (and
|
||||
* hence this implementation) only defines for candidate types: host,
|
||||
* server reflexive, peer reflexive and relayed candidates. Others may be
|
||||
* added in the future.
|
||||
*/
|
||||
private CandidateType candidateType = null;
|
||||
|
||||
/**
|
||||
* An arbitrary string that is the same for two candidates
|
||||
* that have the same type, base IP address, protocol (UDP, TCP,
|
||||
* etc.) and STUN or TURN server. If any of these are different then
|
||||
* the foundation will be different. Two candidate pairs with the
|
||||
* same foundation pairs are likely to have similar network
|
||||
* characteristics. Foundations are used in the frozen algorithm.
|
||||
*/
|
||||
private String foundation = null;
|
||||
|
||||
/**
|
||||
* The base of a server reflexive candidate is the host candidate
|
||||
* from which it was derived. A host candidate is also said to have
|
||||
* a base, equal to that candidate itself. Similarly, the base of a
|
||||
* relayed candidate is that candidate itself.
|
||||
*/
|
||||
private Candidate base = null;
|
||||
|
||||
/**
|
||||
* A unique priority number that MUST be a positive integer between 1 and
|
||||
* (2**32 - 1). This priority will be set and used by ICE algorithms to
|
||||
* determine the order of the connectivity checks and the relative
|
||||
* preference for candidates.
|
||||
*/
|
||||
private long priority = 0;
|
||||
|
||||
/**
|
||||
* Specifies whether the address associated with this candidate belongs to
|
||||
* a VPN interface. In many cases (e.g. when running on a 1.5 JVM) we won't
|
||||
* be able to determine whether an interface is virtual or not. If we are
|
||||
* however (that is when running a more recent JVM) we will reflect it in
|
||||
* this property.
|
||||
*/
|
||||
private boolean isVirtual = false;
|
||||
|
||||
/**
|
||||
* The component that this candidate was created for. Every candidate is
|
||||
* always associated with a specific component for which it is a candidate.
|
||||
*/
|
||||
private Component parentComponent = null;
|
||||
|
||||
/**
|
||||
* The address of the STUN server that was used to obtain this
|
||||
* <tt>Candidate</tt>. Will be <tt>null</tt> if this is not a server
|
||||
* reflexive candidate.
|
||||
*/
|
||||
private TransportAddress stunServerAddress = null;
|
||||
|
||||
/**
|
||||
* The address of the TURN server that was used to obtain this
|
||||
* <tt>Candidate</tt>. Will be <tt>null</tt> if this is not a relayed
|
||||
* candidate.
|
||||
*/
|
||||
private TransportAddress turnServerAddress = null;
|
||||
|
||||
/**
|
||||
* The address that our TURN/STUN server returned as mapped if this is a
|
||||
* relayed or a reflexive <tt>Candidate</tt>. Will remain <tt>null</tt> if
|
||||
* this is a host candidate.
|
||||
*/
|
||||
private TransportAddress mappedAddress = null;
|
||||
|
||||
/**
|
||||
* The maximum value for a candidate's type preference.
|
||||
*/
|
||||
public static final int MAX_TYPE_PREFERENCE = 126;
|
||||
|
||||
/**
|
||||
* The minimum value for a candidate's type preference.
|
||||
*/
|
||||
public static final int MIN_TYPE_PREFERENCE = 0;
|
||||
|
||||
/**
|
||||
* The maximum value for a candidate's local preference.
|
||||
*/
|
||||
public static final int MAX_LOCAL_PREFERENCE = 65535;
|
||||
|
||||
/**
|
||||
* The minimum value for a candidate's local preference.
|
||||
*/
|
||||
public static final int MIN_LOCAL_PREFERENCE = 0;
|
||||
|
||||
/**
|
||||
* Creates a candidate for the specified transport address and properties.
|
||||
*
|
||||
* @param transportAddress the transport address that this candidate is
|
||||
* encapsulating.
|
||||
* @param parentComponent the <tt>Component</tt> that this candidate
|
||||
* belongs to.
|
||||
* @param type the <tt>CandidateType</tt> for this <tt>Candidate</tt>.
|
||||
*/
|
||||
public Candidate(TransportAddress transportAddress,
|
||||
Component parentComponent,
|
||||
CandidateType type)
|
||||
{
|
||||
this.transportAddress = transportAddress;
|
||||
this.parentComponent = parentComponent;
|
||||
this.candidateType = type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the type of this candidate which should be an instance of the
|
||||
* {@link CandidateType} enumeration.
|
||||
*
|
||||
* @return a <tt>CandidateType</tt> indicating the type of this
|
||||
* <tt>Candidate</tt>.
|
||||
*/
|
||||
public CandidateType getType()
|
||||
{
|
||||
return candidateType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the type of this candidate which should be an instance of the
|
||||
* {@link CandidateType} enumeration.
|
||||
*
|
||||
* @param candidateType a <tt>CandidateType</tt> instance indicating the
|
||||
* type of this <tt>Candidate</tt>.
|
||||
*/
|
||||
public void setCandidateType(CandidateType candidateType)
|
||||
{
|
||||
this.candidateType = candidateType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a <tt>String</tt> containing the foundation of this
|
||||
* <tt>Candidate</tt>. A foundation is an arbitrary <tt>String</tt> that is
|
||||
* the same for candidates that have the same type, base IP address,
|
||||
* transport protocol (UDP, TCP, etc.) and STUN or TURN server. If any of
|
||||
* these are different then the foundation will be different. Two candidate
|
||||
* pairs with the same foundation pairs are likely to have similar network
|
||||
* characteristics. Typically, candidates for RTP and RTCP streams will
|
||||
* share the same foundation. Foundations are used in the frozen algorithm.
|
||||
*
|
||||
* @return the foundation of this <tt>Candidate</tt>.
|
||||
*/
|
||||
public String getFoundation()
|
||||
{
|
||||
return foundation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this <tt>Candidate</tt>'s foundation. A foundation is an arbitrary
|
||||
* string that is always the same for candidates that have the same type,
|
||||
* base IP address, protocol (UDP, TCP, etc.) and STUN or TURN server. If
|
||||
* any of these are different then the foundation will be different. Two
|
||||
* candidate pairs with the same foundation pairs are likely to have similar
|
||||
* network characteristics. Foundations are used in the frozen algorithm.
|
||||
*
|
||||
* @param foundation the foundation of this <tt>Candidate</tt>.
|
||||
*/
|
||||
public void setFoundation(String foundation)
|
||||
{
|
||||
this.foundation = foundation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns this <tt>Candidate</tt>'s base. The base of a server
|
||||
* reflexive candidate is the host candidate from which it was derived.
|
||||
* A host candidate is also said to have a base, equal to that candidate
|
||||
* itself. Similarly, the base of a relayed candidate is that candidate
|
||||
* itself.
|
||||
*
|
||||
* @return the base <tt>Candidate</tt> for this <tt>Candidate</tt>.
|
||||
*/
|
||||
public Candidate getBase()
|
||||
{
|
||||
return base;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this <tt>Candidate</tt>'s base. The base of a server
|
||||
* reflexive candidate is the host candidate from which it was derived.
|
||||
* A host candidate is also said to have a base, equal to that candidate
|
||||
* itself. Similarly, the base of a relayed candidate is that candidate
|
||||
* itself.
|
||||
*
|
||||
* @param base the base <tt>Candidate</tt> of this <tt>Candidate</tt>.
|
||||
*/
|
||||
public void setBase(Candidate base)
|
||||
{
|
||||
this.base = base;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the priority of this candidate. Priority is a unique priority
|
||||
* number that MUST be a positive integer between 1 and (2**32 - 1). This
|
||||
* priority will be set and used by ICE algorithms to determine the order
|
||||
* of the connectivity checks and the relative preference for candidates.
|
||||
*
|
||||
* @return a number between 1 and (2**32 - 1) indicating the priority of
|
||||
* this candidate.
|
||||
*/
|
||||
public long getPriority()
|
||||
{
|
||||
return priority;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the transport address that this candidate is representing.
|
||||
*
|
||||
* @return the TransportAddress encapsulated by this Candidate.
|
||||
*/
|
||||
public TransportAddress getTransportAddress()
|
||||
{
|
||||
return transportAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates whether some other Candidate is "equal to" this one. We
|
||||
* consider candidates equal when they are redundant, i.e.
|
||||
* <p>
|
||||
* @param obj the reference object with which to compare.
|
||||
* <p>
|
||||
* @return <code>true</code> if this <tt>Candidate</tt> is equal to the
|
||||
* obj argument; <code>false</code> otherwise.
|
||||
*
|
||||
* @throws java.lang.NullPointerException if <tt>obj</tt> 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 <tt>Component</tt> that this candidate belongs
|
||||
* to.
|
||||
*
|
||||
* @return a reference to the <tt>Component</tt> that this candidate belongs
|
||||
* to.
|
||||
*/
|
||||
public Component getParentComponent()
|
||||
{
|
||||
return parentComponent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the priority for this <tt>Candidate</tt> based on the procedures
|
||||
* defined in the ICE specification..
|
||||
*
|
||||
* @return the priority for this <tt>Candidate</tt> 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 <tt>0</tt> to <tt>126</tt>
|
||||
* inclusive, and represents the preference for the type of the candidate
|
||||
* (where the types are local, server reflexive, peer reflexive and
|
||||
* relayed). A <tt>126</tt> is the highest preference, and a <tt>0</tt> is
|
||||
* the lowest. Setting the value to a <tt>0</tt> 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 <tt>Candidate</tt> 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 <tt>Candidate</tt>
|
||||
* <p>
|
||||
* The local preference MUST be an integer from <tt>0</tt> to <tt>65535</tt>
|
||||
* inclusive. It represents a preference for the particular IP address from
|
||||
* which the candidate was obtained, in cases where an agent is multihomed.
|
||||
* <tt>65535</tt> represents the highest preference, and a zero, the lowest.
|
||||
* When there is only a single IP address, this value SHOULD be set to
|
||||
* <tt>65535</tt>. 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.
|
||||
* </p>
|
||||
* @return the local preference for this <tt>Candidate</tt>.
|
||||
*/
|
||||
private int getLocalPreference()
|
||||
{
|
||||
//The ICE spec says: When there is only a single IP address, this value
|
||||
//SHOULD be set to.
|
||||
if(getParentComponent().countLocalHostCandidates() < 2)
|
||||
return MAX_LOCAL_PREFERENCE;
|
||||
|
||||
//The ICE spec also says: Furthermore, if an agent is multi-homed and
|
||||
//has multiple IP addresses, the local preference for host candidates
|
||||
//from a VPN interface SHOULD have a priority of 0.
|
||||
if(isVirtual())
|
||||
return MIN_LOCAL_PREFERENCE;
|
||||
|
||||
|
||||
InetAddress addr = getTransportAddress().getInetAddress();
|
||||
|
||||
//the following tries to reusse precedence from RFC 3484 but that's a
|
||||
//bit tricky since it is not meant to be used exactly the way that
|
||||
//Johnnie seems to think.
|
||||
|
||||
//prefer IPv6 to IPv4
|
||||
if(addr instanceof Inet6Address)
|
||||
{
|
||||
//prefer link local addresses to global ones
|
||||
if(addr.isLinkLocalAddress())
|
||||
return 40;
|
||||
else
|
||||
return 30;
|
||||
}
|
||||
else
|
||||
{
|
||||
//IPv4
|
||||
return 10;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the address associated with this candidate belongs to
|
||||
* a VPN interface. In many cases (e.g. when running on a 1.5 JVM) we won't
|
||||
* be able to determine whether an interface is virtual or not. If we are
|
||||
* however (that is when running a more recent JVM) we will reflect it in
|
||||
* this property. Note that the <tt>isVirtual</tt> property is not really
|
||||
* an ICE concept. The ICE specs only mention it and give basic guidelines
|
||||
* as to how it should be handled so other implementations maybe dealing
|
||||
* with it differently.
|
||||
*
|
||||
* @return <tt>true</tt> if we were able to determine that the address
|
||||
* associated with this <tt>Candidate</tt> comes from a virtual interface
|
||||
* and <tt>false</tt> if otherwise.
|
||||
*/
|
||||
public boolean isVirtual()
|
||||
{
|
||||
return isVirtual;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies whether the address associated with this candidate belongs to
|
||||
* a VPN interface. In many cases (e.g. when running on a 1.5 JVM) we won't
|
||||
* be able to determine whether an interface is virtual or not. If we are
|
||||
* however (that is when running a more recent JVM) we will reflect it in
|
||||
* this property. Note that the <tt>isVirtual</tt> property is not really
|
||||
* an ICE concept. The ICE specs only mention it and give basic guidelines
|
||||
* as to how it should be handled so other implementations maybe dealing
|
||||
* with it differently.
|
||||
*
|
||||
* @param isVirtual <tt>true</tt> if we were able to determine that the
|
||||
* address associated with this <tt>Candidate</tt> comes from a virtual
|
||||
* interface and <tt>false</tt> if otherwise.
|
||||
*/
|
||||
public void setVirtual(boolean isVirtual)
|
||||
{
|
||||
this.isVirtual = isVirtual;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the address of the STUN server that was used to obtain this
|
||||
* <tt>Candidate</tt> or <tt>null</tt> if this is not a server reflexive
|
||||
* candidate.
|
||||
*
|
||||
* @return the address of the STUN server that was used to obtain this
|
||||
* <tt>Candidate</tt> or <tt>null</tt> if this is not a server reflexive
|
||||
* candidate.
|
||||
*/
|
||||
public TransportAddress getStunServerAddress()
|
||||
{
|
||||
return stunServerAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the address of the STUN server that was used to obtain this
|
||||
* <tt>Candidate</tt>. Only makes sense if this is a relayed candidate.
|
||||
*
|
||||
* @param address the address of the STUN server that was used to obtain
|
||||
* this <tt>Candidate</tt> or <tt>null</tt> if this is not a server
|
||||
* reflexive candidate.
|
||||
*/
|
||||
protected void setStunServerAddress(TransportAddress address)
|
||||
{
|
||||
this.stunServerAddress = address;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the address of the TURN server that was used to obtain this
|
||||
* <tt>Candidate</tt> or <tt>null</tt> if this is not a relayed candidate.
|
||||
*
|
||||
* @return the address of the TURN server that was used to obtain this
|
||||
* <tt>Candidate</tt> or <tt>null</tt> if this is not a relayed candidate.
|
||||
*/
|
||||
public TransportAddress getTurnServerAddress()
|
||||
{
|
||||
return turnServerAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the address of the TURN server that was used to obtain this
|
||||
* <tt>Candidate</tt>. Only makes sense if this is a relayed candidate.
|
||||
*
|
||||
* @param address the address of the TURN server that was used to obtain
|
||||
* this <tt>Candidate</tt> or <tt>null</tt> if this is not a relayed
|
||||
* candidate.
|
||||
*/
|
||||
protected void setTurnServerAddress(TransportAddress address)
|
||||
{
|
||||
this.turnServerAddress = address;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the address that was returned to us a "mapped address" from a
|
||||
* TURN or a STUN server in case this <tt>Candidate</tt> is relayed or
|
||||
* reflexive and <tt>null</tt> otherwise. Note that the address returned by
|
||||
* this method would be equal to the transport address for reflexive
|
||||
* <tt>Candidate</tt>s but not for relayed ones.
|
||||
*
|
||||
* @return the address that our TURN/STUN server returned as mapped if this
|
||||
* is a relayed or a reflexive <tt>Candidate</tt> or <tt>null</tt> if this
|
||||
* is a host candidate.
|
||||
*/
|
||||
public TransportAddress getMappedAddress()
|
||||
{
|
||||
return mappedAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the address that was returned to us a "mapped address" from a
|
||||
* TURN or a STUN server in case this <tt>Candidate</tt> is relayed.
|
||||
*
|
||||
* @param address the address that our TURN/STUN server returned as mapped
|
||||
* if this is a relayed or a reflexive <tt>Candidate</tt>.
|
||||
*/
|
||||
protected void setMappedAddress(TransportAddress address)
|
||||
{
|
||||
this.turnServerAddress = address;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the <tt>Transport</tt> for this <tt>Candidate</tt>. This is a
|
||||
* convenience method only and it is equivalent to retrieving the transport
|
||||
* of this <tt>Candidate</tt>'s transport address.
|
||||
*
|
||||
* @return the <tt>Transport</tt> that this <tt>Candidate</tt> was obtained
|
||||
* for/with.
|
||||
*/
|
||||
public Transport getTransport()
|
||||
{
|
||||
return getTransportAddress().getTransport();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a <tt>TransportAddress</tt> related to this <tt>Candidate</tt>.
|
||||
* Related addresses are present for server reflexive, peer reflexive and
|
||||
* relayed candidates. If a candidate is server or peer reflexive,
|
||||
* the related address is equal to the base of this <tt>Candidate</tt>.
|
||||
* If the candidate is relayed, the returned address is equal to the mapped
|
||||
* address. If the candidate is a host candidate then the method returns
|
||||
* <tt>null</tt>.
|
||||
*
|
||||
* @return the <tt>TransportAddress</tt> of the base if this is a reflexive
|
||||
* candidate, the mapped address in the case of a relayed candidate, and
|
||||
* <tt>null</tt> if this is a host candidate.
|
||||
*/
|
||||
public TransportAddress getRelatedAddress()
|
||||
{
|
||||
if ( getType () == CandidateType.SERVER_REFLEXIVE_CANDIDATE
|
||||
|| getType () == CandidateType.PEER_REFLEXIVE_CANDIDATE)
|
||||
{
|
||||
return getBase().getTransportAddress();
|
||||
}
|
||||
else if ( getType () == CandidateType.RELAYED_CANDIDATE)
|
||||
{
|
||||
return getMappedAddress();
|
||||
}
|
||||
else
|
||||
{
|
||||
//host candidate
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a <tt>String</tt> representation of this <tt>Candidate</tt>
|
||||
* containing its <tt>TransportAddress</tt>, base, foundation, priority and
|
||||
* whatever other properties may be relevant.
|
||||
*
|
||||
* @return a <tt>String</tt> representation of this <tt>Candidate</tt>.
|
||||
*/
|
||||
public String toString()
|
||||
{
|
||||
StringBuffer buff
|
||||
= new StringBuffer("candidate: ");
|
||||
|
||||
buff.append(" ").append(getFoundation());
|
||||
buff.append(" ").append(getParentComponent().getComponentID());
|
||||
buff.append(" ").append(getTransport());
|
||||
buff.append(" ").append(getPriority());
|
||||
buff.append(" ").append(getTransportAddress().getHostAddress());
|
||||
buff.append(" ").append(getTransportAddress().getPort());
|
||||
buff.append(" typ ").append(getType());
|
||||
|
||||
TransportAddress relAddr = getRelatedAddress();
|
||||
|
||||
if(relAddr != null)
|
||||
{
|
||||
buff.append(" raddr ").append(relAddr.getHostAddress());
|
||||
buff.append(" rport ").append(relAddr.getPort());
|
||||
}
|
||||
|
||||
return buff.toString();
|
||||
}
|
||||
|
||||
}
|
||||
80
src/org/ice4j/ice/CandidateType.java
Normal file
80
src/org/ice4j/ice/CandidateType.java
Normal file
@ -0,0 +1,80 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* According to the ICE specification, Candidates have a type property which
|
||||
* makes them server reflexive, peer reflexive, relayed or host).
|
||||
*
|
||||
* @author Emil Ivov
|
||||
*/
|
||||
public enum CandidateType
|
||||
{
|
||||
/**
|
||||
* Peer Reflexive Candidate: A candidate whose IP address and port are
|
||||
* a binding allocated by a NAT for an agent when it sent a STUN
|
||||
* Binding Request through the NAT to its peer.
|
||||
*/
|
||||
PEER_REFLEXIVE_CANDIDATE("prflx"),
|
||||
|
||||
/**
|
||||
* A Server Reflexive Candidate is a candidate whose IP address and port
|
||||
* are a binding allocated by a NAT for an agent when it sent a
|
||||
* packet through the NAT to a server. Server reflexive candidates
|
||||
* can be learned by STUN servers using the Binding Request, or TURN
|
||||
* servers, which provides both a Relayed and Server Reflexive
|
||||
* candidate.
|
||||
*/
|
||||
SERVER_REFLEXIVE_CANDIDATE("srflx"),
|
||||
|
||||
/**
|
||||
* A Relayed Candidate is a candidate obtained by sending a TURN Allocate
|
||||
* request from a host candidate to a TURN server. The relayed candidate is
|
||||
* resident on the TURN server, and the TURN server relays packets back
|
||||
* towards the agent.
|
||||
*/
|
||||
RELAYED_CANDIDATE("relay"),
|
||||
|
||||
/**
|
||||
* A candidate obtained by binding to a specific port
|
||||
* from an interface on the host. This includes both physical
|
||||
* interfaces and logical ones, such as ones obtained through Virtual
|
||||
* Private Networks (VPNs) and Realm Specific IP (RSIP) [RFC3102]
|
||||
* (which lives at the operating system level).
|
||||
*/
|
||||
HOST_CANDIDATE("host");
|
||||
|
||||
/**
|
||||
* The name of this <tt>CandidateType</tt> instance.
|
||||
*/
|
||||
private final String typeName;
|
||||
|
||||
/**
|
||||
* Creates a <tt>CandidateType</tt> instance with the specified name.
|
||||
*
|
||||
* @param typeName the name of the <tt>CandidateType</tt> instance we'd
|
||||
* like to create.
|
||||
*/
|
||||
private CandidateType(String typeName)
|
||||
{
|
||||
this.typeName = typeName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of this <tt>CandidateType</tt> (e.g. "host", "prflx",
|
||||
* "srflx", or "relay").
|
||||
*
|
||||
* @return the name of this <tt>Transport</tt> (e.g. "udp" or
|
||||
* "tcp").
|
||||
*/
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return typeName;
|
||||
}
|
||||
}
|
||||
353
src/org/ice4j/ice/Component.java
Normal file
353
src/org/ice4j/ice/Component.java
Normal file
@ -0,0 +1,353 @@
|
||||
/*
|
||||
* 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.util.*;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
* A component is a piece of a media stream requiring a single transport
|
||||
* address; a media stream may require multiple components, each of which has
|
||||
* to work for the media stream as a whole to work. For media streams based on
|
||||
* RTP, there are two components per media stream - one for RTP, and one for
|
||||
* RTCP.
|
||||
* <p>
|
||||
*
|
||||
* @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 <tt>IceMediaStream</tt> that this <tt>Component</tt> belongs to.
|
||||
*/
|
||||
private final IceMediaStream parentStream;
|
||||
|
||||
/**
|
||||
* The list locally gathered candidates for this media stream.
|
||||
*/
|
||||
private List<Candidate> localCandidates = new LinkedList<Candidate>();
|
||||
|
||||
/**
|
||||
* The list of candidates that the peer agent sent for this stream.
|
||||
*/
|
||||
private List<Candidate> remoteCandidates = new LinkedList<Candidate>();
|
||||
|
||||
/**
|
||||
* Creates a new <tt>Component</tt> with the specified <tt>componentID</tt>
|
||||
* as a child of the specified <tt>MediaStream</tt>.
|
||||
*
|
||||
* @param componentID the id of this component.
|
||||
* @param transport the protocol that this component will be using (e.g.
|
||||
* TCP/UDP/TLS/DTLS).
|
||||
* @param mediaStream the {@link IceMediaStream} instance that would be the
|
||||
* parent of this component.
|
||||
*/
|
||||
protected Component(int componentID,
|
||||
Transport transport,
|
||||
IceMediaStream mediaStream)
|
||||
{
|
||||
// the max value for componentID is 256
|
||||
this.componentID = componentID;
|
||||
this.transport = transport;
|
||||
this.parentStream = mediaStream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a local candidate to this component.
|
||||
*
|
||||
* @param candidate the candidate object to be added
|
||||
*/
|
||||
public void addLocalCandidate(Candidate candidate)
|
||||
{
|
||||
synchronized(localCandidates)
|
||||
{
|
||||
localCandidates.add(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a copy of the list containing all local candidates currently
|
||||
* registered in this component.
|
||||
*
|
||||
* @return Returns a copy of the list containing all local candidates
|
||||
* currently registered in this <tt>Component</tt>.
|
||||
*/
|
||||
public List<Candidate> getLocalCandidates()
|
||||
{
|
||||
synchronized(localCandidates)
|
||||
{
|
||||
return new ArrayList<Candidate>(localCandidates);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of local host candidates currently registered in this
|
||||
* <tt>Component</tt>.
|
||||
*
|
||||
* @return the number of local host candidates currently registered in this
|
||||
* <tt>Component</tt>.
|
||||
*/
|
||||
public int countLocalHostCandidates()
|
||||
{
|
||||
synchronized(localCandidates)
|
||||
{
|
||||
int count = 0;
|
||||
for(Candidate cand : localCandidates)
|
||||
{
|
||||
if (cand.getType() == CandidateType.HOST_CANDIDATE
|
||||
&& !cand.isVirtual())
|
||||
{
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of all local candidates currently registered in this
|
||||
* <tt>Component</tt>.
|
||||
*
|
||||
* @return the number of all local candidates currently registered in this
|
||||
* <tt>Component</tt>.
|
||||
*/
|
||||
public int countLocalCandidates()
|
||||
{
|
||||
synchronized(localCandidates)
|
||||
{
|
||||
return localCandidates.size();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a remote <tt>Candidate</tt>s to this media-stream
|
||||
* <tt>Component</tt>.
|
||||
*
|
||||
* @param candidate the <tt>Candidate</tt> instance to add.
|
||||
*/
|
||||
public void addRemoteCandidate(Candidate candidate)
|
||||
{
|
||||
synchronized(remoteCandidates)
|
||||
{
|
||||
remoteCandidates.add(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a copy of the list containing all remote candidates currently
|
||||
* registered in this component.
|
||||
*
|
||||
* @return Returns a copy of the list containing all remote candidates
|
||||
* currently registered in this <tt>Component</tt>.
|
||||
*/
|
||||
public List<Candidate> getRemoteCandidates()
|
||||
{
|
||||
synchronized(remoteCandidates)
|
||||
{
|
||||
return new ArrayList<Candidate>(remoteCandidates);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a list of local <tt>Candidate</tt>s to this media-stream component.
|
||||
*
|
||||
* @param candidates a <tt>List</tt> of candidates to be added
|
||||
*/
|
||||
public void addLocalCandidates(List<Candidate> candidates)
|
||||
{
|
||||
synchronized(localCandidates)
|
||||
{
|
||||
localCandidates.addAll(candidates);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a List of remote <tt>Candidate</tt>s as reported by a remote agent.
|
||||
*
|
||||
* @param candidates the <tt>List</tt> of <tt>Candidate</tt>s reported by
|
||||
* the remote agent for this component.
|
||||
*/
|
||||
public void addRemoteCandidates(List<Candidate> candidates)
|
||||
{
|
||||
synchronized(remoteCandidates)
|
||||
{
|
||||
remoteCandidates.addAll(candidates);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of all remote candidates currently registered in this
|
||||
* <tt>Component</tt>.
|
||||
*
|
||||
* @return the number of all remote candidates currently registered in this
|
||||
* <tt>Component</tt>.
|
||||
*/
|
||||
public int countRemoteCandidates()
|
||||
{
|
||||
synchronized(remoteCandidates)
|
||||
{
|
||||
return remoteCandidates.size();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a reference to the <tt>IceMediaStream</tt> that this
|
||||
* <tt>Component</tt> belongs to.
|
||||
*
|
||||
* @return a reference to the <tt>IceMediaStream</tt> that this
|
||||
* <tt>Component</tt> belongs to.
|
||||
*/
|
||||
public IceMediaStream getParentStream()
|
||||
{
|
||||
return parentStream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the ID of this <tt>Component</tt>. For RTP/RTCP flows this would
|
||||
* be <tt>1</tt> for RTP and 2 for <tt>RTCP</tt>.
|
||||
*
|
||||
* @return the ID of this <tt>Component</tt>.
|
||||
*/
|
||||
public int getComponentID()
|
||||
{
|
||||
return componentID;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the transport protocol of this component
|
||||
*
|
||||
* @return a {@link Transport} instance representing the the transport
|
||||
* protocol that this media stream <tt>Component</tt> uses.
|
||||
*/
|
||||
public Transport getTransport()
|
||||
{
|
||||
return transport;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a <tt>String</tt> representation of this <tt>Component</tt>
|
||||
* containing its ID, parent stream name and any existing candidates.
|
||||
*
|
||||
* @return a <tt>String</tt> representation of this <tt>Component</tt>
|
||||
* containing its ID, parent stream name and any existing candidates.
|
||||
*/
|
||||
public String toString()
|
||||
{
|
||||
StringBuffer buff
|
||||
= new StringBuffer("Component id=").append(getComponentID());
|
||||
|
||||
buff.append(" parent stream=" + getParentStream().getName());
|
||||
|
||||
//local candidates
|
||||
int localCandidatesCount = countLocalCandidates();
|
||||
|
||||
if(localCandidatesCount > 0)
|
||||
{
|
||||
buff.append("\n" + localCandidatesCount + " local candidates:");
|
||||
|
||||
synchronized(localCandidates)
|
||||
{
|
||||
for (Candidate cand : localCandidates)
|
||||
{
|
||||
buff.append("\n" + cand.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
buff.append("\nno local candidates.");
|
||||
}
|
||||
|
||||
//remote candidates
|
||||
int remoteCandidatesCount = countRemoteCandidates();
|
||||
|
||||
if(remoteCandidatesCount > 0)
|
||||
{
|
||||
buff.append("\n" + remoteCandidatesCount + " rocal candidates:");
|
||||
|
||||
synchronized(remoteCandidates)
|
||||
{
|
||||
for (Candidate cand : remoteCandidates)
|
||||
{
|
||||
buff.append("\n" + cand.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
buff.append("\nno remote candidates.");
|
||||
}
|
||||
|
||||
return buff.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void prioritizeCandidates()
|
||||
{
|
||||
//Arrays.sort
|
||||
/*
|
||||
synchronized(localCandidates)
|
||||
{
|
||||
TreeSet<Candidate> prioritizedCands = new TreeSet<Candidate>(new Comparator<Candidate>()
|
||||
{
|
||||
public int compare(Candidate c1, Candidate c2)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
public boolean equal(Candidate c1, Candidate c2)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
for (Candidate cand : localCandidates)
|
||||
{
|
||||
cand.computePriority();
|
||||
prioritizedCands.add(cand);
|
||||
}
|
||||
|
||||
localCandidates.clear();
|
||||
localCandidates.addAll(prioritizedCands);
|
||||
}
|
||||
*/
|
||||
}
|
||||
}
|
||||
93
src/org/ice4j/ice/FoundationsRegistry.java
Normal file
93
src/org/ice4j/ice/FoundationsRegistry.java
Normal file
@ -0,0 +1,93 @@
|
||||
/*
|
||||
* 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.util.*;
|
||||
|
||||
/**
|
||||
* We <tt>FoundationsRegistry</tt>s to keep track of and generate new
|
||||
* foundations within the lifetime of a single <tt>Agent</tt>.
|
||||
*
|
||||
* @author Emil Ivov
|
||||
*/
|
||||
public class FoundationsRegistry
|
||||
{
|
||||
/**
|
||||
* The foundation number that was last assigned to a <tt>Candidate</tt>
|
||||
*/
|
||||
private int lastAssignedFoundation = 0;
|
||||
|
||||
/**
|
||||
* Contains mappings between a type+baseIP+server+transport
|
||||
* <tt>String</tt>s and the foundation that has been assigned to them.
|
||||
*/
|
||||
private Map<String, String> foundations = new Hashtable<String, String>();
|
||||
|
||||
/**
|
||||
* Assigns to <tt>candidate</tt> the foundation that corresponds to its
|
||||
* bas type and transport properties or a new one if no foundation has been
|
||||
* generated yet for the specific combination.
|
||||
*
|
||||
* @param candidate the <tt>Candidate</tt> that we'd like to assign a
|
||||
* foundation to.
|
||||
*/
|
||||
public void assignFoundation(Candidate candidate)
|
||||
{
|
||||
//create the foundation key String
|
||||
String type = candidate.getType().toString();
|
||||
String base
|
||||
= candidate.getBase().getTransportAddress().getHostAddress();
|
||||
String server = null;
|
||||
|
||||
if(candidate.getType()
|
||||
== CandidateType.SERVER_REFLEXIVE_CANDIDATE
|
||||
|| candidate.getType() == CandidateType.RELAYED_CANDIDATE)
|
||||
{
|
||||
server = candidate.getStunServerAddress().getHostAddress();
|
||||
}
|
||||
|
||||
String transport = candidate.getTransport().toString();
|
||||
|
||||
StringBuffer foundationStringBuff = new StringBuffer(type);
|
||||
foundationStringBuff.append(base);
|
||||
if(server != null)
|
||||
foundationStringBuff.append(server);
|
||||
|
||||
foundationStringBuff.append(transport);
|
||||
|
||||
String foundationString = foundationStringBuff.toString();
|
||||
|
||||
String foundationValue = null;
|
||||
synchronized(foundations)
|
||||
{
|
||||
foundationValue = foundations.get(foundationString);
|
||||
|
||||
//obtain a new foundation number if we don't have one for this kind
|
||||
//of candidates.
|
||||
if(foundationValue == null)
|
||||
{
|
||||
foundationValue = Integer.toString(++lastAssignedFoundation);
|
||||
foundations.put(foundationString, foundationValue);
|
||||
}
|
||||
}
|
||||
|
||||
candidate.setFoundation(foundationValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of foundation <tt>String</tt>s that are currently
|
||||
* tracked by the registry.
|
||||
*
|
||||
* @return the number of foundation <tt>String</tt>s that are currently
|
||||
* tracked by this registry.
|
||||
*/
|
||||
public int size()
|
||||
{
|
||||
return foundations.size();
|
||||
}
|
||||
}
|
||||
66
src/org/ice4j/ice/HostCandidate.java
Normal file
66
src/org/ice4j/ice/HostCandidate.java
Normal file
@ -0,0 +1,66 @@
|
||||
/*
|
||||
* 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.net.*;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
* <tt>HostCandidate</tt>s are obtained by binding to a specific port from an
|
||||
* IP address on the host that is running us. This includes IP addresses on
|
||||
* physical interfaces and logical ones, such as ones obtained through
|
||||
* Virtual Private Networks (VPNs), Mobile IPv6, Realm Specific IP (RSIP) etc.
|
||||
* <p>
|
||||
* 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.
|
||||
* </p>
|
||||
*
|
||||
* @author Emil Ivov
|
||||
*/
|
||||
public class HostCandidate extends Candidate
|
||||
{
|
||||
|
||||
/**
|
||||
* If this is a local candidate the field contains the socket that is
|
||||
* actually associated with the candidate.
|
||||
*/
|
||||
private DatagramSocket socket = null;
|
||||
|
||||
/**
|
||||
* Creates a HostCandidate for the specified transport address.
|
||||
*
|
||||
* @param socket the {@link DatagramSocket} that communication associated
|
||||
* with this <tt>Candidate</tt> will be going through.
|
||||
* @param parentComponent the <tt>Component</tt> that this candidate
|
||||
* belongs to.
|
||||
*/
|
||||
public HostCandidate(DatagramSocket socket,
|
||||
Component parentComponent)
|
||||
{
|
||||
super(new TransportAddress(socket.getLocalAddress(),
|
||||
socket.getLocalPort()),
|
||||
parentComponent,
|
||||
CandidateType.HOST_CANDIDATE);
|
||||
|
||||
this.socket = socket;
|
||||
setBase(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the <tt>DatagramSocket</tt> associated with this candidate.
|
||||
*
|
||||
* @return the <tt>DatagramSocket</tt> associated with this candidate.
|
||||
*/
|
||||
public DatagramSocket getSocket()
|
||||
{
|
||||
return socket;
|
||||
}
|
||||
}
|
||||
109
src/org/ice4j/ice/IceMediaStream.java
Normal file
109
src/org/ice4j/ice/IceMediaStream.java
Normal file
@ -0,0 +1,109 @@
|
||||
/*
|
||||
* 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.util.*;
|
||||
import java.util.logging.*;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
* The class represents a media stream from the ICE perspective, i.e. a
|
||||
* collection of components.
|
||||
*
|
||||
* @author Emil Ivov
|
||||
* @author Namal Senarathne
|
||||
*/
|
||||
public class IceMediaStream
|
||||
{
|
||||
/**
|
||||
* Our class logger.
|
||||
*/
|
||||
private static final Logger logger =
|
||||
Logger.getLogger(IceMediaStream.class.getName());
|
||||
|
||||
/**
|
||||
* The name of this media stream. The name is equal to the value specified
|
||||
* in the SDP description.
|
||||
*/
|
||||
private final String name;
|
||||
|
||||
/**
|
||||
* Returns the list of components that this media stream consists of. A
|
||||
* component is a piece of a media stream requiring a single transport
|
||||
* address; a media stream may require multiple components, each of which
|
||||
* has to work for the media stream as a whole to work.
|
||||
*/
|
||||
private final LinkedHashMap<Integer, Component> components
|
||||
= new LinkedHashMap<Integer, Component>();
|
||||
|
||||
/**
|
||||
* The id that was last assigned to a component. The next id that we give
|
||||
* to a component would be lastComponendID + 1;
|
||||
*/
|
||||
private int lastComponentID = 0;
|
||||
|
||||
/**
|
||||
* The agent that this media stream belongs to.
|
||||
*/
|
||||
private final Agent parentAgent;
|
||||
|
||||
/**
|
||||
* Initializes a new <tt>IceMediaStream</tt> object.
|
||||
*
|
||||
* @param name the name of the media stream
|
||||
* @param parentAgent the agent that is handling the session that this
|
||||
* media stream is a part of
|
||||
*/
|
||||
protected IceMediaStream(Agent parentAgent, String name)
|
||||
{
|
||||
this.name = name;
|
||||
this.parentAgent = parentAgent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and adds a component to this media-stream
|
||||
* The component ID is incremented to the next integer value
|
||||
* when creating the component so make sure you keep that in mind in case
|
||||
* assigning a specific component ID is important to you.
|
||||
*
|
||||
* @param transport the transport protocol used by the component
|
||||
*
|
||||
* @return the newly created stream <tt>Component</tt> after adding it to
|
||||
* the stream first.
|
||||
*/
|
||||
protected Component createComponent(Transport transport)
|
||||
{
|
||||
lastComponentID ++;
|
||||
|
||||
Component component = new Component(lastComponentID, transport, this);
|
||||
components.put(new Integer(lastComponentID), component);
|
||||
|
||||
return component;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of this <tt>IceMediaStream</tt>.
|
||||
*
|
||||
* @return the name of this <tt>IceMediaStream</tt>.
|
||||
*/
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a <tt>String</tt> representation of this media stream.
|
||||
*
|
||||
* @return a <tt>String</tt> representation of this media stream.
|
||||
*/
|
||||
public String toString()
|
||||
{
|
||||
return "media stream:" + getName();
|
||||
}
|
||||
}
|
||||
492
src/org/ice4j/ice/NetworkUtils.java
Normal file
492
src/org/ice4j/ice/NetworkUtils.java
Normal file
@ -0,0 +1,492 @@
|
||||
/*
|
||||
* 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.lang.reflect.*;
|
||||
import java.net.*;
|
||||
import java.util.*;
|
||||
import java.util.logging.*;
|
||||
|
||||
/**
|
||||
* Utility methods and fields to use when working with network addresses.
|
||||
*
|
||||
* @author Emil Ivov
|
||||
* @author Damian Minkov
|
||||
* @author Vincent Lucas
|
||||
* @author Alan Kelly
|
||||
*/
|
||||
public class NetworkUtils
|
||||
{
|
||||
/**
|
||||
* Our class logger
|
||||
*/
|
||||
private static final Logger logger
|
||||
= Logger.getLogger(NetworkUtils.class.getName());
|
||||
|
||||
/**
|
||||
* A string containing the "any" local address for IPv6.
|
||||
*/
|
||||
public static final String IN6_ADDR_ANY = "::0";
|
||||
|
||||
/**
|
||||
* A string containing the "any" local address for IPv4.
|
||||
*/
|
||||
public static final String IN4_ADDR_ANY = "0.0.0.0";
|
||||
|
||||
/**
|
||||
* A string containing the "any" local address.
|
||||
*/
|
||||
public static final String IN_ADDR_ANY = determineAnyAddress();
|
||||
|
||||
/**
|
||||
* The maximum int value that could correspond to a port nubmer.
|
||||
*/
|
||||
public static final int MAX_PORT_NUMBER = 65535;
|
||||
|
||||
/**
|
||||
* The minimum int value that could correspond to a port nubmer bindable
|
||||
* by the SIP Communicator.
|
||||
*/
|
||||
public static final int MIN_PORT_NUMBER = 1024;
|
||||
|
||||
|
||||
/**
|
||||
* The random port number generator that we use in getRandomPortNumer()
|
||||
*/
|
||||
private static Random portNumberGenerator = new Random();
|
||||
|
||||
/**
|
||||
* Determines whether the address is the result of windows auto configuration.
|
||||
* (i.e. One that is in the 169.254.0.0 network)
|
||||
* @param add the address to inspect
|
||||
* @return true if the address is autoconfigured by windows, false otherwise.
|
||||
*/
|
||||
public static boolean isWindowsAutoConfiguredIPv4Address(InetAddress add)
|
||||
{
|
||||
return (add.getAddress()[0] & 0xFF) == 169
|
||||
&& (add.getAddress()[1] & 0xFF) == 254;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the address is an IPv4 link local address. IPv4 link
|
||||
* local addresses are those in the following networks:
|
||||
*
|
||||
* 10.0.0.0 to 10.255.255.255
|
||||
* 172.16.0.0 to 172.31.255.255
|
||||
* 192.168.0.0 to 192.168.255.255
|
||||
*
|
||||
* @param add the address to inspect
|
||||
* @return true if add is a link local ipv4 address and false if not.
|
||||
*/
|
||||
public static boolean isLinkLocalIPv4Address(InetAddress add)
|
||||
{
|
||||
if (add instanceof Inet4Address)
|
||||
{
|
||||
byte address[] = add.getAddress();
|
||||
if ( (address[0] & 0xFF) == 10)
|
||||
return true;
|
||||
if ( (address[0] & 0xFF) == 172
|
||||
&& (address[1] & 0xFF) >= 16 && address[1] <= 31)
|
||||
return true;
|
||||
if ( (address[0] & 0xFF) == 192
|
||||
&& (address[1] & 0xFF) == 168)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a random local port number that user applications could bind to.
|
||||
* (i.e. above 1024).
|
||||
* @return a random int located between 1024 and 65 535.
|
||||
*/
|
||||
public static int getRandomPortNumber()
|
||||
{
|
||||
return getRandomPortNumber(MIN_PORT_NUMBER, MAX_PORT_NUMBER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a random local port number, greater than min and lower than max.
|
||||
*
|
||||
* @param min the minimum allowed value for the returned port number.
|
||||
* @param max the maximum allowed value for the returned port number.
|
||||
*
|
||||
* @return a random int located between greater than min and lower than max.
|
||||
*/
|
||||
public static int getRandomPortNumber(int min, int max)
|
||||
{
|
||||
return portNumberGenerator.nextInt(max - min) + min;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a random local port number, greater than min and lower than max.
|
||||
* If the pair flag is set to true, then the returned port number is
|
||||
* guaranteed to be pair. This is useful for protocols that require this
|
||||
* such as RTP
|
||||
*
|
||||
* @param min the minimum allowed value for the returned port number.
|
||||
* @param max the maximum allowed value for the returned port number.
|
||||
* @param pair specifies whether the caller would like the returned port to
|
||||
* be pair.
|
||||
*
|
||||
* @return a random int located between greater than min and lower than max.
|
||||
*/
|
||||
public static int getRandomPortNumber(int min, int max, boolean pair)
|
||||
{
|
||||
if(pair)
|
||||
{
|
||||
int delta = max - min;
|
||||
delta /= 2;
|
||||
int port = getRandomPortNumber(min, min + delta);
|
||||
return port * 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
return getRandomPortNumber(min, max);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies whether <tt>address</tt> could be an IPv4 address string.
|
||||
*
|
||||
* @param address the String that we'd like to determine as an IPv4 address.
|
||||
*
|
||||
* @return true if the address contained by <tt>address</tt> is an IPv4
|
||||
* address and false otherwise.
|
||||
*/
|
||||
public static boolean isIPv4Address(String address)
|
||||
{
|
||||
return sun.net.util.IPAddressUtil.isIPv4LiteralAddress(address);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies whether <tt>address</tt> could be an IPv6 address string.
|
||||
*
|
||||
* @param address the String that we'd like to determine as an IPv6 address.
|
||||
*
|
||||
* @return true if the address contained by <tt>address</tt> is an IPv6
|
||||
* address and false otherwise.
|
||||
*/
|
||||
public static boolean isIPv6Address(String address)
|
||||
{
|
||||
return sun.net.util.IPAddressUtil.isIPv6LiteralAddress(address);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether <tt>address</tt> is a valid IP address string.
|
||||
*
|
||||
* @param address the address that we'd like to check
|
||||
* @return true if address is an IPv4 or IPv6 address and false otherwise.
|
||||
*/
|
||||
public static boolean isValidIPAddress(String address)
|
||||
{
|
||||
// empty string
|
||||
if (address == null || address.length() == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// look for IPv6 brackets and remove brackets for parsing
|
||||
boolean ipv6Expected = false;
|
||||
if (address.charAt(0) == '[')
|
||||
{
|
||||
// This is supposed to be an IPv6 literal
|
||||
if (address.length() > 2
|
||||
&& address.charAt(address.length() - 1) == ']')
|
||||
{
|
||||
// remove brackets from IPv6
|
||||
address = address.substring(1, address.length() - 1);
|
||||
ipv6Expected = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// look for IP addresses
|
||||
if (Character.digit(address.charAt(0), 16) != -1
|
||||
|| (address.charAt(0) == ':'))
|
||||
{
|
||||
byte[] addr = null;
|
||||
|
||||
// see if it is IPv4 address
|
||||
addr = sun.net.util.IPAddressUtil.textToNumericFormatV4(address);
|
||||
// if not, see if it is IPv6 address
|
||||
if (addr == null)
|
||||
{
|
||||
addr = sun.net.util.IPAddressUtil
|
||||
.textToNumericFormatV6(address);
|
||||
}
|
||||
// if IPv4 is found when IPv6 is expected
|
||||
else if (ipv6Expected)
|
||||
{
|
||||
// invalid address: IPv4 address surrounded with brackets!
|
||||
return false;
|
||||
}
|
||||
// if an IPv4 or IPv6 address is found
|
||||
if (addr != null)
|
||||
{
|
||||
// is an IP address
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// no matches found
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an InetAddress from the specified <tt>hostAddress</tt>. The point
|
||||
* of using the method rather than creating the address by yourself is that
|
||||
* it would first check whether the specified <tt>hostAddress</tt> is indeed
|
||||
* a valid ip address. It this is the case, the method would create the
|
||||
* <tt>InetAddress</tt> using the <tt>InetAddress.getByAddress()</tt>
|
||||
* method so that no DNS resolution is attempted by the JRE. Otherwise
|
||||
* it would simply use <tt>InetAddress.getByName()</tt> so that we would an
|
||||
* <tt>InetAddress</tt> instance even at the cost of a potential DNS
|
||||
* resolution.
|
||||
*
|
||||
* @param hostAddress the <tt>String</tt> representation of the address
|
||||
* that we would like to create an <tt>InetAddress</tt> instance for.
|
||||
*
|
||||
* @return an <tt>InetAddress</tt> instance corresponding to the specified
|
||||
* <tt>hostAddress</tt>.
|
||||
*
|
||||
* @throws UnknownHostException if any of the <tt>InetAddress</tt> methods
|
||||
* we are using throw an exception.
|
||||
*/
|
||||
public static InetAddress getInetAddress(String hostAddress)
|
||||
throws UnknownHostException
|
||||
{
|
||||
//is null
|
||||
if (hostAddress == null || hostAddress.length() == 0)
|
||||
{
|
||||
throw new UnknownHostException(
|
||||
hostAddress + " is not a valid host address");
|
||||
}
|
||||
|
||||
//transform IPv6 literals into normal addresses
|
||||
if (hostAddress.charAt(0) == '[')
|
||||
{
|
||||
// This is supposed to be an IPv6 literal
|
||||
if (hostAddress.length() > 2
|
||||
&& hostAddress.charAt(hostAddress.length()-1) == ']')
|
||||
{
|
||||
hostAddress = hostAddress.substring(1, hostAddress.length() -1);
|
||||
}
|
||||
else
|
||||
{
|
||||
// This was supposed to be a IPv6 address, but it's not!
|
||||
throw new UnknownHostException(hostAddress);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (NetworkUtils.isValidIPAddress(hostAddress))
|
||||
{
|
||||
byte[] addr = null;
|
||||
|
||||
// attempt parse as IPv4 address
|
||||
addr = sun.net.util.IPAddressUtil
|
||||
.textToNumericFormatV4(hostAddress);
|
||||
|
||||
// if not IPv4, parse as IPv6 address
|
||||
if (addr == null)
|
||||
{
|
||||
addr = sun.net.util.IPAddressUtil
|
||||
.textToNumericFormatV6(hostAddress);
|
||||
}
|
||||
return InetAddress.getByAddress(hostAddress, addr);
|
||||
}
|
||||
else
|
||||
{
|
||||
return InetAddress.getByName(hostAddress);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to determine if this host supports IPv6 addresses (i.e. has at
|
||||
* least one IPv6 address) and returns IN6_ADDR_ANY or IN4_ADDR_ANY
|
||||
* accordingly. This method is only used to initialize IN_ADDR_ANY so that
|
||||
* it could be used when binding sockets. The reason we need it is because
|
||||
* on mac (contrary to lin or win) binding a socket on 0.0.0.0 would make
|
||||
* it deaf to IPv6 traffic. Binding on ::0 does the trick but that would
|
||||
* fail on hosts that have no IPv6 support. Using the result of this method
|
||||
* provides an easy way to bind sockets in cases where we simply want any
|
||||
* IP packets coming on the port we are listening on (regardless of IP
|
||||
* version).
|
||||
*
|
||||
* @return IN6_ADDR_ANY or IN4_ADDR_ANY if this host supports or not IPv6.
|
||||
*/
|
||||
private static String determineAnyAddress()
|
||||
{
|
||||
Enumeration<NetworkInterface> ifaces;
|
||||
try
|
||||
{
|
||||
ifaces = NetworkInterface.getNetworkInterfaces();
|
||||
}
|
||||
catch (SocketException e)
|
||||
{
|
||||
logger.log(Level.FINE, "Couldn't retrieve local interfaces.", e);
|
||||
return IN4_ADDR_ANY;
|
||||
}
|
||||
|
||||
while(ifaces.hasMoreElements())
|
||||
{
|
||||
Enumeration<InetAddress> addrs
|
||||
= ifaces.nextElement().getInetAddresses();
|
||||
while (addrs.hasMoreElements())
|
||||
{
|
||||
if(addrs.nextElement() instanceof Inet6Address)
|
||||
return IN6_ADDR_ANY;
|
||||
}
|
||||
}
|
||||
|
||||
return IN4_ADDR_ANY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether <tt>port</tt> is a valid port number bindable by an
|
||||
* application (i.e. an integer between 1024 and 65535).
|
||||
*
|
||||
* @param port the port number that we'd like verified.
|
||||
*
|
||||
* @return <tt>true</tt> if port is a valid and bindable port number and
|
||||
* <tt>alse</tt> otherwise.
|
||||
*/
|
||||
public static boolean isValidPortNumber(int port)
|
||||
{
|
||||
return MIN_PORT_NUMBER < port && port < MAX_PORT_NUMBER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether or not the <tt>iface</tt> interface is a loopback
|
||||
* interface. We use this method as a replacement to the
|
||||
* <tt>NetworkInterface.isLoopback()</tt> method that only comes with
|
||||
* java 1.6.
|
||||
*
|
||||
* @param iface the inteface that we'd like to determine as loopback or not.
|
||||
*
|
||||
* @return true if <tt>iface</tt> contains at least one loopback address
|
||||
* and <tt>false</tt> otherwise.
|
||||
*/
|
||||
public static boolean isInterfaceLoopback(NetworkInterface iface)
|
||||
{
|
||||
try
|
||||
{
|
||||
Method method
|
||||
= iface.getClass().getMethod("isLoopback", new Class[]{});
|
||||
|
||||
return ((Boolean)method.invoke(iface, new Object[]{}))
|
||||
.booleanValue();
|
||||
}
|
||||
catch(Throwable t)
|
||||
{
|
||||
//apparently we are not running in a JVM that supports the
|
||||
//is Loopback method. we'll try another approach.
|
||||
}
|
||||
Enumeration<InetAddress> addresses = iface.getInetAddresses();
|
||||
|
||||
return addresses.hasMoreElements()
|
||||
&& addresses.nextElement().isLoopbackAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines, if possible, whether or not the <tt>iface</tt> interface is
|
||||
* up. We use this method so that we could use {@link
|
||||
* java.net.NetworkInterface}'s <tt>isUp()</tt> when running a JVM that
|
||||
* supports it and return a default value otherwise.
|
||||
*
|
||||
* @param iface the interface that we'd like to determine as Up or Down.
|
||||
*
|
||||
* @return <tt>false</tt> if <tt>iface</tt> is known to be down and
|
||||
* <tt>true</tt> if the <tt>iface</tt> is Up or in case we couldn't
|
||||
* determine.
|
||||
*/
|
||||
public static boolean isInterfaceUp(NetworkInterface iface)
|
||||
{
|
||||
try
|
||||
{
|
||||
Method method
|
||||
= iface.getClass().getMethod("isUp", new Class[]{});
|
||||
|
||||
return ((Boolean)method.invoke(iface, new Object[]{}))
|
||||
.booleanValue();
|
||||
}
|
||||
catch(Throwable t)
|
||||
{
|
||||
//apparently we are not running in a JVM that supports the
|
||||
//isUp method. returning default value.
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines, if possible, whether or not the <tt>iface</tt> interface is
|
||||
* a virtual interface (e.g. VPN, MIPv6 tunnel, etc.) or not. We use this
|
||||
* method so that we could use {@link java.net.NetworkInterface}'s
|
||||
* <tt>isVirtual()</tt> when running a JVM that supports it and return a
|
||||
* default value otherwise.
|
||||
*
|
||||
* @param iface the interface that we'd like to determine as virtual or not.
|
||||
*
|
||||
* @return <tt>true</tt> if <tt>iface</tt> is known to be a virtual
|
||||
* interface and <tt>false</tt> if the <tt>iface</tt> is not virtual or in
|
||||
* case we couldn't determine.
|
||||
*/
|
||||
public static boolean isInterfaceVirtual(NetworkInterface iface)
|
||||
{
|
||||
try
|
||||
{
|
||||
Method method
|
||||
= iface.getClass().getMethod("isVirtual", new Class[]{});
|
||||
|
||||
return ((Boolean)method.invoke(iface, new Object[]{}))
|
||||
.booleanValue();
|
||||
}
|
||||
catch(Throwable t)
|
||||
{
|
||||
//apparently we are not running in a JVM that supports the
|
||||
//isVirtual method. returning default value.
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a <tt>String</tt> that is guaranteed not to contain an address
|
||||
* scope specified (i.e. removes the %scopeID at the end of IPv6 addresses
|
||||
* returned by Java. Takes into account the presence or absence of square
|
||||
* brackets encompassing the address.
|
||||
*
|
||||
* @param ipv6Address the address whose scope ID we'd like to get rid of.
|
||||
*
|
||||
* @return the newly form address containing no scope ID.
|
||||
*/
|
||||
public static String stripScopeID(String ipv6Address)
|
||||
{
|
||||
int scopeStart = ipv6Address.indexOf('%');
|
||||
|
||||
if (scopeStart == -1)
|
||||
return ipv6Address;
|
||||
|
||||
ipv6Address = ipv6Address.substring(0, scopeStart);
|
||||
|
||||
//in case this was an IPv6 literal and we remove the closing bracket,
|
||||
//put it back in now.
|
||||
if(ipv6Address.charAt(0) == '['
|
||||
&& ipv6Address.charAt(ipv6Address.length()-1) != ']')
|
||||
{
|
||||
ipv6Address += ']';
|
||||
}
|
||||
|
||||
return ipv6Address;
|
||||
}
|
||||
}
|
||||
30
src/org/ice4j/ice/harvest/CandidateHarvester.java
Normal file
30
src/org/ice4j/ice/harvest/CandidateHarvester.java
Normal file
@ -0,0 +1,30 @@
|
||||
/*
|
||||
* 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.harvest;
|
||||
|
||||
import org.ice4j.ice.*;
|
||||
|
||||
/**
|
||||
* A <tt>CandidateHarvester</tt> gathers a certain kind of <tt>Candidate</tt>s
|
||||
* (e.g. host, reflexive, or relayed) for a specified {@link
|
||||
* org.ice4j.ice.Component}.
|
||||
*
|
||||
* @author Emil Ivov
|
||||
*/
|
||||
public interface CandidateHarvester
|
||||
{
|
||||
|
||||
/**
|
||||
* Gathers all candidate addresses of the type that this
|
||||
* <tt>CandidateHarvester</tt>
|
||||
*
|
||||
* @param component the {@link Component} that we'd like to gather candidate
|
||||
* addresses for.
|
||||
*/
|
||||
public void harvest(Component component);
|
||||
}
|
||||
218
src/org/ice4j/ice/harvest/HostCandidateHarvester.java
Normal file
218
src/org/ice4j/ice/harvest/HostCandidateHarvester.java
Normal file
@ -0,0 +1,218 @@
|
||||
/*
|
||||
* 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.harvest;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.util.*;
|
||||
import java.util.logging.*;
|
||||
|
||||
import org.ice4j.*;
|
||||
import org.ice4j.ice.*;
|
||||
|
||||
/**
|
||||
* A <tt>HostCandidateHarvester</tt> gathers host <tt>Candidate</tt>s for a
|
||||
* specified {@link org.ice4j.ice.Component}. Most <tt>CandidateHarvester</tt>s
|
||||
* would rely on the output of the host harvester, that is all host addresses,
|
||||
* to be already present and bound in a <tt>Component</tt> before being able to
|
||||
* harvest the type of addresses that they are responsible for.
|
||||
*
|
||||
* @author Emil Ivov
|
||||
*/
|
||||
public class HostCandidateHarvester
|
||||
{
|
||||
/**
|
||||
* Our class logger.
|
||||
*/
|
||||
private final Logger logger
|
||||
= Logger.getLogger(HostCandidateHarvester.class.getName());
|
||||
|
||||
/**
|
||||
* Gathers all candidate addresses on the local machine, binds sockets on
|
||||
* them and creates {@link HostCandidate}s. The harvester would always
|
||||
* try to bind the sockets on the specified <tt>preferredPort</tt> first.
|
||||
* If that fails we will move through all ports between <tt>minPort</tt> and
|
||||
* <tt>maxPort</tt> and give up if still can't find a free port.
|
||||
*
|
||||
* @param component the {@link Component} that we'd like to gather candidate
|
||||
* addresses for.
|
||||
* @param preferredPort the port number that should be tried first when
|
||||
* binding local <tt>Candidate</tt> sockets for this <tt>Component</tt>.
|
||||
* @param minPort the port number where we should first try to bind before
|
||||
* moving to the next one (i.e. <tt>minPort + 1</tt>)
|
||||
* @param maxPort the maximum port number where we should try binding
|
||||
* before giving up and throwinG an exception.
|
||||
*
|
||||
* @throws IllegalArgumentException if either <tt>minPort</tt> or
|
||||
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort >
|
||||
* maxPort</tt>.
|
||||
* @throws IOException if an error occurs while the underlying resolver lib
|
||||
* is using sockets.
|
||||
*/
|
||||
public void harvest(Component component,
|
||||
int preferredPort,
|
||||
int minPort,
|
||||
int maxPort)
|
||||
throws IllegalArgumentException,
|
||||
IOException
|
||||
{
|
||||
Enumeration<NetworkInterface> interfaces
|
||||
= NetworkInterface.getNetworkInterfaces();
|
||||
|
||||
boolean boundAtLeastOneSocket = false;
|
||||
while (interfaces.hasMoreElements())
|
||||
{
|
||||
NetworkInterface iface = interfaces.nextElement();
|
||||
|
||||
if (NetworkUtils.isInterfaceLoopback(iface)
|
||||
|| !NetworkUtils.isInterfaceUp(iface))
|
||||
{
|
||||
//this one is obviously not going to do
|
||||
continue;
|
||||
}
|
||||
|
||||
Enumeration<InetAddress> addresses = iface.getInetAddresses();
|
||||
|
||||
while(addresses.hasMoreElements())
|
||||
{
|
||||
InetAddress addr = addresses.nextElement();
|
||||
|
||||
DatagramSocket sock;
|
||||
try
|
||||
{
|
||||
sock = createDatagramSocket(
|
||||
addr, preferredPort, minPort, maxPort);
|
||||
boundAtLeastOneSocket = true;
|
||||
}
|
||||
catch(IOException exc)
|
||||
{
|
||||
//there seems to be a problem with this particular address
|
||||
//let's just move on for now and hope we will find better
|
||||
if (logger.isLoggable(Level.WARNING))
|
||||
logger.warning("Failed to create a socket for:"
|
||||
+"\naddr:" + addr
|
||||
+"\npreferredPort:" + preferredPort
|
||||
+"\nminPort:" + minPort
|
||||
+"\nmaxPort:" + maxPort);
|
||||
continue;
|
||||
}
|
||||
|
||||
HostCandidate candidate = new HostCandidate(sock, component);
|
||||
candidate.setVirtual(NetworkUtils.isInterfaceVirtual(iface));
|
||||
component.addLocalCandidate(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
if(!boundAtLeastOneSocket)
|
||||
{
|
||||
throw new IOException(
|
||||
"Failed to bind even a single host candidate for component:"
|
||||
+ component
|
||||
+ " preferredPort=" + preferredPort
|
||||
+ " minPort=" + minPort
|
||||
+ " maxPort=" + maxPort);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a <tt>DatagramSocket</tt> and binds it to the specified
|
||||
* <tt>localAddress</tt> and a port in the range specified by the
|
||||
* <tt>minPort</tt> and <tt>maxPort</tt> parameters. We first try to bind
|
||||
* the newly created socket on the <tt>preferredPort</tt> port number
|
||||
* (unless it is outside the <tt>[minPort, maxPort]</tt> range in which case
|
||||
* we first try the <tt>minPort</tt>) and then proceed incrementally upwards
|
||||
* until we succeed or reach the bind retries limit. If we reach the
|
||||
* <tt>maxPort</tt> port number before the bind retries limit, we will then
|
||||
* start over again at <tt>minPort</tt> and keep going until we run out of
|
||||
* retries.
|
||||
*
|
||||
* @param laddr the address that we'd like to bind the socket on.
|
||||
* @param preferredPort the port number that we should try to bind to first.
|
||||
* @param minPort the port number where we should first try to bind before
|
||||
* moving to the next one (i.e. <tt>minPort + 1</tt>)
|
||||
* @param maxPort the maximum port number where we should try binding
|
||||
* before giving up and throwinG an exception.
|
||||
*
|
||||
* @return the newly created <tt>DatagramSocket</tt>.
|
||||
*
|
||||
* @throws IllegalArgumentException if either <tt>minPort</tt> or
|
||||
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort >
|
||||
* maxPort</tt>.
|
||||
* @throws IOException if an error occurs while the underlying resolver lib
|
||||
* is using sockets.
|
||||
* @throws BindException if we couldn't find a free port between
|
||||
* <tt>minPort</tt> and <tt>maxPort</tt> before reaching the maximum allowed
|
||||
* number of retries.
|
||||
*/
|
||||
private DatagramSocket createDatagramSocket(InetAddress laddr,
|
||||
int preferredPort,
|
||||
int minPort,
|
||||
int maxPort)
|
||||
throws IllegalArgumentException,
|
||||
IOException,
|
||||
BindException
|
||||
{
|
||||
// make sure port numbers are valid
|
||||
if (!NetworkUtils.isValidPortNumber(minPort)
|
||||
|| !NetworkUtils.isValidPortNumber(maxPort))
|
||||
{
|
||||
throw new IllegalArgumentException("minPort (" + minPort
|
||||
+ ") and maxPort (" + maxPort + ") "
|
||||
+ "should be integers between 1024 and 65535.");
|
||||
}
|
||||
|
||||
// make sure minPort comes before maxPort.
|
||||
if (minPort > maxPort)
|
||||
{
|
||||
throw new IllegalArgumentException("minPort (" + minPort
|
||||
+ ") should be less than or "
|
||||
+ "equal to maxPort (" + maxPort + ")");
|
||||
}
|
||||
|
||||
// if preferredPort is not in the allowed range, place it at min.
|
||||
if (minPort > preferredPort || preferredPort > maxPort)
|
||||
{
|
||||
throw new IllegalArgumentException("preferredPort ("+preferredPort
|
||||
+") must be between minPort (" + minPort
|
||||
+ ") and maxPort (" + maxPort + ")");
|
||||
}
|
||||
|
||||
int bindRetries = StackProperties.getInt(
|
||||
StackProperties.BIND_RETRIES_PROPERTY_NAME,
|
||||
StackProperties.BIND_RETRIES_DEFAULT_VALUE);
|
||||
|
||||
int port = preferredPort;
|
||||
for (int i = 0; i < bindRetries; i++)
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
DatagramSocket sock = new DatagramSocket(port, laddr);
|
||||
|
||||
if(logger.isLoggable(Level.FINEST))
|
||||
logger.log(Level.FINEST,
|
||||
"just bound to: " + sock.getLocalSocketAddress());
|
||||
return sock;
|
||||
}
|
||||
catch (SocketException se)
|
||||
{
|
||||
logger.log(Level.INFO,
|
||||
"Retrying a bind because of a failure to bind to address "
|
||||
+ laddr + " and port " + port, se);
|
||||
}
|
||||
|
||||
port ++;
|
||||
|
||||
if (port > maxPort)
|
||||
port = minPort;
|
||||
}
|
||||
|
||||
throw new BindException("Could not bind to any port between "
|
||||
+ minPort + " and " + (port -1));
|
||||
}
|
||||
}
|
||||
32
src/org/ice4j/ice/harvest/StunCandidateHarvester.java
Normal file
32
src/org/ice4j/ice/harvest/StunCandidateHarvester.java
Normal file
@ -0,0 +1,32 @@
|
||||
/*
|
||||
* 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.harvest;
|
||||
|
||||
import org.ice4j.ice.*;
|
||||
|
||||
/**
|
||||
* A <tt>StunCandidateHarvester</tt> gathers STUN <tt>Candidate</tt>s for a
|
||||
* specified {@link org.ice4j.ice.Component}.
|
||||
*
|
||||
* @author Emil Ivov
|
||||
*/
|
||||
public class StunCandidateHarvester
|
||||
implements CandidateHarvester
|
||||
{
|
||||
/**
|
||||
* Gathers STUN candidates for all host <tt>Candidate</tt>s that are already
|
||||
* present in the specified <tt>component</tt>.
|
||||
*
|
||||
* @param component the {@link Component} that we'd like to gather candidate
|
||||
* STUN <tt>Candidate</tt>s for.
|
||||
*/
|
||||
public void harvest(Component component)
|
||||
{
|
||||
//todo implement
|
||||
}
|
||||
}
|
||||
32
src/org/ice4j/ice/harvest/TurnCandidateHarvester.java
Normal file
32
src/org/ice4j/ice/harvest/TurnCandidateHarvester.java
Normal file
@ -0,0 +1,32 @@
|
||||
/*
|
||||
* 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.harvest;
|
||||
|
||||
import org.ice4j.ice.*;
|
||||
|
||||
/**
|
||||
* A <tt>TurnCandidateHarvester</tt> gathers TURN <tt>Candidate</tt>s for a
|
||||
* specified {@link org.ice4j.ice.Component}.
|
||||
*
|
||||
* @author Emil Ivov
|
||||
*/
|
||||
public class TurnCandidateHarvester
|
||||
implements CandidateHarvester
|
||||
{
|
||||
/**
|
||||
* Gathers TURN candidates for all host <tt>Candidate</tt>s that are already
|
||||
* present in the specified <tt>component</tt>.
|
||||
*
|
||||
* @param component the {@link Component} that we'd like to gather candidate
|
||||
* TURN <tt>Candidate</tt>s for.
|
||||
*/
|
||||
public void harvest(Component component)
|
||||
{
|
||||
//todo implement
|
||||
}
|
||||
}
|
||||
195
src/org/ice4j/message/ChannelData.java
Normal file
195
src/org/ice4j/message/ChannelData.java
Normal file
@ -0,0 +1,195 @@
|
||||
/*
|
||||
* Ice4j, 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.*;
|
||||
|
||||
/**
|
||||
* The ChannelData message are used in TURN protocol
|
||||
* after a client has bound a channel to a peer.
|
||||
*
|
||||
* 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
|
||||
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
* | Channel Number | Length |
|
||||
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
* | |
|
||||
* / Application Data /
|
||||
* / /
|
||||
* | |
|
||||
* | +-------------------------------+
|
||||
* | |
|
||||
* +-------------------------------+
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Sebastien Vincent
|
||||
* @version 0.1
|
||||
*/
|
||||
public class ChannelData
|
||||
{
|
||||
/**
|
||||
* The channel number.
|
||||
*/
|
||||
private char channelNumber = 0;
|
||||
|
||||
/**
|
||||
* The data.
|
||||
*/
|
||||
private byte data[] = null;
|
||||
|
||||
/**
|
||||
* Size of the header.
|
||||
*/
|
||||
public static char HEADER_LENGTH = 4;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public ChannelData()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the channel number
|
||||
* @param channelNumber the channel number
|
||||
*/
|
||||
public void setChannelNumber(char channelNumber)
|
||||
{
|
||||
this.channelNumber = channelNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the channel number.
|
||||
* @return channel number
|
||||
*/
|
||||
public char getChannelNumber()
|
||||
{
|
||||
return this.channelNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the data.
|
||||
* @param data the data
|
||||
*/
|
||||
public void setData(byte data[])
|
||||
{
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the data.
|
||||
* @return data
|
||||
*/
|
||||
public byte[] getData()
|
||||
{
|
||||
return this.data;
|
||||
}
|
||||
|
||||
public char getDataLength()
|
||||
{
|
||||
char length = 0;
|
||||
if(data == null)
|
||||
{
|
||||
return length;
|
||||
}
|
||||
|
||||
/* pad to a multiple of four */
|
||||
if((length % 4) > 0)
|
||||
{
|
||||
length += (4 - (length % 4));
|
||||
}
|
||||
|
||||
return (char)data.length;
|
||||
}
|
||||
|
||||
private static boolean validateChannelNumber(char channelNumber)
|
||||
{
|
||||
if(channelNumber <= 0x3FFF)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a binary representation of this message.
|
||||
* @return a binary representation of this message.
|
||||
* @throws StunException if the channel number is invalid
|
||||
*/
|
||||
public byte[] encode() throws StunException
|
||||
{
|
||||
char dataLength = getDataLength();
|
||||
byte binMsg[] = new byte[HEADER_LENGTH + dataLength];
|
||||
int offset = 0;
|
||||
|
||||
if(!validateChannelNumber(channelNumber))
|
||||
{
|
||||
throw new StunException(StunException.ILLEGAL_ARGUMENT, "Channel number invalid");
|
||||
}
|
||||
|
||||
/* channel number */
|
||||
binMsg[offset++] = (byte)(channelNumber >> 8);
|
||||
binMsg[offset++] = (byte)(channelNumber & 0xff);
|
||||
|
||||
/* length */
|
||||
binMsg[offset++] = (byte)((data != null) ? data.length >> 8 : 0);
|
||||
binMsg[offset++] = (byte)((data != null) ? data.length & 0xff : 0);
|
||||
|
||||
if(data != null)
|
||||
{
|
||||
System.arraycopy(data, 0, binMsg, offset, data.length);
|
||||
}
|
||||
|
||||
return binMsg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a message from its binary representation.
|
||||
* @param binMessage the binary array that contains the encoded message
|
||||
* @param offset the index where the message starts.
|
||||
* @param arrayLen the length of the message
|
||||
* @return a Message object constructed from the binMessage array
|
||||
* @throws StunException ILLEGAL_ARGUMENT if one or more of the arguments
|
||||
* have invalid values.
|
||||
*/
|
||||
public static ChannelData decode(byte binMessage[], char offset, char arrayLen) throws StunException
|
||||
{
|
||||
char msgLen = 0;
|
||||
char channelNumber = 0;
|
||||
ChannelData channelData = null;
|
||||
byte data[] = null;
|
||||
|
||||
if(arrayLen < 4)
|
||||
{
|
||||
throw new StunException(StunException.ILLEGAL_ARGUMENT, "Size too short");
|
||||
}
|
||||
|
||||
channelNumber = (char)((binMessage[offset++]<<8) | (binMessage[offset++]&0xFF));
|
||||
|
||||
if(!validateChannelNumber(channelNumber))
|
||||
{
|
||||
throw new StunException(StunException.ILLEGAL_ARGUMENT, "Channel number invalid");
|
||||
}
|
||||
|
||||
msgLen = (char)((binMessage[offset++]<<8) | (binMessage[offset++]&0xFF));
|
||||
if(msgLen != (binMessage.length - 4))
|
||||
{
|
||||
throw new StunException(StunException.ILLEGAL_ARGUMENT, "Size mismatch");
|
||||
}
|
||||
|
||||
data = new byte[msgLen];
|
||||
System.arraycopy(binMessage, offset, data, 0, msgLen);
|
||||
|
||||
channelData = new ChannelData();
|
||||
channelData.setData(data);
|
||||
channelData.setChannelNumber(channelNumber);
|
||||
|
||||
return channelData;
|
||||
}
|
||||
}
|
||||
|
||||
50
src/org/ice4j/message/Indication.java
Normal file
50
src/org/ice4j/message/Indication.java
Normal file
@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Ice4j, 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.*;
|
||||
|
||||
/**
|
||||
* An indication descendant of the message class.
|
||||
*
|
||||
* For example, indication messages is used by TURN protocol
|
||||
* to send and receive encapsulated data.
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Sebastien Vincent
|
||||
* @version 0.1
|
||||
*/
|
||||
public class Indication extends Message
|
||||
{
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
Indication()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether indicationType is a valid response type and if yes sets it
|
||||
* as the type of the current instance.
|
||||
* @param indicationType the type to set
|
||||
* @throws StunException ILLEGAL_ARGUMENT if indicationType is not a valid
|
||||
* response type
|
||||
*/
|
||||
public void setMessageType(char indicationType)
|
||||
throws StunException
|
||||
{
|
||||
if(!isIndicationType(indicationType))
|
||||
throw new StunException(StunException.ILLEGAL_ARGUMENT,
|
||||
(int)(indicationType)
|
||||
+ " - is not a valid response type.");
|
||||
|
||||
super.setMessageType(indicationType);
|
||||
}
|
||||
}
|
||||
|
||||
684
src/org/ice4j/message/Message.java
Normal file
684
src/org/ice4j/message/Message.java
Normal file
@ -0,0 +1,684 @@
|
||||
/*
|
||||
* 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 java.util.*;
|
||||
|
||||
import org.ice4j.*;
|
||||
import org.ice4j.attribute.*;
|
||||
|
||||
/**
|
||||
* This class represents a STUN message. STUN messages are TLV (type-length-value)
|
||||
* encoded using big endian (network ordered) binary. All STUN messages start
|
||||
* with a STUN header, followed by a STUN payload. The payload is a series of
|
||||
* STUN attributes, the set of which depends on the message type. The STUN
|
||||
* header contains a STUN message type, transaction ID, and length.
|
||||
*
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p>
|
||||
* @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 LinkedHashMap<Character, Attribute> attributes = new LinkedHashMap<Character, Attribute>();
|
||||
|
||||
/**
|
||||
* Desribes which attributes are present in which messages. An
|
||||
* M indicates that inclusion of the attribute in the message is
|
||||
* mandatory, O means its optional, C means it's conditional based on
|
||||
* some other aspect of the message, and N/A means that the attribute is
|
||||
* not applicable to that message type.
|
||||
*
|
||||
* For classic STUN :
|
||||
*
|
||||
*
|
||||
* Binding Shared Shared Shared <br/>
|
||||
* Binding Binding Error Secret Secret Secret <br/>
|
||||
* Att. Req. Resp. Resp. Req. Resp. Error <br/>
|
||||
* Resp. <br/>
|
||||
* _____________________________________________________________________ <br/>
|
||||
* MAPPED-ADDRESS N/A M N/A N/A N/A N/A <br/>
|
||||
* RESPONSE-ADDRESS O N/A N/A N/A N/A N/A <br/>
|
||||
* CHANGE-REQUEST O N/A N/A N/A N/A N/A <br/>
|
||||
* SOURCE-ADDRESS N/A M N/A N/A N/A N/A <br/>
|
||||
* CHANGED-ADDRESS N/A M N/A N/A N/A N/A <br/>
|
||||
* USERNAME O N/A N/A N/A M N/A <br/>
|
||||
* PASSWORD N/A N/A N/A N/A M N/A <br/>
|
||||
* MESSAGE-INTEGRITY O O N/A N/A N/A N/A <br/>
|
||||
* ERROR-CODE N/A N/A M N/A N/A M <br/>
|
||||
* UNKNOWN-ATTRIBUTES N/A N/A C N/A N/A C <br/>
|
||||
* REFLECTED-FROM N/A C N/A N/A N/A N/A <br/>
|
||||
* XOR-MAPPED-ADDRESS N/A M N/A N/A N/A N/A <br/>
|
||||
* XOR-ONLY O N/A N/A N/A N/A N/A <br/>
|
||||
* SOFTWARE N/A O O N/A O O <br/>
|
||||
*
|
||||
*/
|
||||
public static final byte N_A = 0;
|
||||
public static final byte C = 1;
|
||||
public static final byte O = 2;
|
||||
public static final byte M = 3;
|
||||
|
||||
//Message indices
|
||||
protected static final byte BINDING_REQUEST_PRESENTITY_INDEX = 0;
|
||||
protected static final byte BINDING_RESPONSE_PRESENTITY_INDEX = 1;
|
||||
protected static final byte BINDING_ERROR_RESPONSE_PRESENTITY_INDEX = 2;
|
||||
protected static final byte SHARED_SECRET_REQUEST_PRESENTITY_INDEX = 3;
|
||||
protected static final byte SHARED_SECRET_RESPONSE_PRESENTITY_INDEX = 4;
|
||||
protected static final byte SHARED_SECRET_ERROR_RESPONSE_PRESENTITY_INDEX = 5;
|
||||
protected static final byte ALLOCATE_REQUEST_PRESENTITY_INDEX = 6;
|
||||
protected static final byte ALLOCATE_RESPONSE_PRESENTITY_INDEX = 7;
|
||||
protected static final byte REFRESH_REQUEST_PRESENTITY_INDEX = 8;
|
||||
protected static final byte REFRESH_RESPONSE_PRESENTITY_INDEX = 9;
|
||||
protected static final byte CHANNELBIND_REQUEST_PRESENTITY_INDEX = 10;
|
||||
protected static final byte CHANNELBIND_RESPONSE_PRESENTITY_INDEX = 11;
|
||||
protected static final byte SEND_INDICATION_PRESENTITY_INDEX = 12;
|
||||
protected static final byte DATA_INDICATION_PRESENTITY_INDEX = 13;
|
||||
|
||||
//Attribute indices
|
||||
protected static final byte MAPPED_ADDRESS_PRESENTITY_INDEX = 0;
|
||||
protected static final byte RESPONSE_ADDRESS_PRESENTITY_INDEX = 1;
|
||||
protected static final byte CHANGE_REQUEST_PRESENTITY_INDEX = 2;
|
||||
protected static final byte SOURCE_ADDRESS_PRESENTITY_INDEX = 3;
|
||||
protected static final byte CHANGED_ADDRESS_PRESENTITY_INDEX = 4;
|
||||
protected static final byte USERNAME_PRESENTITY_INDEX = 5;
|
||||
protected static final byte PASSWORD_PRESENTITY_INDEX = 6;
|
||||
protected static final byte MESSAGE_INTEGRITY_PRESENTITY_INDEX = 7;
|
||||
protected static final byte ERROR_CODE_PRESENTITY_INDEX = 8;
|
||||
protected static final byte UNKNOWN_ATTRIBUTES_PRESENTITY_INDEX = 9;
|
||||
protected static final byte REFLECTED_FROM_PRESENTITY_INDEX = 10;
|
||||
protected static final byte XOR_MAPPED_ADDRESS_PRESENTITY_INDEX = 11;
|
||||
protected static final byte XOR_ONLY_PRESENTITY_INDEX = 12;
|
||||
protected static final byte SOFTWARE_PRESENTITY_INDEX = 13;
|
||||
protected static final byte UNKNOWN_OPTIONAL_ATTRIBUTES_PRESENTITY_INDEX = 14;
|
||||
protected static final byte ALTERNATE_SERVER_PRESENTITY_INDEX = 15;
|
||||
protected static final byte REALM_PRESENTITY_INDEX = 16;
|
||||
protected static final byte NONCE_PRESENTITY_INDEX = 17;
|
||||
protected static final byte FINGERPRINT_PRESENTITY_INDEX = 18;
|
||||
|
||||
/* TURN attributes */
|
||||
protected static final byte CHANNEL_NUMBER_PRESENTITY_INDEX = 19;
|
||||
protected static final byte LIFETIME_PRESENTITY_INDEX = 20;
|
||||
protected static final byte XOR_PEER_ADDRESS_PRESENTITY_INDEX = 21;
|
||||
protected static final byte DATA_PRESENTITY_INDEX = 22;
|
||||
protected static final byte XOR_RELAYED_ADDRESS_PRESENTITY_INDEX = 23;
|
||||
protected static final byte EVEN_PORT_PRESENTITY_INDEX = 24;
|
||||
protected static final byte REQUESTED_TRANSPORT_PRESENTITY_INDEX = 25;
|
||||
protected static final byte DONT_FRAGMENT_PRESENTITY_INDEX = 26;
|
||||
protected static final byte RESERVATION_TOKEN_PRESENTITY_INDEX = 27;
|
||||
|
||||
/* ICE attributes */
|
||||
protected static final byte PRIORITY_PRESENTITY_INDEX = 28;
|
||||
protected static final byte ICE_CONTROLLING_PRESENTITY_INDEX = 29;
|
||||
protected static final byte ICE_CONTROLLED_PRESENTITY_INDEX = 30;
|
||||
protected static final byte USE_CANDIDATE_PRESENTITY_INDEX = 31;
|
||||
|
||||
protected final static byte attributePresentities[][] = new byte[][]{
|
||||
// Binding Shared Shared Shared Alloc Alloc Rfrsh Rfrsh ChnlBnd ChnlBnd Send Data
|
||||
// Binding Binding Error Secret Secret Secret Req. Resp. Req. Resp. Req. Resp. Indic. Indic.
|
||||
// Att. Req. Resp. Resp. Req. Resp. Error
|
||||
// Resp.
|
||||
// ____________________________________________________________________________________________________________________________________________
|
||||
/*MAPPED-ADDRESS*/ { N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*RESPONSE-ADDRESS*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*CHANGE-REQUEST*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*SOURCE-ADDRESS*/ { N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*CHANGED-ADDRESS*/ { N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*USERNAME*/ { O, N_A, N_A, N_A, M, N_A, O, N_A, O, N_A, O, N_A, N_A, N_A},
|
||||
/*PASSWORD*/ { N_A, N_A, N_A, N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*MESSAGE-INTEGRITY*/ { O, O, N_A, N_A, N_A, N_A, O, O, O, O, O, O, N_A, N_A},
|
||||
/*ERROR-CODE*/ { N_A, N_A, M, N_A, N_A, M, N_A, M, N_A, M, N_A, M, N_A, N_A},
|
||||
/*UNKNOWN-ATTRIBUTES*/{ N_A, N_A, C, N_A, N_A, C, N_A, C, N_A, C, N_A, C, N_A, N_A},
|
||||
/*REFLECTED-FROM*/ { N_A, C, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*XOR-MAPPED-ADDRESS*/{ N_A, M, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*XOR-ONLY*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*SOFTWARE*/ { N_A, O, O, N_A, O, O, O, O, O, O, O, O, O, N_A},
|
||||
/*UNKNOWN_OPTIONAL*/ { O, O, O, O, O, O, O, O, O, O, O, O, N_A, N_A},
|
||||
/*ALTERNATE_SERVER*/ { O, O, O, O, O, O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*REALM*/ { O, N_A, N_A, N_A, M, N_A, O, O, O, O, O, O, N_A, N_A},
|
||||
/*NONCE*/ { O, N_A, N_A, N_A, M, N_A, O, O, O, O, O, O, N_A, N_A},
|
||||
/*FINGERPRINT*/ { O, O, O, O, O, O, O, O, O, O, O, O, N_A, N_A},
|
||||
/*CHANNEL-NUMBER*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A},
|
||||
/*LIFETIME*/ { N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, M, N_A, N_A, N_A, N_A, N_A},
|
||||
/*XOR-PEER-ADDRESS*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, M, M},
|
||||
/*DATA*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, O, M},
|
||||
/*XOR-RELAYED-ADDRESS*/{N_A, N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*EVEN-PORT*/ { N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*REQUESTED-TRANSPORT*/{N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*DONT-FRAGMENT*/ { N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, N_A, N_A, N_A, N_A, O, N_A},
|
||||
/*RESERVATION-TOKEN*/ { N_A, N_A, N_A, N_A, N_A, N_A, O, O, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*PRIORITY*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*ICE-CONTROLLING*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*ICE-CONTROLLED*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
/*USE-CANDIDATE*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates an empty STUN Mesage.
|
||||
*/
|
||||
protected Message()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of this message's body.
|
||||
* @return the length of the data in this message.
|
||||
*/
|
||||
public char getDataLength()
|
||||
{
|
||||
char length = 0;
|
||||
Attribute att = null;
|
||||
|
||||
Iterator iter = attributes.entrySet().iterator();
|
||||
while (iter.hasNext()) {
|
||||
att = (Attribute)((Map.Entry)iter.next()).getValue();
|
||||
length += att.getDataLength() + Attribute.HEADER_LENGTH;
|
||||
}
|
||||
|
||||
if((length % 4) > 0)
|
||||
{
|
||||
length += (4 - (length % 4));
|
||||
}
|
||||
|
||||
return length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the specified attribute to this message. If an attribute with that
|
||||
* name was already added, it would be replaced.
|
||||
* @param attribute the attribute to add to this message.
|
||||
* @throws StunException if the message cannot contain
|
||||
* such an attribute.
|
||||
*/
|
||||
public void addAttribute(Attribute attribute)
|
||||
throws StunException
|
||||
{
|
||||
Character attributeType = new Character(attribute.getAttributeType());
|
||||
if (getAttributePresentity(attributeType.charValue()) == N_A)
|
||||
{
|
||||
throw new StunException(StunException.ILLEGAL_ARGUMENT,
|
||||
"The attribute "
|
||||
+ attribute.getName()
|
||||
+ " is not allowed in a "
|
||||
+ getName());
|
||||
}
|
||||
|
||||
attributes.put(attributeType, attribute);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the attribute with the specified type or null if no such
|
||||
* attribute exists.
|
||||
*
|
||||
* @param attributeType the type of the attribute
|
||||
* @return the attribute with the specified type or null if no such attribute
|
||||
* exists
|
||||
*/
|
||||
public Attribute getAttribute(char attributeType)
|
||||
{
|
||||
return attributes.get(new Character(attributeType));
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns an enumeration containing all message attributes.
|
||||
* @return an enumeration containing all message attributes..
|
||||
*/
|
||||
/*
|
||||
public Iterator getAttributes()
|
||||
{
|
||||
return attributes.entrySet().iterator();
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Removes the specified attribute.
|
||||
* @param attributeType the attribute to remove.
|
||||
*/
|
||||
public void removeAttribute(char attributeType)
|
||||
{
|
||||
attributes.remove(new Character(attributeType));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of attributes, currently contained by the message.
|
||||
* @return the number of attributes, currently contained by the message.
|
||||
*/
|
||||
public int getAttributeCount()
|
||||
{
|
||||
return attributes.size();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Sets this message's type to be messageType. Method is package access
|
||||
* as it should not permit changing the type of message once it has been
|
||||
* initialized (could provoke attribute discrepancies). Called by
|
||||
* messageFactory.
|
||||
* @param messageType the message type.
|
||||
* @throws StunException ILLEGAL_ARGUMENT if message type is not valid in
|
||||
* the current context (e.g. when trying to set a Response type to a Request
|
||||
* and vice versa)
|
||||
*/
|
||||
protected void setMessageType(char messageType)
|
||||
throws StunException
|
||||
{
|
||||
this.messageType = messageType;
|
||||
}
|
||||
|
||||
/**
|
||||
* The message type of this message.
|
||||
* @return the message type of the message.
|
||||
*/
|
||||
public char getMessageType()
|
||||
{
|
||||
return messageType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the specified tranID and sets it as this message's transactionID.
|
||||
* @param tranID the transaction id to set in this message.
|
||||
* @throws StunException ILLEGAL_ARGUMENT if the transaction id is not valid.
|
||||
*/
|
||||
public void setTransactionID(byte[] tranID)
|
||||
throws StunException
|
||||
{
|
||||
if(tranID == null
|
||||
|| tranID.length != TRANSACTION_ID_LENGTH)
|
||||
throw new StunException(StunException.ILLEGAL_ARGUMENT,
|
||||
"Invalid transaction id");
|
||||
|
||||
this.transactionID = new byte[TRANSACTION_ID_LENGTH];
|
||||
System.arraycopy(tranID, 0,
|
||||
this.transactionID, 0, TRANSACTION_ID_LENGTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a reference to this message's transaction id.
|
||||
* @return a reference to this message's transaction id.
|
||||
*/
|
||||
public byte[] getTransactionID()
|
||||
{
|
||||
return this.transactionID;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether an attribute could be present in this message.
|
||||
* @param attributeType the id of the attribute to check .
|
||||
* @return Message.N_A - for not applicable <br/>
|
||||
* Message.C - for case depending <br/>
|
||||
* Message.N_A - for not applicable <br/>
|
||||
*/
|
||||
protected byte getAttributePresentity(char attributeType)
|
||||
{
|
||||
byte msgIndex = -1;
|
||||
byte attributeIndex = -1;
|
||||
|
||||
switch (messageType)
|
||||
{
|
||||
case BINDING_REQUEST: msgIndex = BINDING_REQUEST_PRESENTITY_INDEX; break;
|
||||
case BINDING_RESPONSE: msgIndex = BINDING_RESPONSE_PRESENTITY_INDEX; break;
|
||||
case BINDING_ERROR_RESPONSE: msgIndex = BINDING_ERROR_RESPONSE_PRESENTITY_INDEX; break;
|
||||
case SHARED_SECRET_REQUEST: msgIndex = SHARED_SECRET_REQUEST_PRESENTITY_INDEX; break;
|
||||
case SHARED_SECRET_RESPONSE: msgIndex = SHARED_SECRET_RESPONSE_PRESENTITY_INDEX; break;
|
||||
case SHARED_SECRET_ERROR_RESPONSE: msgIndex = SHARED_SECRET_ERROR_RESPONSE_PRESENTITY_INDEX; break;
|
||||
case ALLOCATE_REQUEST: msgIndex = ALLOCATE_REQUEST_PRESENTITY_INDEX; break;
|
||||
case REFRESH_REQUEST: msgIndex = REFRESH_REQUEST_PRESENTITY_INDEX; break;
|
||||
case CHANNELBIND_REQUEST: msgIndex = CHANNELBIND_REQUEST_PRESENTITY_INDEX; break;
|
||||
case SEND_INDICATION: msgIndex = SEND_INDICATION_PRESENTITY_INDEX; break;
|
||||
case DATA_INDICATION: msgIndex = DATA_INDICATION_PRESENTITY_INDEX; break;
|
||||
}
|
||||
|
||||
switch (attributeType)
|
||||
{
|
||||
case Attribute.MAPPED_ADDRESS: attributeIndex = MAPPED_ADDRESS_PRESENTITY_INDEX; break;
|
||||
case Attribute.RESPONSE_ADDRESS: attributeIndex = RESPONSE_ADDRESS_PRESENTITY_INDEX; break;
|
||||
case Attribute.CHANGE_REQUEST: attributeIndex = CHANGE_REQUEST_PRESENTITY_INDEX; break;
|
||||
case Attribute.SOURCE_ADDRESS: attributeIndex = SOURCE_ADDRESS_PRESENTITY_INDEX; break;
|
||||
case Attribute.CHANGED_ADDRESS: attributeIndex = CHANGED_ADDRESS_PRESENTITY_INDEX; break;
|
||||
case Attribute.USERNAME: attributeIndex = USERNAME_PRESENTITY_INDEX; break;
|
||||
case Attribute.PASSWORD: attributeIndex = PASSWORD_PRESENTITY_INDEX; break;
|
||||
case Attribute.MESSAGE_INTEGRITY: attributeIndex = MESSAGE_INTEGRITY_PRESENTITY_INDEX; break;
|
||||
case Attribute.ERROR_CODE: attributeIndex = ERROR_CODE_PRESENTITY_INDEX; break;
|
||||
case Attribute.UNKNOWN_ATTRIBUTES: attributeIndex = UNKNOWN_ATTRIBUTES_PRESENTITY_INDEX; break;
|
||||
case Attribute.REFLECTED_FROM: attributeIndex = REFLECTED_FROM_PRESENTITY_INDEX; break;
|
||||
case Attribute.XOR_MAPPED_ADDRESS: attributeIndex = XOR_MAPPED_ADDRESS_PRESENTITY_INDEX; break;
|
||||
case Attribute.XOR_ONLY: attributeIndex = XOR_ONLY_PRESENTITY_INDEX; break;
|
||||
case Attribute.SOFTWARE: attributeIndex = SOFTWARE_PRESENTITY_INDEX; break;
|
||||
case Attribute.ALTERNATE_SERVER: attributeIndex = ALTERNATE_SERVER_PRESENTITY_INDEX; break;
|
||||
case Attribute.REALM: attributeIndex = REALM_PRESENTITY_INDEX; break;
|
||||
case Attribute.NONCE: attributeIndex = NONCE_PRESENTITY_INDEX; break;
|
||||
case Attribute.FINGERPRINT: attributeIndex = FINGERPRINT_PRESENTITY_INDEX; break;
|
||||
case Attribute.CHANNEL_NUMBER: attributeIndex = CHANNEL_NUMBER_PRESENTITY_INDEX; break;
|
||||
case Attribute.LIFETIME: attributeIndex = LIFETIME_PRESENTITY_INDEX; break;
|
||||
case Attribute.XOR_PEER_ADDRESS: attributeIndex = XOR_PEER_ADDRESS_PRESENTITY_INDEX; break;
|
||||
case Attribute.DATA: attributeIndex = DATA_PRESENTITY_INDEX; break;
|
||||
case Attribute.XOR_RELAYED_ADDRESS:attributeIndex = XOR_RELAYED_ADDRESS_PRESENTITY_INDEX; break;
|
||||
case Attribute.EVEN_PORT: attributeIndex = EVEN_PORT_PRESENTITY_INDEX; break;
|
||||
case Attribute.REQUESTED_TRANSPORT:attributeIndex = REQUESTED_TRANSPORT_PRESENTITY_INDEX; break;
|
||||
case Attribute.DONT_FRAGMENT: attributeIndex = DONT_FRAGMENT_PRESENTITY_INDEX; break;
|
||||
case Attribute.RESERVATION_TOKEN: attributeIndex = RESERVATION_TOKEN_PRESENTITY_INDEX; break;
|
||||
default: attributeIndex = UNKNOWN_OPTIONAL_ATTRIBUTES_PRESENTITY_INDEX; break;
|
||||
}
|
||||
|
||||
return attributePresentities[ attributeIndex ][ msgIndex ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the human readable name of this message. Message names do
|
||||
* not really matter from the protocol point of view. They are only used
|
||||
* for debugging and readability.
|
||||
* @return this message's name.
|
||||
*/
|
||||
public String getName()
|
||||
{
|
||||
switch (messageType)
|
||||
{
|
||||
case BINDING_REQUEST: return "BINDING-REQUEST";
|
||||
case BINDING_RESPONSE: return "BINDING-RESPONSE";
|
||||
case BINDING_ERROR_RESPONSE: return "BINDING-ERROR-RESPONSE";
|
||||
case SHARED_SECRET_REQUEST: return "SHARED-SECRET-REQUEST";
|
||||
case SHARED_SECRET_RESPONSE: return "SHARED-SECRET-RESPONSE";
|
||||
case SHARED_SECRET_ERROR_RESPONSE: return "SHARED-SECRET-ERROR-RESPONSE";
|
||||
}
|
||||
|
||||
return "UNKNOWN-MESSAGE";
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two STUN Messages. Messages are considered equal when their
|
||||
* type, length, and all their attributes are equal.
|
||||
*
|
||||
* @param obj the object to compare this message with.
|
||||
* @return true if the messages are equal and false otherwise.
|
||||
*/
|
||||
public boolean equals(Object obj)
|
||||
{
|
||||
if(!(obj instanceof Message)
|
||||
|| obj == null)
|
||||
return false;
|
||||
|
||||
if(obj == this)
|
||||
return true;
|
||||
|
||||
Message msg = (Message) obj;
|
||||
if( msg.getMessageType() != getMessageType())
|
||||
return false;
|
||||
if(msg.getDataLength() != getDataLength())
|
||||
return false;
|
||||
|
||||
//compare attributes
|
||||
Iterator iter = attributes.entrySet().iterator();
|
||||
while (iter.hasNext()) {
|
||||
Attribute localAtt = (Attribute)((Map.Entry)iter.next()).getValue();
|
||||
|
||||
if(!localAtt.equals(msg.getAttribute(localAtt.getAttributeType())))
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a binary representation of this message.
|
||||
* @return a binary representation of this message.
|
||||
* @throws StunException if the message does not have all required
|
||||
* attributes.
|
||||
*/
|
||||
public byte[] encode()
|
||||
throws StunException
|
||||
{
|
||||
//make sure we have everything necessary to encode a proper message
|
||||
validateAttributePresentity();
|
||||
char dataLength = getDataLength();
|
||||
byte binMsg[] = new byte[HEADER_LENGTH + dataLength];
|
||||
int offset = 0;
|
||||
|
||||
binMsg[offset++] = (byte)(getMessageType()>>8);
|
||||
binMsg[offset++] = (byte)(getMessageType()&0xFF);
|
||||
|
||||
binMsg[offset++] = (byte)(dataLength >> 8);
|
||||
binMsg[offset++] = (byte)(dataLength & 0xFF);
|
||||
|
||||
System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4);
|
||||
offset+=4;
|
||||
System.arraycopy(getTransactionID(), 0, binMsg, offset, TRANSACTION_ID_LENGTH);
|
||||
offset+=TRANSACTION_ID_LENGTH;
|
||||
|
||||
Iterator iter = attributes.entrySet().iterator();
|
||||
while (iter.hasNext()) {
|
||||
|
||||
Attribute attribute = (Attribute)((Map.Entry)iter.next()).getValue();
|
||||
|
||||
byte[] attBinValue = attribute.encode();
|
||||
System.arraycopy(attBinValue, 0, binMsg, offset, attBinValue.length);
|
||||
offset += attBinValue.length;
|
||||
}
|
||||
|
||||
return binMsg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a message from its binary representation.
|
||||
* @param binMessage the binary array that contains the encoded message
|
||||
* @param offset the index where the message starts.
|
||||
* @param arrayLen the length of the message
|
||||
* @return a Message object constructed from the binMessage array
|
||||
* @throws StunException ILLEGAL_ARGUMENT if one or more of the arguments
|
||||
* have invalid values.
|
||||
*/
|
||||
public static Message decode(byte binMessage[], char offset, char arrayLen)
|
||||
throws StunException
|
||||
{
|
||||
arrayLen = (char)Math.min(binMessage.length, arrayLen);
|
||||
|
||||
if(binMessage == null || arrayLen - offset < Message.HEADER_LENGTH)
|
||||
throw new StunException(StunException.ILLEGAL_ARGUMENT,
|
||||
"The given binary array is not a valid StunMessage");
|
||||
|
||||
char messageType = (char)((binMessage[offset++]<<8) | (binMessage[offset++]&0xFF));
|
||||
Message message;
|
||||
if (Message.isResponseType(messageType))
|
||||
{
|
||||
message = new Response();
|
||||
}
|
||||
else if(Message.isRequestType(messageType))
|
||||
{
|
||||
message = new Request();
|
||||
}
|
||||
else /* indication */
|
||||
{
|
||||
message = new Indication();
|
||||
}
|
||||
|
||||
message.setMessageType(messageType);
|
||||
|
||||
int length = (char)((binMessage[offset++]<<8) | (binMessage[offset++]&0xFF));
|
||||
|
||||
/* copy the cookie */
|
||||
byte cookie[] = new byte[4];
|
||||
System.arraycopy(binMessage, offset, cookie, 0, 4);
|
||||
offset+=4;
|
||||
|
||||
if(arrayLen - offset - TRANSACTION_ID_LENGTH < length)
|
||||
throw new StunException(StunException.ILLEGAL_ARGUMENT,
|
||||
"The given binary array does not seem to "
|
||||
+"contain a whole StunMessage");
|
||||
|
||||
byte tranID[] = new byte[TRANSACTION_ID_LENGTH];
|
||||
System.arraycopy(binMessage, offset, tranID, 0, TRANSACTION_ID_LENGTH);
|
||||
message.setTransactionID(tranID);
|
||||
offset+=TRANSACTION_ID_LENGTH;
|
||||
|
||||
while(offset - Message.HEADER_LENGTH< length)
|
||||
{
|
||||
Attribute att = AttributeDecoder.decode(binMessage,
|
||||
offset,
|
||||
(char)(length - offset));
|
||||
message.addAttribute(att);
|
||||
offset += att.getDataLength() + Attribute.HEADER_LENGTH;
|
||||
}
|
||||
|
||||
return message;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that the message has all obligatory attributes and throw an
|
||||
* exception if this is not the case.
|
||||
*
|
||||
* @throws StunException (ILLEGAL_STATE)if the message does not have all
|
||||
* required attributes.
|
||||
*/
|
||||
protected void validateAttributePresentity()
|
||||
throws StunException
|
||||
{
|
||||
for(char i = Attribute.MAPPED_ADDRESS; i < Attribute.REFLECTED_FROM; i++)
|
||||
if(getAttributePresentity(i) == M && getAttribute(i) == null)
|
||||
throw new StunException(StunException.ILLEGAL_STATE,
|
||||
"A mandatory attribute (type="
|
||||
+(int)i
|
||||
+ ") is missing!");
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the message type is a Error Response.
|
||||
* @param type type to test
|
||||
* @return true if the type is Error Response, false otherwise
|
||||
*/
|
||||
public static boolean isErrorResponseType(char type)
|
||||
{
|
||||
return ((type & 0x0110) == STUN_ERROR_RESP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the message type is a Success Response.
|
||||
* @param type type to test
|
||||
* @return true if the type is Success Response, false otherwise
|
||||
*/
|
||||
public static boolean isSuccessResponseType(char type)
|
||||
{
|
||||
return ((type & 0x0110) == STUN_SUCCESS_RESP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether type could be the type of a STUN Response (as opposed
|
||||
* to STUN Request).
|
||||
* @param type the type to test.
|
||||
* @return true if type is a valid response type.
|
||||
*/
|
||||
public static boolean isResponseType(char type)
|
||||
{
|
||||
/* return (((type >> 8) & 1) != 0); */
|
||||
return (isSuccessResponseType(type) || isErrorResponseType(type));
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the message type is Indication.
|
||||
* @param type type to test
|
||||
* @return true if the type is Indictation, false otherwise
|
||||
*/
|
||||
public static boolean isIndicationType(char type)
|
||||
{
|
||||
return ((type & 0x0110) == STUN_INDICATION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether type could be the type of a STUN Request (as opposed
|
||||
* to STUN Response).
|
||||
* @param type the type to test.
|
||||
* @return true if type is a valid request type.
|
||||
*/
|
||||
public static boolean isRequestType(char type)
|
||||
{
|
||||
/* return !isResponseType(type); */
|
||||
return ((type & 0x0110) == STUN_REQUEST);
|
||||
}
|
||||
|
||||
public String toString()
|
||||
{
|
||||
return getName()+"("+getMessageType()
|
||||
+")[attrib.count=" + getAttributeCount()
|
||||
+" len=" + this.getDataLength()
|
||||
+" tranID=" + this.getTransactionID() + "]";
|
||||
}
|
||||
|
||||
}
|
||||
484
src/org/ice4j/message/MessageFactory.java
Normal file
484
src/org/ice4j/message/MessageFactory.java
Normal file
@ -0,0 +1,484 @@
|
||||
/*
|
||||
* Ice4j, 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 java.util.List;
|
||||
import java.util.logging.*;
|
||||
|
||||
import org.ice4j.*;
|
||||
import org.ice4j.attribute.*;
|
||||
|
||||
/**
|
||||
* This class provides factory methods to allow an application to create
|
||||
* STUN Messages from a particular implementation.
|
||||
*
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France.</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @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.<br/>
|
||||
* This will also add a MESSAGE-INTEGRITY and FINGERPRINT attribute.<br/>
|
||||
* Do not add another attributes after called this method.
|
||||
* @param request the original request
|
||||
* @param username username value
|
||||
* @param realm realm value
|
||||
* @param nonce nonce value
|
||||
*/
|
||||
public static void addLongTermAuthentifcationAttribute(Request request, byte username[], byte realm[], byte nonce[]) throws StunException
|
||||
{
|
||||
UsernameAttribute usernameAttr = AttributeFactory.createUsernameAttribute(username);
|
||||
RealmAttribute realmAttr = AttributeFactory.createRealmAttribute(realm);
|
||||
NonceAttribute nonceAttr = AttributeFactory.createNonceAttribute(nonce);
|
||||
|
||||
request.addAttribute(usernameAttr);
|
||||
request.addAttribute(realmAttr);
|
||||
request.addAttribute(nonceAttr);
|
||||
|
||||
/* TODO calculate MESSAGE-INTEGRITY and FINGERPRINT */
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a refresh request.
|
||||
* @param lifetime lifetime value
|
||||
* @return refresh request
|
||||
*/
|
||||
public static Request createRefreshRequest(int lifetime) throws StunException
|
||||
{
|
||||
Request refreshRequest = new Request();
|
||||
|
||||
try
|
||||
{
|
||||
refreshRequest.setMessageType(Message.REFRESH_REQUEST);
|
||||
|
||||
/* add a LIFETIME attribute */
|
||||
LifetimeAttribute lifetimeReq = AttributeFactory.createLifetimeAttribute(lifetime);
|
||||
refreshRequest.addAttribute(lifetimeReq);
|
||||
}
|
||||
catch(StunException ex)
|
||||
{
|
||||
logger.log(Level.FINE, "Failed to set message type.", ex);
|
||||
}
|
||||
|
||||
return refreshRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ChannelBind request.
|
||||
* @param channelNumber the channel number
|
||||
* @param peerAddress the peer address
|
||||
* @return channelbind request
|
||||
*/
|
||||
public static Request createChannelBindRequest(char channelNumber, TransportAddress peerAddress) throws StunException
|
||||
{
|
||||
Request channelBindRequest = new Request();
|
||||
|
||||
try
|
||||
{
|
||||
channelBindRequest.setMessageType(Message.CHANNELBIND_REQUEST);
|
||||
|
||||
/* add a CHANNEL-NUMBER attribute */
|
||||
ChannelNumberAttribute channelNumberAttribute = AttributeFactory.createChannelNumberAttribute(channelNumber);
|
||||
channelBindRequest.addAttribute(channelNumberAttribute);
|
||||
|
||||
/* add a XOR-PEER-ADDRESS */
|
||||
XorPeerAddressAttribute peerAddressAttribute = AttributeFactory.createXorPeerAddressAttribute(peerAddress);
|
||||
channelBindRequest.addAttribute(peerAddressAttribute);
|
||||
}
|
||||
catch(StunException ex)
|
||||
{
|
||||
logger.log(Level.FINE, "Failed to set message type.", ex);
|
||||
}
|
||||
|
||||
return channelBindRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a Send Indication.
|
||||
* @param peerAddress peer address
|
||||
* @param data data (could be 0 byte)
|
||||
* @return send indication message
|
||||
*/
|
||||
public static Indication createSendIndication(TransportAddress peerAddress, byte data[])
|
||||
{
|
||||
Indication sendIndication = new Indication();
|
||||
|
||||
try
|
||||
{
|
||||
sendIndication.setMessageType(Message.SEND_INDICATION);
|
||||
|
||||
/* add XOR-PEER-ADDRESS attribute */
|
||||
XorPeerAddressAttribute peerAddressAttribute = AttributeFactory.createXorPeerAddressAttribute(peerAddress);
|
||||
sendIndication.addAttribute(peerAddressAttribute);
|
||||
|
||||
/* add DATA if data */
|
||||
if(data != null && data.length > 0)
|
||||
{
|
||||
DataAttribute dataAttribute = AttributeFactory.createDataAttribute(data);
|
||||
sendIndication.addAttribute(dataAttribute);
|
||||
}
|
||||
}
|
||||
catch(StunException ex)
|
||||
{
|
||||
logger.log(Level.FINE, "Failed to set message type.", ex);
|
||||
}
|
||||
|
||||
return sendIndication;
|
||||
}
|
||||
|
||||
|
||||
//======================== NOT CURRENTLY SUPPORTED =============================
|
||||
public static Request createShareSecretRequest()
|
||||
{
|
||||
throw new UnsupportedOperationException(
|
||||
"Shared Secret Support is not currently implemented");
|
||||
}
|
||||
|
||||
public static Response createSharedSecretResponse()
|
||||
{
|
||||
throw new UnsupportedOperationException(
|
||||
"Shared Secret Support is not currently implemented");
|
||||
}
|
||||
|
||||
public static Response createSharedSecretErrorResponse()
|
||||
{
|
||||
throw new UnsupportedOperationException(
|
||||
"Shared Secret Support is not currently implemented");
|
||||
}
|
||||
|
||||
}
|
||||
52
src/org/ice4j/message/Request.java
Normal file
52
src/org/ice4j/message/Request.java
Normal file
@ -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 request descendant of the message class. The primary purpose of the
|
||||
* Request class is to allow better functional definition of the classes in the
|
||||
* stack package.
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class 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);
|
||||
}
|
||||
|
||||
}
|
||||
52
src/org/ice4j/message/Response.java
Normal file
52
src/org/ice4j/message/Response.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class 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);
|
||||
}
|
||||
|
||||
}
|
||||
36
src/org/ice4j/stack/ErrorHandler.java
Normal file
36
src/org/ice4j/stack/ErrorHandler.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France.</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
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);
|
||||
}
|
||||
205
src/org/ice4j/stack/EventDispatcher.java
Normal file
205
src/org/ice4j/stack/EventDispatcher.java
Normal file
@ -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 Vector<RequestListener> requestListeners = null;
|
||||
|
||||
/**
|
||||
* Hashtable for managing property change listeners registered for specific
|
||||
* properties. Maps property names to PropertyChangeSupport objects.
|
||||
*/
|
||||
private Hashtable<NetAccessPointDescriptor, EventDispatcher> requestListenersChildren = null;
|
||||
|
||||
/**
|
||||
* Constructs an <code>EventDispatcher</code> 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 Vector<RequestListener>();
|
||||
}
|
||||
|
||||
if(!requestListeners.contains(listener))
|
||||
requestListeners.addElement(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a RequestListener for a specific NetAccessPoint. The listener
|
||||
* will be invoked only when a call on fireRequestReceived is issued for
|
||||
* that specific NetAccessPoint.
|
||||
*
|
||||
* @param descriptor The NETAP descriptor that we're interested in.
|
||||
* @param listener The ConfigurationChangeListener to be added
|
||||
*/
|
||||
|
||||
public synchronized void addRequestListener(
|
||||
NetAccessPointDescriptor descriptor,
|
||||
RequestListener listener)
|
||||
{
|
||||
if (requestListenersChildren == null)
|
||||
{
|
||||
requestListenersChildren = new Hashtable<NetAccessPointDescriptor, EventDispatcher>();
|
||||
}
|
||||
EventDispatcher child = requestListenersChildren.get(descriptor);
|
||||
if (child == null)
|
||||
{
|
||||
child = new EventDispatcher();
|
||||
requestListenersChildren.put(descriptor, child);
|
||||
}
|
||||
child.addRequestListener(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a RquestListener from the listener list.
|
||||
* This removes a RequestListener that was registered
|
||||
* for all NetAccessPoints and would not remove lsiteners registered for
|
||||
* specific NetAccessPointDescriptors.
|
||||
*
|
||||
* @param listener The RequestListener to be removed
|
||||
*/
|
||||
public synchronized void removeRequestListener(
|
||||
RequestListener listener)
|
||||
{
|
||||
|
||||
if (requestListeners == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
requestListeners.removeElement(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a RequestListener for a specific NetAccessPointDescriptor. This
|
||||
* would only remove the listener for the specified NetAccessPointDescriptor
|
||||
* and would not remove it if it was also registered as a wildcard listener.
|
||||
*
|
||||
* @param apDescriptor The NetAPDescriptor that was listened on.
|
||||
* @param listener The RequestListener to be removed
|
||||
*/
|
||||
public synchronized void removeRequestListener(
|
||||
NetAccessPointDescriptor apDescriptor,
|
||||
RequestListener listener)
|
||||
{
|
||||
if (requestListenersChildren == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
EventDispatcher child = requestListenersChildren.get( apDescriptor );
|
||||
|
||||
if (child == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
child.removeRequestListener(listener);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Dispatch a StunMessageEvent to any registered listeners.
|
||||
*
|
||||
* @param evt The request event to be delivered.
|
||||
*/
|
||||
public void fireMessageEvent(StunMessageEvent evt)
|
||||
{
|
||||
NetAccessPointDescriptor apDescriptor = evt.getSourceAccessPoint();
|
||||
if (requestListeners != null)
|
||||
{
|
||||
Iterator iterator = null;
|
||||
synchronized(requestListeners)
|
||||
{
|
||||
iterator = new ArrayList<RequestListener>(requestListeners).iterator();
|
||||
}
|
||||
|
||||
while (iterator.hasNext())
|
||||
{
|
||||
RequestListener target =
|
||||
(RequestListener) iterator.next();
|
||||
target.requestReceived(evt);
|
||||
}
|
||||
}
|
||||
|
||||
if (requestListenersChildren != null && apDescriptor != null)
|
||||
{
|
||||
EventDispatcher child
|
||||
= requestListenersChildren.get(apDescriptor);
|
||||
apDescriptor.getAddress().toString();
|
||||
|
||||
if (child != null)
|
||||
{
|
||||
child.fireMessageEvent(evt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if there are any listeners for a specific NetAccessPointDescriptor.
|
||||
* (Generic listeners count as well)
|
||||
*
|
||||
* @param apDescriptor the NetAccessPointDescriptor.
|
||||
* @return true if there are one or more listeners for the specified
|
||||
* NetAccessPointDescriptor
|
||||
*/
|
||||
public synchronized boolean hasRequestListeners(
|
||||
NetAccessPointDescriptor apDescriptor)
|
||||
{
|
||||
if(requestListeners != null && !requestListeners.isEmpty())
|
||||
{
|
||||
// there is a generic listener
|
||||
return true;
|
||||
}
|
||||
if (requestListenersChildren != null)
|
||||
{
|
||||
EventDispatcher child = requestListenersChildren.get(apDescriptor);
|
||||
if (child != null && child.requestListeners != null)
|
||||
{
|
||||
return!child.requestListeners.isEmpty();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes (absolutely all listeners for this event dispatcher).
|
||||
*/
|
||||
public void removeAllListeners()
|
||||
{
|
||||
if(requestListeners != null)
|
||||
requestListeners.removeAllElements();
|
||||
requestListenersChildren = null;
|
||||
}
|
||||
}
|
||||
30
src/org/ice4j/stack/MessageEventHandler.java
Normal file
30
src/org/ice4j/stack/MessageEventHandler.java
Normal file
@ -0,0 +1,30 @@
|
||||
/*
|
||||
* 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.*;
|
||||
|
||||
/**
|
||||
* The class is used for collecting incoming STUN messages from the
|
||||
* NetAccessManager (and more precisely - MessageProcessors). This is our
|
||||
* way of keeping scalable network and stun layers.
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
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);
|
||||
}
|
||||
172
src/org/ice4j/stack/MessageProcessor.java
Normal file
172
src/org/ice4j/stack/MessageProcessor.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
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 <tt>MessageQueue</tt> where we'll be storing incoming
|
||||
* messages.
|
||||
* @param messageHandler MessageEventHandler
|
||||
* @param errorHandler the <tt>ErrorHandler</tt> 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;
|
||||
}
|
||||
}
|
||||
109
src/org/ice4j/stack/MessageQueue.java
Normal file
109
src/org/ice4j/stack/MessageQueue.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
*
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
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 Vector<RawMessage> queue = new Vector<RawMessage>();
|
||||
|
||||
//keep a copy of the fifo size and make it accessible for concurrent queries.
|
||||
private int size = 0;
|
||||
|
||||
/**
|
||||
* Create an empty MessaeFIFO
|
||||
*/
|
||||
MessageQueue()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of messages currently in the queue.
|
||||
* @return the number of messages in the queue.
|
||||
*/
|
||||
public int getSize()
|
||||
{
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the FIFO is currently empty.
|
||||
* @return true if the FIFO is currently empty and false otherwise.
|
||||
*/
|
||||
public boolean isEmpty()
|
||||
{
|
||||
return (size == 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the specified message to the queue.
|
||||
*
|
||||
* @param rawMessage the message to add.
|
||||
*/
|
||||
public synchronized void add(RawMessage rawMessage)
|
||||
{
|
||||
logger.finest("Adding raw message to queue.");
|
||||
queue.add(rawMessage);
|
||||
size++;
|
||||
|
||||
notifyAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes and returns the oldest message from the fifo. If there are
|
||||
* currently no messages in the queue the method block until there is at
|
||||
* least one message.
|
||||
*
|
||||
*
|
||||
* @return the oldest message in the fifo.
|
||||
* @throws java.lang.InterruptedException if an InterruptedException is thrown
|
||||
* wail waiting for a new message to be added.
|
||||
*/
|
||||
public synchronized RawMessage remove()
|
||||
throws InterruptedException
|
||||
{
|
||||
waitWhileEmpty();
|
||||
RawMessage rawMessage = queue.remove(0);
|
||||
|
||||
size--;
|
||||
return rawMessage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocks until there is at least one message in the queue.
|
||||
*
|
||||
* @throws java.lang.InterruptedException if an InterruptedException is thrown
|
||||
* wail waiting for a new message to be added.
|
||||
*/
|
||||
public synchronized void waitWhileEmpty() throws InterruptedException
|
||||
{
|
||||
while (isEmpty())
|
||||
{
|
||||
wait();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
323
src/org/ice4j/stack/NetAccessManager.java
Normal file
323
src/org/ice4j/stack/NetAccessManager.java
Normal file
@ -0,0 +1,323 @@
|
||||
/*
|
||||
* 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.Hashtable;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import java.net.DatagramSocket;
|
||||
import java.util.logging.*;
|
||||
|
||||
import org.ice4j.*;
|
||||
import org.ice4j.message.*;
|
||||
|
||||
/**
|
||||
* Manages NetAccessPoints and MessageProcessor pooling. This class serves as a
|
||||
* layer that masks network primitives and provides equivalent STUN abstractions.
|
||||
* Instances that operate with the NetAccessManager are only supposed to
|
||||
* understand STUN talk and shouldn't be aware of datagrams sockets, and etc.
|
||||
*
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
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 Hashtable<NetAccessPointDescriptor, NetAccessPoint> netAccessPoints = new Hashtable<NetAccessPointDescriptor, NetAccessPoint>();
|
||||
|
||||
/**
|
||||
* A synchronized FIFO where incoming messages are stocked for processing.
|
||||
*/
|
||||
private MessageQueue messageQueue = new MessageQueue();
|
||||
|
||||
/**
|
||||
* A thread pool of message processors.
|
||||
*/
|
||||
private Vector<MessageProcessor> messageProcessors = new Vector<MessageProcessor>();
|
||||
|
||||
/**
|
||||
* The instance that should be notified whan an incoming message has been
|
||||
* processed and ready for delivery
|
||||
*/
|
||||
private MessageEventHandler messageEventHandler = null;
|
||||
|
||||
/**
|
||||
* The size of the thread pool to start with.
|
||||
*/
|
||||
private int initialThreadPoolSize = StunStack.DEFAULT_THREAD_POOL_SIZE;
|
||||
|
||||
/**
|
||||
* Constructs a NetAccessManager.
|
||||
*
|
||||
* @param evtHandler the handler that incoming message requests should be
|
||||
* passed to.
|
||||
*/
|
||||
NetAccessManager(MessageEventHandler evtHandler)
|
||||
{
|
||||
setEventHandler(evtHandler);
|
||||
initThreadPool();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the instance to notify for incoming message events.
|
||||
* @param evtHandler the entity that will handle incoming messages.
|
||||
*/
|
||||
void setEventHandler(MessageEventHandler evtHandler)
|
||||
{
|
||||
messageEventHandler = evtHandler;
|
||||
}
|
||||
|
||||
//------------------------ error handling -------------------------------------
|
||||
/**
|
||||
* A civilized way of not caring!
|
||||
* @param message a description of the error
|
||||
* @param error the error that has occurred
|
||||
*/
|
||||
public void handleError(String message, Throwable error)
|
||||
{
|
||||
/**
|
||||
* apart from logging, i am not sure what else we could do here.
|
||||
*/
|
||||
logger.log( Level.WARNING, "The following error occurred", error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the faulty thread and tries to repair the damage and instanciate
|
||||
* a replacement.
|
||||
*
|
||||
* @param callingThread the thread where the error occurred.
|
||||
* @param message A description of the error
|
||||
* @param error The error itself
|
||||
*/
|
||||
public void handleFatalError(Runnable callingThread,
|
||||
String message,
|
||||
Throwable error)
|
||||
{
|
||||
if (callingThread instanceof NetAccessPoint)
|
||||
{
|
||||
NetAccessPoint ap = (NetAccessPoint)callingThread;
|
||||
|
||||
//make sure socket is closed
|
||||
removeNetAccessPoint(ap.getDescriptor());
|
||||
|
||||
try
|
||||
{
|
||||
logger.log( Level.WARNING, "An access point has unexpectedly "
|
||||
+"stopped. AP:" + ap.toString(), error);
|
||||
installNetAccessPoint(ap.getDescriptor());
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
//make sure nothing's left and notify user
|
||||
removeNetAccessPoint(ap.getDescriptor());
|
||||
logger.log(Level.WARNING, "Failed to relaunch accesspoint:" + ap,
|
||||
ex);
|
||||
}
|
||||
}
|
||||
else if( callingThread instanceof MessageProcessor )
|
||||
{
|
||||
MessageProcessor mp = (MessageProcessor)callingThread;
|
||||
logger.log( Level.WARNING, "A message processor has unexpectedly "
|
||||
+"stopped. AP:" + mp.toString(), error);
|
||||
|
||||
//make sure the guy's dead.
|
||||
mp.stop();
|
||||
messageProcessors.remove(mp);
|
||||
|
||||
mp = new MessageProcessor(messageQueue, messageEventHandler, this);
|
||||
mp.start();
|
||||
logger.fine("A message processor has been relaunched because "
|
||||
+"of an error.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and starts a new access point according to the given descriptor.
|
||||
* If the specified access point has already been installed the method
|
||||
* has no effect.
|
||||
*
|
||||
* @param apDescriptor a description of the access point to create.
|
||||
* @throws IOException if we fail to bind a datagram socket on the specified
|
||||
* address and port (NetAccessPointDescriptor)
|
||||
*/
|
||||
void installNetAccessPoint(NetAccessPointDescriptor apDescriptor)
|
||||
throws IOException
|
||||
{
|
||||
if(netAccessPoints.containsKey(apDescriptor))
|
||||
return;
|
||||
|
||||
NetAccessPoint ap = new NetAccessPoint(apDescriptor, messageQueue, this);
|
||||
netAccessPoints.put(apDescriptor, ap);
|
||||
ap.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and starts a new access point based on the specified socket.
|
||||
* If the specified access point has already been installed the method
|
||||
* has no effect.
|
||||
*
|
||||
* @param socket the socket that the access point should use.
|
||||
* @return an access point descriptor to allow further management of the
|
||||
* newly created access point.
|
||||
*
|
||||
* @throws IOException if we fail to setup the socket.
|
||||
*/
|
||||
NetAccessPointDescriptor installNetAccessPoint(DatagramSocket socket)
|
||||
throws IOException
|
||||
{
|
||||
|
||||
//no null check - let it through a null pointer exception
|
||||
TransportAddress address = new TransportAddress(socket.getLocalAddress(), socket.getLocalPort());
|
||||
NetAccessPointDescriptor apDescriptor = new NetAccessPointDescriptor(address);
|
||||
|
||||
if(netAccessPoints.containsKey(apDescriptor))
|
||||
return apDescriptor;
|
||||
|
||||
NetAccessPoint ap = new NetAccessPoint(apDescriptor, messageQueue, this);
|
||||
//call the useExternalSocket method to avoid closing the socket when
|
||||
//removing the accesspoint. Bug Report - Dave Stuart - SipQuest
|
||||
ap.useExternalSocket(socket);
|
||||
netAccessPoints.put(apDescriptor, ap);
|
||||
|
||||
ap.start();
|
||||
|
||||
return apDescriptor;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Stops and deletes the specified access point.
|
||||
* @param apDescriptor the access point to remove
|
||||
*/
|
||||
void removeNetAccessPoint(NetAccessPointDescriptor apDescriptor)
|
||||
{
|
||||
NetAccessPoint ap = netAccessPoints.remove(apDescriptor);
|
||||
|
||||
if(ap != null)
|
||||
ap.stop();
|
||||
}
|
||||
|
||||
//---------------thread pool implementation --------------------------------
|
||||
/**
|
||||
* Adjusts the number of concurrently running MessageProcessors.
|
||||
* If the number is smaller or bigger than the number of threads
|
||||
* currentlyrunning, then message processors are created/deleted so that
|
||||
* their count matches the new value.
|
||||
*
|
||||
* @param threadPoolSize the number of MessageProcessors that should be
|
||||
* running concurrently
|
||||
* @throws IllegalArgumentException if threadPoolSize is not a valid size.
|
||||
*/
|
||||
void setThreadPoolSize(int threadPoolSize)
|
||||
throws IllegalArgumentException
|
||||
{
|
||||
if(threadPoolSize < 1)
|
||||
throw new IllegalArgumentException(
|
||||
threadPoolSize
|
||||
+ " is not a legal thread pool size value.");
|
||||
|
||||
//if we are not running just record the size
|
||||
//so that we could init later.
|
||||
if(messageProcessors.size() < threadPoolSize)
|
||||
{
|
||||
//create additional processors
|
||||
fillUpThreadPool(threadPoolSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
//delete extra processors
|
||||
shrinkThreadPool(threadPoolSize);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws StunException INVALID_ARGUMENT if threadPoolSize is not a
|
||||
* valid size.
|
||||
*/
|
||||
private void initThreadPool()
|
||||
{
|
||||
//create additional processors
|
||||
fillUpThreadPool(initialThreadPoolSize);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Starts all message processors
|
||||
*
|
||||
* @param newSize the new thread poolsize
|
||||
*/
|
||||
private void fillUpThreadPool(int newSize)
|
||||
{
|
||||
//make sure we don't resize more than once
|
||||
messageProcessors.ensureCapacity(newSize);
|
||||
|
||||
for (int i = messageProcessors.size(); i < newSize; i++)
|
||||
{
|
||||
MessageProcessor mp = new MessageProcessor(messageQueue,
|
||||
messageEventHandler,
|
||||
this);
|
||||
messageProcessors.add(mp);
|
||||
|
||||
mp.start();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts all message processors
|
||||
*
|
||||
* @param newSize the new thread poolsize
|
||||
*/
|
||||
private void shrinkThreadPool(int newSize)
|
||||
{
|
||||
while(messageProcessors.size() > newSize)
|
||||
{
|
||||
MessageProcessor mp = messageProcessors.remove(0);
|
||||
mp.stop();
|
||||
}
|
||||
}
|
||||
|
||||
//--------------- SENDING MESSAGES -----------------------------------------
|
||||
/**
|
||||
* Sends the specified stun message through the specified access point.
|
||||
*
|
||||
* @param stunMessage the message to send
|
||||
* @param apDescriptor the access point to use to send the message
|
||||
* @param address the destination of the message.
|
||||
*
|
||||
* @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 sendMessage(Message stunMessage,
|
||||
NetAccessPointDescriptor apDescriptor,
|
||||
TransportAddress address)
|
||||
throws IOException, IllegalArgumentException, StunException
|
||||
{
|
||||
byte[] bytes = stunMessage.encode();
|
||||
NetAccessPoint ap = netAccessPoints.get(apDescriptor);
|
||||
|
||||
if(ap == null)
|
||||
throw new IllegalArgumentException(
|
||||
"The specified access point had not been installed.");
|
||||
|
||||
ap.sendMessage(bytes, address);
|
||||
}
|
||||
|
||||
}
|
||||
325
src/org/ice4j/stack/NetAccessPoint.java
Normal file
325
src/org/ice4j/stack/NetAccessPoint.java
Normal file
@ -0,0 +1,325 @@
|
||||
/*
|
||||
* 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.io.IOException;
|
||||
import java.net.*;
|
||||
import java.util.logging.*;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
* The Network Access Point is the most outward part of the stack. It is
|
||||
* constructed around a datagram socket and takes care about forwarding incoming
|
||||
* messages to the MessageProcessor as well as sending datagrams to the STUN server
|
||||
* specified by the original NetAccessPointDescriptor.
|
||||
*
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
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 the <code>useExternalSocket()</code> method and is consulted
|
||||
* inside the stop method. When its value is true, the AP's socket is not
|
||||
* closed when <code>stop()</code>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 <code>stop()</code>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;
|
||||
}
|
||||
}
|
||||
113
src/org/ice4j/stack/RawMessage.java
Normal file
113
src/org/ice4j/stack/RawMessage.java
Normal file
@ -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).
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
*
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
24
src/org/ice4j/stack/RequestListener.java
Normal file
24
src/org/ice4j/stack/RequestListener.java
Normal file
@ -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.*;
|
||||
|
||||
/**
|
||||
* <p>Title: Stun4J.</p>
|
||||
* <p>Description: Simple Traversal of UDP Through NAT.</p>
|
||||
* <p>Copyright: Copyright (c) 2003.</p>
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France.</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr).</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public interface RequestListener
|
||||
{
|
||||
public void requestReceived(StunMessageEvent evt);
|
||||
}
|
||||
400
src/org/ice4j/stack/StunClientTransaction.java
Normal file
400
src/org/ice4j/stack/StunClientTransaction.java
Normal file
@ -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.
|
||||
*
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
322
src/org/ice4j/stack/StunProvider.java
Normal file
322
src/org/ice4j/stack/StunProvider.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class StunProvider
|
||||
implements MessageEventHandler
|
||||
{
|
||||
private static final Logger logger =
|
||||
Logger.getLogger(StunProvider.class.getName());
|
||||
|
||||
/**
|
||||
* Stores active client transactions mapped against TransactionID-s.
|
||||
*/
|
||||
private Hashtable<TransactionID, StunClientTransaction> clientTransactions = new Hashtable<TransactionID, StunClientTransaction>();
|
||||
|
||||
/**
|
||||
* Currently open server transactions. The vector contains transaction ids
|
||||
* for transactions corresponding to all non-answered received requests.
|
||||
*/
|
||||
private Hashtable<TransactionID, StunServerTransaction> serverTransactions = new Hashtable<TransactionID, StunServerTransaction>();
|
||||
|
||||
/**
|
||||
* The stack that created us.
|
||||
*/
|
||||
private StunStack stunStack = null;
|
||||
|
||||
/**
|
||||
* A dispatcher for incoming requests event;
|
||||
*/
|
||||
private EventDispatcher eventDispatcher = new EventDispatcher();
|
||||
|
||||
|
||||
|
||||
//------------------ public interface
|
||||
/**
|
||||
* Creates the provider.
|
||||
* @param stunStack The currently active stack instance.
|
||||
*/
|
||||
StunProvider(StunStack stunStack)
|
||||
{
|
||||
this.stunStack = stunStack;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the specified request through the specified access point, and
|
||||
* registers the specified ResponseCollector for later notification.
|
||||
* @param request the request to send
|
||||
* @param sendTo the destination address of the request.
|
||||
* @param sendThrough the access point to use when sending the request
|
||||
* @param collector the instance to notify when a response arrives or the
|
||||
* the transaction timeouts
|
||||
*
|
||||
* @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 void sendRequest( Request request,
|
||||
TransportAddress sendTo,
|
||||
NetAccessPointDescriptor sendThrough,
|
||||
ResponseCollector collector )
|
||||
throws StunException, IOException, IllegalArgumentException
|
||||
{
|
||||
StunClientTransaction clientTransaction
|
||||
= new StunClientTransaction(this,
|
||||
request,
|
||||
sendTo,
|
||||
sendThrough,
|
||||
collector);
|
||||
|
||||
clientTransactions.put(clientTransaction.getTransactionID(),
|
||||
clientTransaction);
|
||||
clientTransaction.sendRequest();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the specified response message through the specified access point.
|
||||
*
|
||||
* @param transactionID the id of the transaction to use when sending the
|
||||
* response. Actually we are getting kind of redundant here as we already
|
||||
* have the id in the response object, but I am bringing out as an extra
|
||||
* parameter as the user might otherwise forget to explicitly set it.
|
||||
* @param response the message to send.
|
||||
* @param sendThrough the access point to use when sending the message.
|
||||
* @param sendTo the destination of the message.
|
||||
*
|
||||
* @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 void sendResponse(byte[] transactionID,
|
||||
Response response,
|
||||
NetAccessPointDescriptor sendThrough,
|
||||
TransportAddress sendTo)
|
||||
throws StunException,
|
||||
IOException,
|
||||
IllegalArgumentException
|
||||
{
|
||||
TransactionID tid = TransactionID.createTransactionID(transactionID);
|
||||
StunServerTransaction sTran =
|
||||
serverTransactions.get(tid);
|
||||
|
||||
if(sTran == null || sTran.isReransmitting()){
|
||||
throw new StunException(StunException.TRANSACTION_DOES_NOT_EXIST,
|
||||
"The transaction specified in the response "
|
||||
+ "object does not exist or has already "
|
||||
+ "transmitted a response.");
|
||||
}
|
||||
else{
|
||||
sTran.sendResponse(response, sendThrough, sendTo);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the listener that should be notified when a new Request is received.
|
||||
* @param requestListener the listener interested in incoming requests.
|
||||
*/
|
||||
public void addRequestListener(RequestListener requestListener)
|
||||
{
|
||||
this.eventDispatcher.addRequestListener( requestListener );
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the specified listener from the local listener list. (If any
|
||||
* instances of this listener have been registered for a particular
|
||||
* access point, they will not be removed).
|
||||
* @param listener the RequestListener listener to unregister
|
||||
*/
|
||||
public void removeRequestListener(RequestListener listener)
|
||||
{
|
||||
this.eventDispatcher.removeRequestListener(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a RequestListener for requests coming from a specific NetAccessPoint.
|
||||
* The listener will be invoked only when a request event is received on
|
||||
* that specific property.
|
||||
*
|
||||
* @param apDescriptor The descriptor of the NetAccessPoint to listen on.
|
||||
* @param listener The ConfigurationChangeListener to be added
|
||||
*/
|
||||
|
||||
public synchronized void addRequestListener(
|
||||
NetAccessPointDescriptor apDescriptor,
|
||||
RequestListener listener)
|
||||
{
|
||||
eventDispatcher.addRequestListener(apDescriptor, listener);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//------------- stack internals ------------------------------------------------
|
||||
/**
|
||||
* Returns the currently active instance of NetAccessManager. Used by client
|
||||
* transactions when sending messages.
|
||||
* @return the currently active instance of NetAccessManager.
|
||||
*/
|
||||
NetAccessManager getNetAccessManager()
|
||||
{
|
||||
return stunStack.getNetAccessManager();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a client transaction from this providers client transactions list.
|
||||
* Method is used by StunClientTransaction-s themselves when a timeout occurs.
|
||||
* @param tran the transaction to remove.
|
||||
*/
|
||||
synchronized void removeClientTransaction(StunClientTransaction tran)
|
||||
{
|
||||
clientTransactions.remove(tran.getTransactionID());
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a server transaction from this provider's server transactions
|
||||
* list.
|
||||
* Method is used by StunServerTransaction-s themselves when they expire.
|
||||
* @param tran the transaction to remove.
|
||||
*/
|
||||
synchronized void removeServerTransaction(StunServerTransaction tran)
|
||||
{
|
||||
serverTransactions.remove(tran.getTransactionID());
|
||||
}
|
||||
|
||||
/**
|
||||
* Called to notify this provider for an incoming message.
|
||||
* @param event the event object that contains the new message.
|
||||
*/
|
||||
public void handleMessageEvent(StunMessageEvent event)
|
||||
{
|
||||
Message msg = event.getMessage();
|
||||
|
||||
if(logger.isLoggable(Level.FINEST))
|
||||
logger.finest("Received a message on NetAP"
|
||||
+ event.getSourceAccessPoint()
|
||||
+ " of type:"
|
||||
+ (int)msg.getMessageType());
|
||||
|
||||
//request
|
||||
if(msg instanceof Request)
|
||||
{
|
||||
logger.finest("parsing request");
|
||||
TransactionID serverTid = TransactionID.
|
||||
createTransactionID(msg.getTransactionID());
|
||||
|
||||
StunServerTransaction sTran = serverTransactions.get(serverTid);
|
||||
if( sTran != null){
|
||||
|
||||
//requests from this transaction have already been seen
|
||||
//retransmit the response if there was any
|
||||
logger.finest("found an existing transaction");
|
||||
|
||||
try
|
||||
{
|
||||
sTran.retransmitResponse();
|
||||
logger.finest("Response retransmitted");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//we couldn't really do anything here .. apart from logging
|
||||
logger.log(Level.WARNING,
|
||||
"Failed to retransmit a stun response", ex);
|
||||
}
|
||||
|
||||
String propagate = System.getProperty(
|
||||
"org.ice4j.PROPAGATE_RECEIVED_RETRANSMISSIONS");
|
||||
if(propagate == null || !propagate.trim().equalsIgnoreCase("true"))
|
||||
return;
|
||||
}
|
||||
else{
|
||||
logger.finest("exising transaction not found");
|
||||
sTran =
|
||||
new StunServerTransaction(this, serverTid);
|
||||
|
||||
serverTransactions.put(serverTid, sTran);
|
||||
sTran.start();
|
||||
}
|
||||
eventDispatcher.fireMessageEvent(event);
|
||||
}
|
||||
//response
|
||||
else if(msg instanceof Response)
|
||||
{
|
||||
TransactionID tid = TransactionID.
|
||||
createTransactionID(msg.getTransactionID());
|
||||
|
||||
StunClientTransaction tran =
|
||||
clientTransactions.remove(tid);
|
||||
|
||||
if(tran != null)
|
||||
{
|
||||
tran.handleResponse(event);
|
||||
}
|
||||
else
|
||||
{
|
||||
//do nothing - just drop the phantom response.
|
||||
logger.fine("Dropped response - no matching client tran found.");
|
||||
logger.fine("response tid was - " + tid.toString());
|
||||
logger.fine("all tids in stock were" + clientTransactions.toString());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels all running transactions and prepares for garbage collection
|
||||
*/
|
||||
void shutDown()
|
||||
{
|
||||
eventDispatcher.removeAllListeners();
|
||||
|
||||
Enumeration tids = clientTransactions.keys();
|
||||
while (tids.hasMoreElements()) {
|
||||
TransactionID item = (TransactionID)tids.nextElement();
|
||||
StunClientTransaction tran = clientTransactions.remove(item);
|
||||
if(tran != null)
|
||||
tran.cancel();
|
||||
|
||||
}
|
||||
|
||||
tids = serverTransactions.keys();
|
||||
while (tids.hasMoreElements()) {
|
||||
TransactionID item = (TransactionID)tids.nextElement();
|
||||
StunServerTransaction tran =
|
||||
serverTransactions.remove(item);
|
||||
if(tran != null)
|
||||
tran.expire();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
261
src/org/ice4j/stack/StunServerTransaction.java
Normal file
261
src/org/ice4j/stack/StunServerTransaction.java
Normal file
@ -0,0 +1,261 @@
|
||||
/*
|
||||
* 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.TimerTask;
|
||||
import java.io.*;
|
||||
|
||||
import org.ice4j.*;
|
||||
import org.ice4j.message.*;
|
||||
|
||||
/**
|
||||
* A STUN client retransmits requests as specified by the protocol.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* A server transaction is therefore responsible for retransmitting the same
|
||||
* response that was saved for the original request, and not let any
|
||||
* retransmissions go through to the user application.
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
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 the <code>sendThrough</code>
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
142
src/org/ice4j/stack/StunStack.java
Normal file
142
src/org/ice4j/stack/StunStack.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
public class 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;
|
||||
}
|
||||
}
|
||||
172
src/org/ice4j/stack/TransactionID.java
Normal file
172
src/org/ice4j/stack/TransactionID.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
126
src/org/ice4j/stunclient/BlockingRequestSender.java
Normal file
126
src/org/ice4j/stunclient/BlockingRequestSender.java
Normal file
@ -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();
|
||||
* }
|
||||
*
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -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.*;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* This class implements the STUN Discovery Process as described by section 10.1
|
||||
* of rfc 3489.
|
||||
* </p><p>
|
||||
* 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.
|
||||
* </p><p>
|
||||
* 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.
|
||||
* </p><p>
|
||||
* 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.
|
||||
* </p><p>
|
||||
* 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.
|
||||
* </p><p>
|
||||
* 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.
|
||||
* </p><p>
|
||||
* 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).
|
||||
* </p><p>
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class 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.
|
||||
*/
|
||||
269
src/org/ice4j/stunclient/SimpleAddressDetector.java
Normal file
269
src/org/ice4j/stunclient/SimpleAddressDetector.java
Normal file
@ -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.
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class 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 <tt>address</tt> 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 <tt>port</tt> 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();
|
||||
}
|
||||
*/
|
||||
}
|
||||
203
src/org/ice4j/stunclient/StunClient.java
Executable file
203
src/org/ice4j/stunclient/StunClient.java
Executable file
@ -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 HashMap<byte[], Request> requestMap = new HashMap<byte[], Request>();
|
||||
|
||||
public StunClient(StunStack stunStack)
|
||||
{
|
||||
this.stunStack = stunStack;
|
||||
|
||||
stunProvider = stunStack.getProvider();
|
||||
}
|
||||
|
||||
//------------------ Implemented methods of the ResponseCollector interface -------------
|
||||
/**
|
||||
* This callBack method is called in a separate thread to process
|
||||
* incomming response
|
||||
*/
|
||||
public void processResponse(StunMessageEvent response) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
Message responseMsg = response.getMessage(); /* retrieving the response message */
|
||||
|
||||
byte[] tid = responseMsg.getTransactionID(); /* retrieving the Transaction ID */
|
||||
|
||||
synchronized(requestMap)
|
||||
{
|
||||
if(requestMap.containsKey(tid))
|
||||
{
|
||||
// TODO : process the response
|
||||
requestMap.remove(tid);
|
||||
// TODO : additional processing ; set done status for the candidate pair
|
||||
}
|
||||
}
|
||||
|
||||
MappedAddressAttribute mappedAttribute =
|
||||
(MappedAddressAttribute)responseMsg.getAttribute(Attribute.MAPPED_ADDRESS);
|
||||
|
||||
if(mappedAttribute != null)
|
||||
{
|
||||
TransportAddress mappedAddr = mappedAttribute.getAddress();
|
||||
System.out.println("The mapped address : " + mappedAddr.getHostAddress() +
|
||||
" : " + (int)mappedAddr.getPort());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void processTimeout() {
|
||||
// TODO Auto-generated method stub
|
||||
// How can you recognize which request (TransactionID) timed-out
|
||||
// ignore it at the moment
|
||||
}
|
||||
|
||||
|
||||
//-------------------- Public interface ---------------------------------------
|
||||
|
||||
// TODO : move them up
|
||||
private boolean ended = false;
|
||||
private Object sendLock = new Object();
|
||||
|
||||
/**
|
||||
* Determines the public IP of the specified Transport address in a blocking manner
|
||||
*/
|
||||
public TransportAddress determineAddress(TransportAddress localAddress,
|
||||
TransportAddress serverAddress)
|
||||
throws StunException, IOException
|
||||
{
|
||||
NetAccessPointDescriptor apDescriptor
|
||||
= new NetAccessPointDescriptor(localAddress);
|
||||
Request request = MessageFactory.createBindingRequest();
|
||||
|
||||
stunStack.installNetAccessPoint(apDescriptor);
|
||||
|
||||
synchronized (sendLock)
|
||||
{
|
||||
try
|
||||
{
|
||||
stunProvider.sendRequest(request, serverAddress,
|
||||
apDescriptor, this);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
logger.warning("Cannot determine mapped address for " + localAddress);
|
||||
}
|
||||
}
|
||||
|
||||
ended = false;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the NAT type
|
||||
*/
|
||||
public TransportAddress determineAddress(NetAccessPointDescriptor apDescriptor,
|
||||
TransportAddress serverAddress)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* TODO : modify the signature of the method
|
||||
*
|
||||
* @param request The stun Request object
|
||||
* @param sendTo The address of the server
|
||||
* @param apDescriptor The NetAccessPointDescriptor
|
||||
* @param collector The response collector
|
||||
*/
|
||||
public void sendStunRequest(Request request,
|
||||
TransportAddress sendTo,
|
||||
NetAccessPointDescriptor apDescriptor, // apDescriptor must be installed in the stack
|
||||
ResponseCollector collector)
|
||||
throws StunException, IOException, IllegalArgumentException
|
||||
{
|
||||
logger.log(Level.INFO, "Sending the request ... ");
|
||||
try
|
||||
{
|
||||
stunProvider.sendRequest(request, sendTo, apDescriptor, collector);
|
||||
synchronized (requestMap) {
|
||||
requestMap.put(request.getTransactionID(), request);
|
||||
}
|
||||
}
|
||||
catch(StunException ex)
|
||||
{
|
||||
logger.log(Level.SEVERE, "StunException occurred..", ex);
|
||||
throw new StunException();
|
||||
}
|
||||
catch(IOException ex)
|
||||
{
|
||||
logger.log(Level.SEVERE, "IOException occurred", ex);
|
||||
throw new StunException();
|
||||
}
|
||||
catch(IllegalArgumentException ex)
|
||||
{
|
||||
logger.log(Level.SEVERE, "IllegalArgumentException occurred", ex);
|
||||
throw new StunException();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/*public static void main(String[] args) throws IOException, IllegalArgumentException, StunException
|
||||
{
|
||||
StunStack stunStack = StunStack.getInstance();
|
||||
|
||||
NetAccessPointDescriptor apDescriptor =
|
||||
new NetAccessPointDescriptor(new TransportAddress("localhost", 5009));
|
||||
|
||||
stunStack.installNetAccessPoint(apDescriptor);
|
||||
|
||||
StunClient stunClient = new StunClient(stunStack);
|
||||
|
||||
// create the Stun Request message
|
||||
Request request = MessageFactory.createBindingRequest();
|
||||
|
||||
TransportAddress serverAddress = new TransportAddress("localhost", 4006);
|
||||
|
||||
stunClient.sendStunRequest(request, serverAddress, apDescriptor, stunClient);
|
||||
|
||||
|
||||
}*/
|
||||
}
|
||||
149
src/org/ice4j/stunclient/StunDiscoveryReport.java
Normal file
149
src/org/ice4j/stunclient/StunDiscoveryReport.java
Normal file
@ -0,0 +1,149 @@
|
||||
/*
|
||||
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Distributable under LGPL license.
|
||||
* See terms of license at gnu.org.
|
||||
*/
|
||||
package org.ice4j.stunclient;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
* The class is used to deliver results from a STUN Discovery Process. It
|
||||
* contains information about the NAT Server (or firewall )this client is behind,
|
||||
* and a mapped address value (if discovered)
|
||||
*
|
||||
*
|
||||
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
|
||||
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
|
||||
* @author Emil Ivov
|
||||
* @version 0.1
|
||||
*/
|
||||
|
||||
public class 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();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user