Ongoing work on connectivity checks. Support for XOR-MAPPED-ADDRESS attributes in Binding Responses

This commit is contained in:
emcho 2010-04-25 14:40:11 +00:00
parent cf2bee10aa
commit b75359ad69
16 changed files with 471 additions and 390 deletions

View File

@ -253,19 +253,26 @@ public class AttributeFactory
return attribute;
};
/* ------------------------------------ XOR-RELAYED-ADRESS attribute ------------------------ */
/**
* Creates a XorRelayedAddressAttribute of the specified type and with
* the specified address and port
* the specified address and port.
*
* @param address the address value of the address attribute
* @param tranID the ID of the transaction that we will be using for the XOR
* mask.
*
* @return the newly created address attribute.
*/
public static XorRelayedAddressAttribute createXorRelayedAddressAttribute(TransportAddress address)
public static XorRelayedAddressAttribute createXorRelayedAddressAttribute(
TransportAddress address,
byte[] tranID)
{
XorRelayedAddressAttribute attribute = new XorRelayedAddressAttribute();
attribute.setAddress(address);
//TODO (Emil): shouldn't we be XORing the address before setting it?
attribute.setAddress(address, tranID);
return attribute;
}
@ -273,17 +280,45 @@ public class AttributeFactory
/**
* Creates a XorPeerAddressAttribute of the specified type and with
* the specified address and port
*
* @param address the address value of the address attribute
* @param tranID the ID of the transaction that we will be using for the XOR
* mask.
* @return the newly created address attribute.
*/
public static XorPeerAddressAttribute createXorPeerAddressAttribute(TransportAddress address)
public static XorPeerAddressAttribute createXorPeerAddressAttribute(
TransportAddress address,
byte[] tranID)
{
XorPeerAddressAttribute attribute = new XorPeerAddressAttribute();
attribute.setAddress(address);
//TODO (Emil): shouldn't we be XORing the address before setting it?
attribute.setAddress(address, tranID);
return attribute;
}
//------------------------------------ XOR MAPPED ADDRESS --------------------------
/**
* Creates a XorMappedAddressAttribute for the specified <tt>address</tt>.
*
* @param address the address value of the address attribute
* @param tranID the ID of the transaction that we will be using for the XOR
* mask.
*
* @return the newly created xor address attribute.
*/
public static XorMappedAddressAttribute createXorMappedAddressAttribute(
TransportAddress address,
byte[] tranID)
{
XorMappedAddressAttribute attribute = new XorMappedAddressAttribute();
attribute.setAddress(address, tranID);
return attribute;
};
/* --------------------------------- USERNAME attribute ----------------------------- */
/**
* Create a UsernameAttribute.
@ -401,7 +436,7 @@ public class AttributeFactory
/* -------------------------------- RESERVATION-TOKEN attribute -------------------- */
/**
* Create a ReservationTokenAttribute.
* @param token the token
* @param token the token
* @return newly created RequestedTransportAttribute
*/
public static ReservationTokenAttribute createReservationTokenAttribute(byte token[])

View File

@ -143,4 +143,25 @@ public class XorMappedAddressAttribute
{
return applyXor(getAddress(), xorMask);
}
/**
* Applies a XOR mask to the specified address and then sets it as the value
* transported by this attribute.
*
* @param address the address that we should xor and then record in this
* attribute.
* @param transactionID the transaction identifier that we should use
* when creating the XOR mask.
*/
public void setAddress(TransportAddress address, byte[] transactionID)
{
byte[] xorMask = new byte[16];
System.arraycopy(Message.MAGIC_COOKIE, 0, xorMask, 0, 4);
System.arraycopy(transactionID, 0, xorMask, 4, 12);
TransportAddress xorAddress = applyXor(address, xorMask);
super.setAddress(xorAddress);
}
}

View File

@ -109,7 +109,7 @@ public class Agent
ufrag = new BigInteger(24, random).toString(32);
password = new BigInteger(128, random).toString(32);
tieBreaker = random.nextLong();
tieBreaker = Math.abs(random.nextLong());
}
/**
@ -233,6 +233,16 @@ public class Agent
public void startChecks()
{
initCheckLists();
List<IceMediaStream> streams = getStreams();
for(IceMediaStream stream : streams)
{
CheckList list = stream.getCheckList();
ConnectivityCheckDispatcher client = new ConnectivityCheckDispatcher(list);
client.startChecks();
}
}
/**

View File

@ -48,4 +48,28 @@ public class CheckList
{
this.state = state;
}
/**
* Returns a <tt>String</tt> representation of this check list. It
* consists of a list of the <tt>CandidatePair</tt>s in the order they
* were inserted and enclosed in square brackets (<tt>"[]"</tt>). The method
* would also call and use the content returned by every member
* <tt>CandidatePair</tt>.
*
* @return A <tt>String</tt> representation of this collection.
*/
public String toString()
{
StringBuffer buff = new StringBuffer("CheckList. (num pairs=");
buff.append(size() + ")\n");
Iterator<CandidatePair> pairs = iterator();
while(pairs.hasNext())
{
buff.append(pairs.next().toString()).append("\n");
}
return buff.toString();
}
}

View File

@ -1,96 +0,0 @@
/*
* 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 java.util.logging.*;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.socket.*;
import org.ice4j.stack.*;
/**
* @author Emil Ivov
*/
public class ConnectivityCheckClient
implements ResponseCollector
{
/**
* The <tt>Logger</tt> used by the <tt>ConnectivityCheckClient</tt>
* class and its instances for logging output.
*/
private static final Logger logger = Logger
.getLogger(ConnectivityCheckClient.class.getName());
/**
* The <tt>DatagramPacketFilter</tt> that only accepts STUN messages.
*/
private DatagramPacketFilter stunDatagramPacketFilter;
private final CheckList checkList;
public ConnectivityCheckClient(CheckList list)
{
this.checkList = list;
}
public void startChecks()
{
for(CandidatePair pair : checkList)
{
startCheckForPair(pair);
}
}
private void startCheckForPair(CandidatePair pair)
{
//we don't need to do a canReach() verification here as it has been
//already verified during the gathering process.
DatagramSocket stunSocket = ((HostCandidate)pair.getLocalCandidate())
.getStunSocket(pair.getRemoteCandidate().getTransportAddress());
StunStack.getInstance().addSocket(stunSocket);
Request request = MessageFactory.createBindingRequest();
TransactionID tran;
try
{
tran = StunStack.getInstance().sendRequest(
request, pair.getRemoteCandidate().getTransportAddress(),
stunSocket,
this);
}
catch (Exception exception)
{
logger.log(
Level.INFO,
"Failed to send " + request + " through "
+ stunSocket.getLocalSocketAddress(),
exception);
return;
}
}
public void processResponse(StunMessageEvent response)
{
System.out.println("stun response=" + response);
}
public void processTimeout(StunTimeoutEvent event)
{
System.out.println("timeout event=" + event);
}
public void processUnreachable(StunFailureEvent event)
{
System.out.println("failure event=" + event);
}
}

View File

@ -80,9 +80,13 @@ public class HostCandidate extends LocalCandidate
}
/**
* Returns the <tt>DatagramSocket</tt> that this candidate uses when sending
* and receiving STUN packets, while harvesting STUN candidates or
* performing connectivity checks.
* Creates if necessary and returns a <tt>DatagramSocket</tt> that would
* capture all STUN packets arriving on this candidate's socket. If the
* <tt>serverAddress</tt> parameter is not <tt>null</tt> this socket would
* only intercept packets originating at this address.
*
* @param serverAddress the address of the source we'd like to receive
* packets from or <tt>null</tt> if we'd like to intercept all stun packets.
*
* @return the <tt>DatagramSocket</tt> that this candidate uses when sending
* and receiving STUN packets, while harvesting STUN candidates or

View File

@ -453,7 +453,7 @@ public class IceMediaStream
* @return the list of <tt>CandidatePair</tt>s to be used in checks for
* this stream.
*/
public List<CandidatePair> getCheckList()
public CheckList getCheckList()
{
return checkList;
}

View File

@ -15,6 +15,7 @@ import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.ice.*;
import org.ice4j.socket.*;
import org.ice4j.stack.*;
/**
* A <tt>HostCandidateHarvester</tt> gathers host <tt>Candidate</tt>s for a
@ -107,6 +108,12 @@ public class HostCandidateHarvester
HostCandidate candidate = new HostCandidate(sock, component);
candidate.setVirtual(NetworkUtils.isInterfaceVirtual(iface));
component.addLocalCandidate(candidate);
//We are most certainly going to use all local host candidates
//for sending and receiving STUN connectivity checks. In case
//we have enabled STUN, we are going to use them as well while
//harvesting reflexive candidates.
createAndRegisterStunSocket(candidate);
}
}
@ -221,4 +228,20 @@ public class HostCandidateHarvester
throw new BindException("Could not bind to any port between "
+ minPort + " and " + (port -1));
}
/**
* Since we are most certainly going to use all local host candidates for
* sending and receiving STUN connectivity checks, and possibly for STUN
* harvesting too, we might as well create their STUN sockets here and
* register them with the StunStack. This allows us to avoid conflicts
* between the STUN harvester and the connectivity checks later on.
*
* @param candidate the candidate whose stun socket we'd like to initialize
* and register with the StunStack.
*/
private void createAndRegisterStunSocket(HostCandidate candidate)
{
DatagramSocket stunSocket = candidate.getStunSocket(null);
StunStack.getInstance().addSocket(stunSocket);
}
}

View File

@ -339,13 +339,12 @@ public class StunCandidateHarvester
*/
private void refreshCandidate(ServerReflexiveCandidate srflxCand)
{
DatagramSocket sock = srflxCand.getSocket();
stunStack.addSocket(sock);
try
{
stunStack.sendRequest( MessageFactory.createBindingRequest(),
stunServer, sock, this);
stunServer,
srflxCand.getBase().getTransportAddress(),
this);
}
catch (Exception exception)
@ -369,10 +368,6 @@ public class StunCandidateHarvester
if (!hostCand.getTransportAddress().canReach(stunServer))
return;
DatagramSocket socket = getStunSocket(hostCand);
stunStack.addSocket(socket);
synchronized(resolveMap)
{
Request request = createRequestToStartResolvingCandidate(hostCand);
@ -380,7 +375,8 @@ public class StunCandidateHarvester
try
{
tran = stunStack.sendRequest(request, stunServer, socket, this);
tran = stunStack.sendRequest(request, stunServer,
hostCand.getTransportAddress(), this);
}
catch (Exception exception)
{
@ -388,7 +384,7 @@ public class StunCandidateHarvester
Level.INFO,
"Failed to send "
+ request
+ " through " + socket.getLocalSocketAddress(),
+ " through " + hostCand.getTransportAddress(),
exception);
return;
}

View File

@ -9,14 +9,14 @@ package org.ice4j.message;
import org.ice4j.*;
/**
* An indication descendant of the message class.
*
* 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
* @author Sebastien Vincent
* @version 0.1
*/
public class Indication extends Message
@ -33,14 +33,14 @@ public class Indication extends Message
* 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
* @throws IllegalArgumentException if indicationType is not a valid
* response type
*/
public void setMessageType(char indicationType)
throws StunException
throws IllegalArgumentException
{
if(!isIndicationType(indicationType))
throw new StunException(StunException.ILLEGAL_ARGUMENT,
throw new IllegalArgumentException(
(int)(indicationType)
+ " - is not a valid response type.");

View File

@ -97,6 +97,15 @@ public abstract class Message
protected LinkedHashMap<Character, Attribute> attributes
= new LinkedHashMap<Character, Attribute>();
/**
* Attribute presentity is a thing of RFC 3489 and no longer exists in
* 5389. we are not using it any longer and if at some point we decide we
* need it in certain situations, then make extend use of the following
* field.
*/
private static boolean rfc3489CompatibilityMode = false;
/**
* Desribes which attributes are present in which messages. An
* M indicates that inclusion of the attribute in the message is
@ -258,17 +267,19 @@ public abstract class Message
/**
* 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
*
* @throws IllegalArgumentException if the message cannot contain
* such an attribute.
*/
public void addAttribute(Attribute attribute)
throws StunException
throws IllegalArgumentException
{
Character attributeType = new Character(attribute.getAttributeType());
if (getAttributePresentity(attributeType.charValue()) == N_A)
{
throw new StunException(StunException.ILLEGAL_ARGUMENT,
throw new IllegalArgumentException(
"The attribute "
+ attribute.getName()
+ " is not allowed in a "
@ -328,12 +339,8 @@ public abstract class Message
* 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;
}
@ -607,6 +614,10 @@ public abstract class Message
protected void validateAttributePresentity()
throws IllegalStateException
{
//the
if(! rfc3489CompatibilityMode )
return;
for(char i = Attribute.MAPPED_ADDRESS; i < Attribute.REFLECTED_FROM; i++)
if(getAttributePresentity(i) == M && getAttribute(i) == null)
throw new IllegalStateException(

View File

@ -12,21 +12,22 @@ import org.ice4j.*;
import org.ice4j.attribute.*;
/**
* This class provides factory methods to allow an application to create
* STUN Messages from a particular implementation.
* This class provides factory methods to allow an application to create STUN
* Messages from a particular implementation.
*
* @author Emil Ivov
* @author Sebastien Vincent
*/
public class MessageFactory
{
private static final Logger logger =
Logger.getLogger(MessageFactory.class.getName());
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.
* 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()
@ -35,49 +36,41 @@ public class MessageFactory
try
{
bindingRequest.setMessageType(Message.BINDING_REQUEST);
}
catch (StunException ex)
} catch (IllegalArgumentException ex)
{
//there should be no exc here since we're the creators.
// 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!");
}
*/
* //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
* attribute with zero change ip and change port flags. It also contains the
* PRIORITY attribute used for ICE processing
*
* @param priority the value for the priority attribute
* @return a BindingRequest header with ICE PRIORITY attribute
* @throws StunException if we have a problem creating the request
*/
public static Request createBindingRequest(long priority)
throws StunException
throws StunException
{
Request bindingRequest = createBindingRequest();
PriorityAttribute attribute
= AttributeFactory.createPriorityAttribute(priority);
PriorityAttribute attribute = AttributeFactory
.createPriorityAttribute(priority);
bindingRequest.addAttribute(attribute);
return bindingRequest;
@ -85,9 +78,9 @@ public class MessageFactory
/**
* 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
* 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 the value of the ICE priority attributes
* @param controlling the value of the controlling attribute
@ -96,27 +89,25 @@ public class MessageFactory
* ICE-CONTROLLING / ICE-CONTROLLED)
* @throws StunException if we have a problem creating the request
*/
public static Request createBindingRequest(long priority,
boolean controlling,
long tieBreaker)
throws StunException
public static Request createBindingRequest(long priority,
boolean controlling, long tieBreaker)
throws StunException
{
Request bindingRequest = createBindingRequest();
PriorityAttribute attribute
= AttributeFactory.createPriorityAttribute(priority);
PriorityAttribute attribute = AttributeFactory
.createPriorityAttribute(priority);
bindingRequest.addAttribute(attribute);
if(controlling)
if (controlling)
{
IceControllingAttribute iceControllingAttribute
= AttributeFactory.createIceControllingAttribute(tieBreaker);
IceControllingAttribute iceControllingAttribute = AttributeFactory
.createIceControllingAttribute(tieBreaker);
bindingRequest.addAttribute(iceControllingAttribute);
}
else
} else
{
IceControlledAttribute iceControlledAttribute
= AttributeFactory.createIceControlledAttribute(tieBreaker);
IceControlledAttribute iceControlledAttribute = AttributeFactory
.createIceControlledAttribute(tieBreaker);
bindingRequest.addAttribute(iceControlledAttribute);
}
@ -124,48 +115,86 @@ public class MessageFactory
}
/**
* Creates a BindingResponse assigning the specified values to mandatory
* headers.
* Creates a BindingResponse in a 3489 compliant manner, 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
* @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
* headers.
* @throws IllegalArgumentException if there was something wrong with the
* way we are trying to create the response.
*/
public static Response createBindingResponse(
TransportAddress mappedAddress,
TransportAddress sourceAddress,
TransportAddress changedAddress)
throws StunException
public static Response create3482BindingResponse(
TransportAddress mappedAddress,
TransportAddress sourceAddress,
TransportAddress changedAddress)
throws IllegalArgumentException
{
Response bindingResponse = new Response();
bindingResponse.setMessageType(Message.BINDING_RESPONSE);
//mapped address
MappedAddressAttribute mappedAddressAttribute =
AttributeFactory.createMappedAddressAttribute(mappedAddress);
// mapped address
MappedAddressAttribute mappedAddressAttribute = AttributeFactory
.createMappedAddressAttribute(mappedAddress);
//source address
SourceAddressAttribute sourceAddressAttribute =
AttributeFactory.createSourceAddressAttribute(sourceAddress);
// the changed address and source address attribute were removed in
// RFC 5389 so we should be prepared to go without them.
//changed address
ChangedAddressAttribute changedAddressAttribute =
AttributeFactory.createChangedAddressAttribute(changedAddress);
// source address
SourceAddressAttribute sourceAddressAttribute = null;
try
{
bindingResponse.addAttribute(mappedAddressAttribute);
if (sourceAddress != null)
sourceAddressAttribute = AttributeFactory
.createSourceAddressAttribute(sourceAddress);
// changed address
ChangedAddressAttribute changedAddressAttribute = null;
if (changedAddress != null)
changedAddressAttribute = AttributeFactory
.createChangedAddressAttribute(changedAddress);
bindingResponse.addAttribute(mappedAddressAttribute);
// the changed address and source address attribute were removed in
// RFC 5389 so we should be prepared to go without them.
if (sourceAddressAttribute != null)
bindingResponse.addAttribute(sourceAddressAttribute);
if (changedAddressAttribute != null)
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 BindingResponse in a 5389 compliant manner containing a single
* <tt>XOR-MAPPED-ADDRESS</tt> attribute
*
* @param request the request that created the transaction that this
* response will belong to.
* @param mappedAddress the address to assign the mappedAddressAttribute
* @return a BindingResponse assigning the specified values to mandatory
* headers.
* @throws IllegalArgumentException if there was something wrong with the
* way we are trying to create the response.
*/
public static Response createBindingResponse(Request request,
TransportAddress mappedAddress)
throws IllegalArgumentException
{
Response bindingResponse = new Response();
bindingResponse.setMessageType(Message.BINDING_RESPONSE);
// xor mapped address
XorMappedAddressAttribute xorMappedAddressAttribute = AttributeFactory
.createXorMappedAddressAttribute(mappedAddress,
request.getTransactionID());
bindingResponse.addAttribute(xorMappedAddressAttribute);
return bindingResponse;
}
@ -185,74 +214,75 @@ public class MessageFactory
* UNKNOWN-ATTRIBUTES header
*/
private static Response createBindingErrorResponse(char errorCode,
String reasonPhrase,
char[] unknownAttributes)
throws StunException
String reasonPhrase, char[] unknownAttributes)
throws StunException
{
Response bindingErrorResponse = new Response();
bindingErrorResponse.setMessageType(Message.BINDING_ERROR_RESPONSE);
bindingErrorResponse
.setMessageType(Message.BINDING_ERROR_RESPONSE);
//init attributes
// init attributes
UnknownAttributesAttribute unknownAttributesAttribute = null;
ErrorCodeAttribute errorCodeAttribute =
AttributeFactory.createErrorCodeAttribute(errorCode,reasonPhrase);
ErrorCodeAttribute errorCodeAttribute = AttributeFactory
.createErrorCodeAttribute(errorCode,
reasonPhrase);
bindingErrorResponse.addAttribute(errorCodeAttribute);
if(unknownAttributes != null)
if (unknownAttributes != null)
{
unknownAttributesAttribute = AttributeFactory.
createUnknownAttributesAttribute();
unknownAttributesAttribute = AttributeFactory
.createUnknownAttributesAttribute();
for (int i = 0; i < unknownAttributes.length; i++)
{
unknownAttributesAttribute.addAttributeID(unknownAttributes[i]);
unknownAttributesAttribute
.addAttributeID(unknownAttributes[i]);
}
bindingErrorResponse.addAttribute(unknownAttributesAttribute);
bindingErrorResponse
.addAttribute(unknownAttributesAttribute);
}
return bindingErrorResponse;
}
/**
* Creates a binding error response with UNKNOWN_ATTRIBUTES error code
* and the specified unknown attributes.
* 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.
* 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
char[] unknownAttributes) throws StunException
{
return createBindingErrorResponse(ErrorCodeAttribute.UNKNOWN_ATTRIBUTE,
null,
unknownAttributes);
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.
* 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.
* 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
String reasonPhrase, char[] unknownAttributes)
throws StunException
{
return createBindingErrorResponse(ErrorCodeAttribute.UNKNOWN_ATTRIBUTE,
reasonPhrase,
unknownAttributes);
return createBindingErrorResponse(
ErrorCodeAttribute.UNKNOWN_ATTRIBUTE,
reasonPhrase, unknownAttributes);
}
/**
@ -267,25 +297,24 @@ public class MessageFactory
* UNKNOWN-ATTRIBUTES header
*/
public static Response createBindingErrorResponse(char errorCode,
String reasonPhrase)
throws StunException
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
* 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);
}
@ -302,59 +331,59 @@ public class MessageFactory
try
{
allocateRequest.setMessageType(Message.ALLOCATE_REQUEST);
}
catch (StunException ex)
} catch (IllegalArgumentException ex)
{
//there should be no exc here since we're the creators.
// 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.
* 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)
public static Request createAllocateRequest(byte protocol,
boolean rFlag)
{
Request allocateRequest = new Request();
Request allocateRequest = new Request();
try
{
allocateRequest.setMessageType(Message.ALLOCATE_REQUEST);
/* XXX add enum somewhere for transport number */
if(protocol != 6 && protocol != 17)
try
{
throw new StunException("Protocol not valid!");
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);
}
/* 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;
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
@ -363,137 +392,142 @@ public class MessageFactory
* @throws StunException in case we have a problem creating the username
* realm or nonce attributes.
*/
public static void addLongTermAuthentifcationAttribute(Request request,
byte username[],
byte realm[],
byte nonce[])
throws StunException
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);
UsernameAttribute usernameAttr = AttributeFactory
.createUsernameAttribute(username);
RealmAttribute realmAttr = AttributeFactory
.createRealmAttribute(realm);
NonceAttribute nonceAttr = AttributeFactory
.createNonceAttribute(nonce);
request.addAttribute(usernameAttr);
request.addAttribute(realmAttr);
request.addAttribute(nonceAttr);
request.addAttribute(usernameAttr);
request.addAttribute(realmAttr);
request.addAttribute(nonceAttr);
/* TODO calculate MESSAGE-INTEGRITY and FINGERPRINT */
/* TODO calculate MESSAGE-INTEGRITY and FINGERPRINT */
}
/**
* Create a refresh request.
*
* @param lifetime lifetime value
* @return refresh request
*/
public static Request createRefreshRequest(int lifetime)
{
Request refreshRequest = new Request();
Request refreshRequest = new Request();
try
{
refreshRequest.setMessageType(Message.REFRESH_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);
}
/* add a LIFETIME attribute */
LifetimeAttribute lifetimeReq = AttributeFactory
.createLifetimeAttribute(lifetime);
refreshRequest.addAttribute(lifetimeReq);
} catch (IllegalArgumentException ex)
{
logger.log(Level.FINE, "Failed to set message type.", ex);
}
return refreshRequest;
return refreshRequest;
}
/**
* Create a ChannelBind request.
*
* @param channelNumber the channel number
* @param peerAddress the peer address
* @param tranID the ID of the transaction that we should be using
*
* @return channel bind request
*/
public static Request createChannelBindRequest(
char channelNumber,
TransportAddress peerAddress)
public static Request createChannelBindRequest(char channelNumber,
TransportAddress peerAddress, byte[] tranID)
{
Request channelBindRequest = new Request();
Request channelBindRequest = new Request();
try
{
channelBindRequest.setMessageType(Message.CHANNELBIND_REQUEST);
try
{
channelBindRequest
.setMessageType(Message.CHANNELBIND_REQUEST);
/* add a CHANNEL-NUMBER attribute */
ChannelNumberAttribute channelNumberAttribute
= AttributeFactory.createChannelNumberAttribute(channelNumber);
channelBindRequest.addAttribute(channelNumberAttribute);
// 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);
}
// add a XOR-PEER-ADDRESS
XorPeerAddressAttribute peerAddressAttribute = AttributeFactory
.createXorPeerAddressAttribute(peerAddress,
tranID);
return channelBindRequest;
channelBindRequest.addAttribute(peerAddressAttribute);
} catch (IllegalArgumentException 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)
* @param tranID the ID of the transaction that we should be using
*
* @return send indication message
*/
public static Indication createSendIndication(TransportAddress peerAddress,
byte data[])
public static Indication createSendIndication(
TransportAddress peerAddress, byte[] data, byte[] tranID)
{
Indication sendIndication = new Indication();
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)
try
{
DataAttribute dataAttribute = AttributeFactory.createDataAttribute(data);
sendIndication.addAttribute(dataAttribute);
}
}
catch(StunException ex)
{
logger.log(Level.FINE, "Failed to set message type.", ex);
}
sendIndication.setMessageType(Message.SEND_INDICATION);
return sendIndication;
/* add XOR-PEER-ADDRESS attribute */
XorPeerAddressAttribute peerAddressAttribute = AttributeFactory
.createXorPeerAddressAttribute(peerAddress, tranID);
sendIndication.addAttribute(peerAddressAttribute);
/* add DATA if data */
if (data != null && data.length > 0)
{
DataAttribute dataAttribute = AttributeFactory
.createDataAttribute(data);
sendIndication.addAttribute(dataAttribute);
}
} catch (IllegalArgumentException ex)
{
logger.log(Level.FINE, "Failed to set message type.", ex);
}
return sendIndication;
}
//======================== NOT CURRENTLY SUPPORTED =============================
// ======================== NOT CURRENTLY SUPPORTED
public static Request createShareSecretRequest()
{
throw new UnsupportedOperationException(
"Shared Secret Support is not currently implemented");
"Shared Secret Support is not currently implemented");
}
public static Response createSharedSecretResponse()
{
throw new UnsupportedOperationException(
"Shared Secret Support is not currently implemented");
"Shared Secret Support is not currently implemented");
}
public static Response createSharedSecretErrorResponse()
{
throw new UnsupportedOperationException(
"Shared Secret Support is not currently implemented");
"Shared Secret Support is not currently implemented");
}
}

View File

@ -34,14 +34,14 @@ public class Request extends Message
* 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
* @throws IllegalArgumentException if requestType is not a valid
* request type
*/
public void setMessageType(char requestType)
throws StunException
throws IllegalArgumentException
{
if(!isRequestType(requestType))
throw new StunException(StunException.ILLEGAL_ARGUMENT,
throw new IllegalArgumentException(
(int)(requestType)
+ " - is not a valid request type.");

View File

@ -29,14 +29,14 @@ public class Response extends Message
* 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
* @throws IllegalArgumentException if responseType is not a valid
* response type
*/
public void setMessageType(char responseType)
throws StunException
throws IllegalArgumentException
{
if(!isResponseType(responseType))
throw new StunException(StunException.ILLEGAL_ARGUMENT,
throw new IllegalArgumentException(
(int)(responseType)
+ " - is not a valid response type.");

View File

@ -372,7 +372,9 @@ public class MultiplexingDatagramSocket
{
socket.received.add(clone(p));
accepted = true;
break;
//emil: don't break, we want all
//filtering sockets to get this
//break;
}
if (!accepted)

View File

@ -34,21 +34,33 @@ public class StunDatagramPacketFilter
/**
* Initializes a new <tt>StunDatagramPacketFilter</tt> which will accept
* <tt>DatagramPacket</tt>s which represent STUN messages and which are part
* of the communication with a specific STUN server.
* of the communication with a specific STUN server (or any server if
* <tt>stunServer</tt> is <tt>null</tt>).
*
* @param turnServer the <tt>TransportAddress</tt> of the STUN server
* @param stunServer the <tt>TransportAddress</tt> of the STUN server
* <tt>DatagramPacket</tt>s representing STUN messages from and to which
* will be accepted by the new instance
* will be accepted by the new instance or <tt>null</tt> if we would like
* to accept stun messages from any destination.
*/
public StunDatagramPacketFilter(TransportAddress stunServer)
{
this.stunServer = stunServer;
}
/**
* Initializes a new <tt>StunDatagramPacketFilter</tt> which will accept
* <tt>DatagramPacket</tt>s which represent STUN messages received from
* any destination.
*/
public StunDatagramPacketFilter()
{
this(null);
}
/**
* Determines whether a specific <tt>DatagramPacket</tt> represents a STUN
* message which is part of the communication with the STUN server
* associated with this instance.
* message and whether it is part of the communication with the STUN server
* if one was associated with this instance.
*
* @param p the <tt>DatagramPacket</tt> which is to be checked whether it is
* a STUN message which is part of the communicator with the STUN server
@ -59,31 +71,36 @@ public class StunDatagramPacketFilter
*/
public boolean accept(DatagramPacket p)
{
if (stunServer.equals(p.getSocketAddress()))
//if we were instantiated for a specific stun server, and the packet
//did not originate there, we reject it.
if (stunServer != null
&& !stunServer.equals(p.getSocketAddress()))
{
return false;
}
/*
* All STUN messages MUST start with a 20-byte header followed by
* zero or more Attributes.
*/
if (p.getLength() >= 20)
{
/*
* All STUN messages MUST start with a 20-byte header followed by
* zero or more Attributes.
* The most significant 2 bits of every STUN message MUST be
* zeroes. This can be used to differentiate STUN packets from
* other protocols when STUN is multiplexed with other protocols
* on the same port.
*/
if (p.getLength() >= 20)
byte[] data = p.getData();
int offset = p.getOffset();
byte b0 = data[offset];
if ((b0 & 0xC0) == 0)
{
/*
* The most significant 2 bits of every STUN message MUST be
* zeroes. This can be used to differentiate STUN packets from
* other protocols when STUN is multiplexed with other protocols
* on the same port.
*/
byte[] data = p.getData();
int offset = p.getOffset();
byte b0 = data[offset];
if ((b0 & 0xC0) == 0)
{
byte b1 = data[offset + 1];
char method = (char) ((b0 & 0xFE) | (b1 & 0xEF));
return acceptMethod(method);
}
byte b1 = data[offset + 1];
char method = (char) ((b0 & 0xFE) | (b1 & 0xEF));
return acceptMethod(method);
}
}
return false;