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

@ -257,15 +257,22 @@ public class AttributeFactory
/* ------------------------------------ XOR-RELAYED-ADRESS attribute ------------------------ */ /* ------------------------------------ XOR-RELAYED-ADRESS attribute ------------------------ */
/** /**
* Creates a XorRelayedAddressAttribute of the specified type and with * 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 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. * @return the newly created address attribute.
*/ */
public static XorRelayedAddressAttribute createXorRelayedAddressAttribute(TransportAddress address) public static XorRelayedAddressAttribute createXorRelayedAddressAttribute(
TransportAddress address,
byte[] tranID)
{ {
XorRelayedAddressAttribute attribute = new XorRelayedAddressAttribute(); 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; return attribute;
} }
@ -273,17 +280,45 @@ public class AttributeFactory
/** /**
* Creates a XorPeerAddressAttribute of the specified type and with * Creates a XorPeerAddressAttribute 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 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. * @return the newly created address attribute.
*/ */
public static XorPeerAddressAttribute createXorPeerAddressAttribute(TransportAddress address) public static XorPeerAddressAttribute createXorPeerAddressAttribute(
TransportAddress address,
byte[] tranID)
{ {
XorPeerAddressAttribute attribute = new XorPeerAddressAttribute(); 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; 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 ----------------------------- */ /* --------------------------------- USERNAME attribute ----------------------------- */
/** /**
* Create a UsernameAttribute. * Create a UsernameAttribute.

View File

@ -143,4 +143,25 @@ public class XorMappedAddressAttribute
{ {
return applyXor(getAddress(), xorMask); 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); ufrag = new BigInteger(24, random).toString(32);
password = new BigInteger(128, 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() public void startChecks()
{ {
initCheckLists(); 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; 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 * Creates if necessary and returns a <tt>DatagramSocket</tt> that would
* and receiving STUN packets, while harvesting STUN candidates or * capture all STUN packets arriving on this candidate's socket. If the
* performing connectivity checks. * <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 * @return the <tt>DatagramSocket</tt> that this candidate uses when sending
* and receiving STUN packets, while harvesting STUN candidates or * 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 * @return the list of <tt>CandidatePair</tt>s to be used in checks for
* this stream. * this stream.
*/ */
public List<CandidatePair> getCheckList() public CheckList getCheckList()
{ {
return checkList; return checkList;
} }

View File

@ -15,6 +15,7 @@ import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.ice.*; import org.ice4j.ice.*;
import org.ice4j.socket.*; import org.ice4j.socket.*;
import org.ice4j.stack.*;
/** /**
* A <tt>HostCandidateHarvester</tt> gathers host <tt>Candidate</tt>s for a * 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); HostCandidate candidate = new HostCandidate(sock, component);
candidate.setVirtual(NetworkUtils.isInterfaceVirtual(iface)); candidate.setVirtual(NetworkUtils.isInterfaceVirtual(iface));
component.addLocalCandidate(candidate); 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 " throw new BindException("Could not bind to any port between "
+ minPort + " and " + (port -1)); + 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) private void refreshCandidate(ServerReflexiveCandidate srflxCand)
{ {
DatagramSocket sock = srflxCand.getSocket();
stunStack.addSocket(sock);
try try
{ {
stunStack.sendRequest( MessageFactory.createBindingRequest(), stunStack.sendRequest( MessageFactory.createBindingRequest(),
stunServer, sock, this); stunServer,
srflxCand.getBase().getTransportAddress(),
this);
} }
catch (Exception exception) catch (Exception exception)
@ -369,10 +368,6 @@ public class StunCandidateHarvester
if (!hostCand.getTransportAddress().canReach(stunServer)) if (!hostCand.getTransportAddress().canReach(stunServer))
return; return;
DatagramSocket socket = getStunSocket(hostCand);
stunStack.addSocket(socket);
synchronized(resolveMap) synchronized(resolveMap)
{ {
Request request = createRequestToStartResolvingCandidate(hostCand); Request request = createRequestToStartResolvingCandidate(hostCand);
@ -380,7 +375,8 @@ public class StunCandidateHarvester
try try
{ {
tran = stunStack.sendRequest(request, stunServer, socket, this); tran = stunStack.sendRequest(request, stunServer,
hostCand.getTransportAddress(), this);
} }
catch (Exception exception) catch (Exception exception)
{ {
@ -388,7 +384,7 @@ public class StunCandidateHarvester
Level.INFO, Level.INFO,
"Failed to send " "Failed to send "
+ request + request
+ " through " + socket.getLocalSocketAddress(), + " through " + hostCand.getTransportAddress(),
exception); exception);
return; return;
} }

View File

@ -33,14 +33,14 @@ public class Indication extends Message
* Checks whether indicationType is a valid response type and if yes sets it * Checks whether indicationType is a valid response type and if yes sets it
* as the type of the current instance. * as the type of the current instance.
* @param indicationType the type to set * @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 * response type
*/ */
public void setMessageType(char indicationType) public void setMessageType(char indicationType)
throws StunException throws IllegalArgumentException
{ {
if(!isIndicationType(indicationType)) if(!isIndicationType(indicationType))
throw new StunException(StunException.ILLEGAL_ARGUMENT, throw new IllegalArgumentException(
(int)(indicationType) (int)(indicationType)
+ " - is not a valid response type."); + " - is not a valid response type.");

View File

@ -97,6 +97,15 @@ public abstract class Message
protected LinkedHashMap<Character, Attribute> attributes protected LinkedHashMap<Character, Attribute> attributes
= new LinkedHashMap<Character, Attribute>(); = 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 * Desribes which attributes are present in which messages. An
* M indicates that inclusion of the attribute in the message is * 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 * Adds the specified attribute to this message. If an attribute with that
* name was already added, it would be replaced. * name was already added, it would be replaced.
*
* @param attribute the attribute to add to this message. * @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. * such an attribute.
*/ */
public void addAttribute(Attribute attribute) public void addAttribute(Attribute attribute)
throws StunException throws IllegalArgumentException
{ {
Character attributeType = new Character(attribute.getAttributeType()); Character attributeType = new Character(attribute.getAttributeType());
if (getAttributePresentity(attributeType.charValue()) == N_A) if (getAttributePresentity(attributeType.charValue()) == N_A)
{ {
throw new StunException(StunException.ILLEGAL_ARGUMENT, throw new IllegalArgumentException(
"The attribute " "The attribute "
+ attribute.getName() + attribute.getName()
+ " is not allowed in a " + " is not allowed in a "
@ -328,12 +339,8 @@ public abstract class Message
* initialized (could provoke attribute discrepancies). Called by * initialized (could provoke attribute discrepancies). Called by
* messageFactory. * messageFactory.
* @param messageType the message type. * @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) protected void setMessageType(char messageType)
throws StunException
{ {
this.messageType = messageType; this.messageType = messageType;
} }
@ -607,6 +614,10 @@ public abstract class Message
protected void validateAttributePresentity() protected void validateAttributePresentity()
throws IllegalStateException throws IllegalStateException
{ {
//the
if(! rfc3489CompatibilityMode )
return;
for(char i = Attribute.MAPPED_ADDRESS; i < Attribute.REFLECTED_FROM; i++) for(char i = Attribute.MAPPED_ADDRESS; i < Attribute.REFLECTED_FROM; i++)
if(getAttributePresentity(i) == M && getAttribute(i) == null) if(getAttributePresentity(i) == M && getAttribute(i) == null)
throw new IllegalStateException( throw new IllegalStateException(

View File

@ -12,21 +12,22 @@ import org.ice4j.*;
import org.ice4j.attribute.*; import org.ice4j.attribute.*;
/** /**
* This class provides factory methods to allow an application to create * This class provides factory methods to allow an application to create STUN
* STUN Messages from a particular implementation. * Messages from a particular implementation.
* *
* @author Emil Ivov * @author Emil Ivov
* @author Sebastien Vincent * @author Sebastien Vincent
*/ */
public class MessageFactory public class MessageFactory
{ {
private static final Logger logger = private static final Logger logger = Logger
Logger.getLogger(MessageFactory.class.getName()); .getLogger(MessageFactory.class
.getName());
/** /**
* Creates a default binding request. * Creates a default binding request. The request DOES NOT contains a
* The request DOES NOT contains a ChangeRequest attribute * ChangeRequest attribute with zero change ip and change port flags.
* with zero change ip and change port flags. *
* @return a default binding request. * @return a default binding request.
*/ */
public static Request createBindingRequest() public static Request createBindingRequest()
@ -35,49 +36,41 @@ public class MessageFactory
try try
{ {
bindingRequest.setMessageType(Message.BINDING_REQUEST); bindingRequest.setMessageType(Message.BINDING_REQUEST);
} } catch (IllegalArgumentException ex)
catch (StunException 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); logger.log(Level.FINE, "Failed to set message type.", ex);
} }
/* do not add this by default */ /* do not add this by default */
/* /*
//add a change request attribute * //add a change request attribute ChangeRequestAttribute attribute =
ChangeRequestAttribute attribute * AttributeFactory.createChangeRequestAttribute();
= AttributeFactory.createChangeRequestAttribute(); *
* try { bindingRequest.addAttribute(attribute); } catch (StunException
try * ex) { //shouldn't happen throw new
{ * RuntimeException("Failed to add a change request "
bindingRequest.addAttribute(attribute); * +"attribute to a binding request!"); }
} */
catch (StunException ex)
{
//shouldn't happen
throw new RuntimeException("Failed to add a change request "
+"attribute to a binding request!");
}
*/
return bindingRequest; return bindingRequest;
} }
/** /**
* Creates a default binding request. The request contains a ChangeReqeust * Creates a default binding request. The request contains a ChangeReqeust
* attribute with zero change ip and change port flags. * attribute with zero change ip and change port flags. It also contains the
* It also contains the PRIORITY attribute used for ICE processing * PRIORITY attribute used for ICE processing
* *
* @param priority the value for the priority attribute * @param priority the value for the priority attribute
* @return a BindingRequest header with ICE PRIORITY attribute * @return a BindingRequest header with ICE PRIORITY attribute
* @throws StunException if we have a problem creating the request * @throws StunException if we have a problem creating the request
*/ */
public static Request createBindingRequest(long priority) public static Request createBindingRequest(long priority)
throws StunException throws StunException
{ {
Request bindingRequest = createBindingRequest(); Request bindingRequest = createBindingRequest();
PriorityAttribute attribute PriorityAttribute attribute = AttributeFactory
= AttributeFactory.createPriorityAttribute(priority); .createPriorityAttribute(priority);
bindingRequest.addAttribute(attribute); bindingRequest.addAttribute(attribute);
return bindingRequest; return bindingRequest;
@ -85,9 +78,9 @@ public class MessageFactory
/** /**
* Creates a default binding request. The request contains a ChangeReqeust * Creates a default binding request. The request contains a ChangeReqeust
* attribute with zero change ip and change port flags. * attribute with zero change ip and change port flags. It contains the
* It contains the PRIORITY, ICE-CONTROLLED or ICE-CONTROLLING attributes * PRIORITY, ICE-CONTROLLED or ICE-CONTROLLING attributes used for ICE
* used for ICE processing * processing
* *
* @param priority the value of the ICE priority attributes * @param priority the value of the ICE priority attributes
* @param controlling the value of the controlling attribute * @param controlling the value of the controlling attribute
@ -96,27 +89,25 @@ public class MessageFactory
* ICE-CONTROLLING / ICE-CONTROLLED) * ICE-CONTROLLING / ICE-CONTROLLED)
* @throws StunException if we have a problem creating the request * @throws StunException if we have a problem creating the request
*/ */
public static Request createBindingRequest(long priority, public static Request createBindingRequest(long priority,
boolean controlling, boolean controlling, long tieBreaker)
long tieBreaker) throws StunException
throws StunException
{ {
Request bindingRequest = createBindingRequest(); Request bindingRequest = createBindingRequest();
PriorityAttribute attribute PriorityAttribute attribute = AttributeFactory
= AttributeFactory.createPriorityAttribute(priority); .createPriorityAttribute(priority);
bindingRequest.addAttribute(attribute); bindingRequest.addAttribute(attribute);
if(controlling) if (controlling)
{ {
IceControllingAttribute iceControllingAttribute IceControllingAttribute iceControllingAttribute = AttributeFactory
= AttributeFactory.createIceControllingAttribute(tieBreaker); .createIceControllingAttribute(tieBreaker);
bindingRequest.addAttribute(iceControllingAttribute); bindingRequest.addAttribute(iceControllingAttribute);
} } else
else
{ {
IceControlledAttribute iceControlledAttribute IceControlledAttribute iceControlledAttribute = AttributeFactory
= AttributeFactory.createIceControlledAttribute(tieBreaker); .createIceControlledAttribute(tieBreaker);
bindingRequest.addAttribute(iceControlledAttribute); bindingRequest.addAttribute(iceControlledAttribute);
} }
@ -124,48 +115,86 @@ public class MessageFactory
} }
/** /**
* Creates a BindingResponse assigning the specified values to mandatory * Creates a BindingResponse in a 3489 compliant manner, assigning the
* headers. * specified values to mandatory headers.
* *
* @param mappedAddress the address to assign the mappedAddressAttribute * @param mappedAddress the address to assign the mappedAddressAttribute
* @param sourceAddress the address to assign the sourceAddressAttribute * @param sourceAddress the address to assign the sourceAddressAttribute
* @param changedAddress the address to assign the changedAddressAttribute * @param changedAddress the address to assign the changedAddressAttribute
* @return a BindingResponse assigning the specified values to mandatory * @return a BindingResponse assigning the specified values to mandatory
* headers. * headers.
* @throws StunException ILLEGAL_ARGUMENT * @throws IllegalArgumentException if there was something wrong with the
* way we are trying to create the response.
*/ */
public static Response createBindingResponse( public static Response create3482BindingResponse(
TransportAddress mappedAddress, TransportAddress mappedAddress,
TransportAddress sourceAddress, TransportAddress sourceAddress,
TransportAddress changedAddress) TransportAddress changedAddress)
throws StunException throws IllegalArgumentException
{ {
Response bindingResponse = new Response(); Response bindingResponse = new Response();
bindingResponse.setMessageType(Message.BINDING_RESPONSE); bindingResponse.setMessageType(Message.BINDING_RESPONSE);
//mapped address // mapped address
MappedAddressAttribute mappedAddressAttribute = MappedAddressAttribute mappedAddressAttribute = AttributeFactory
AttributeFactory.createMappedAddressAttribute(mappedAddress); .createMappedAddressAttribute(mappedAddress);
//source address // the changed address and source address attribute were removed in
SourceAddressAttribute sourceAddressAttribute = // RFC 5389 so we should be prepared to go without them.
AttributeFactory.createSourceAddressAttribute(sourceAddress);
//changed address // source address
ChangedAddressAttribute changedAddressAttribute = SourceAddressAttribute sourceAddressAttribute = null;
AttributeFactory.createChangedAddressAttribute(changedAddress);
try if (sourceAddress != null)
{ sourceAddressAttribute = AttributeFactory
bindingResponse.addAttribute(mappedAddressAttribute); .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); bindingResponse.addAttribute(sourceAddressAttribute);
if (changedAddressAttribute != null)
bindingResponse.addAttribute(changedAddressAttribute); bindingResponse.addAttribute(changedAddressAttribute);
}
catch (StunException ex) return bindingResponse;
{ }
throw new StunException(StunException.INTERNAL_ERROR,
"Failed to add a mandatory attribute to the binding response."); /**
} * 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; return bindingResponse;
} }
@ -185,74 +214,75 @@ public class MessageFactory
* UNKNOWN-ATTRIBUTES header * UNKNOWN-ATTRIBUTES header
*/ */
private static Response createBindingErrorResponse(char errorCode, private static Response createBindingErrorResponse(char errorCode,
String reasonPhrase, String reasonPhrase, char[] unknownAttributes)
char[] unknownAttributes) throws StunException
throws StunException
{ {
Response bindingErrorResponse = new Response(); Response bindingErrorResponse = new Response();
bindingErrorResponse.setMessageType(Message.BINDING_ERROR_RESPONSE); bindingErrorResponse
.setMessageType(Message.BINDING_ERROR_RESPONSE);
//init attributes // init attributes
UnknownAttributesAttribute unknownAttributesAttribute = null; UnknownAttributesAttribute unknownAttributesAttribute = null;
ErrorCodeAttribute errorCodeAttribute = ErrorCodeAttribute errorCodeAttribute = AttributeFactory
AttributeFactory.createErrorCodeAttribute(errorCode,reasonPhrase); .createErrorCodeAttribute(errorCode,
reasonPhrase);
bindingErrorResponse.addAttribute(errorCodeAttribute); bindingErrorResponse.addAttribute(errorCodeAttribute);
if(unknownAttributes != null) if (unknownAttributes != null)
{ {
unknownAttributesAttribute = AttributeFactory. unknownAttributesAttribute = AttributeFactory
createUnknownAttributesAttribute(); .createUnknownAttributesAttribute();
for (int i = 0; i < unknownAttributes.length; i++) for (int i = 0; i < unknownAttributes.length; i++)
{ {
unknownAttributesAttribute.addAttributeID(unknownAttributes[i]); unknownAttributesAttribute
.addAttributeID(unknownAttributes[i]);
} }
bindingErrorResponse.addAttribute(unknownAttributesAttribute); bindingErrorResponse
.addAttribute(unknownAttributesAttribute);
} }
return bindingErrorResponse; return bindingErrorResponse;
} }
/** /**
* Creates a binding error response with UNKNOWN_ATTRIBUTES error code * Creates a binding error response with UNKNOWN_ATTRIBUTES error code and
* and the specified unknown attributes. * the specified unknown attributes.
* *
* @param unknownAttributes a char[] array containing the ids of one or more * @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 * @throws StunException INVALID_ARGUMENTS if one or more of the given
* parameters had an invalid value. * parameters had an invalid value.
* @return a binding error response message containing an error code and a * @return a binding error response message containing an error code and a
* UNKNOWN-ATTRIBUTES header * UNKNOWN-ATTRIBUTES header
*/ */
public static Response createBindingErrorResponseUnknownAttributes( public static Response createBindingErrorResponseUnknownAttributes(
char[] unknownAttributes) char[] unknownAttributes) throws StunException
throws StunException
{ {
return createBindingErrorResponse(ErrorCodeAttribute.UNKNOWN_ATTRIBUTE, return createBindingErrorResponse(
null, ErrorCodeAttribute.UNKNOWN_ATTRIBUTE, null,
unknownAttributes); unknownAttributes);
} }
/** /**
* Creates a binding error response with UNKNOWN_ATTRIBUTES error code * Creates a binding error response with UNKNOWN_ATTRIBUTES error code and
* and the specified unknown attributes and reason phrase. * the specified unknown attributes and reason phrase.
* *
* @param reasonPhrase a short description of the error. * @param reasonPhrase a short description of the error.
* @param unknownAttributes a char[] array containing the ids of one or more * @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 * @throws StunException INVALID_ARGUMENTS if one or more of the given
* parameters had an invalid value. * parameters had an invalid value.
* @return a binding error response message containing an error code and a * @return a binding error response message containing an error code and a
* UNKNOWN-ATTRIBUTES header * UNKNOWN-ATTRIBUTES header
*/ */
public static Response createBindingErrorResponseUnknownAttributes( public static Response createBindingErrorResponseUnknownAttributes(
String reasonPhrase, String reasonPhrase, char[] unknownAttributes)
char[] unknownAttributes) throws StunException
throws StunException
{ {
return createBindingErrorResponse(ErrorCodeAttribute.UNKNOWN_ATTRIBUTE, return createBindingErrorResponse(
reasonPhrase, ErrorCodeAttribute.UNKNOWN_ATTRIBUTE,
unknownAttributes); reasonPhrase, unknownAttributes);
} }
/** /**
@ -267,25 +297,24 @@ public class MessageFactory
* UNKNOWN-ATTRIBUTES header * UNKNOWN-ATTRIBUTES header
*/ */
public static Response createBindingErrorResponse(char errorCode, public static Response createBindingErrorResponse(char errorCode,
String reasonPhrase) String reasonPhrase) throws StunException
throws StunException
{ {
return createBindingErrorResponse(errorCode, reasonPhrase, null); return createBindingErrorResponse(errorCode, reasonPhrase, null);
} }
/** /**
* Creates a binding error response according to the specified error code. * Creates a binding error response according to the specified error code.
* *
* @param errorCode the error code to encapsulate in this message * @param errorCode the error code to encapsulate in this message attributes
* attributes that had not been recognized. * that had not been recognized.
* @throws StunException INVALID_ARGUMENTS if one or more of the given * @throws StunException INVALID_ARGUMENTS if one or more of the given
* parameters had an invalid value. * parameters had an invalid value.
* *
* @return a binding error response message containing an error code and a * @return a binding error response message containing an error code and a
* UNKNOWN-ATTRIBUTES header * UNKNOWN-ATTRIBUTES header
*/ */
public static Response createBindingErrorResponse(char errorCode) throws public static Response createBindingErrorResponse(char errorCode)
StunException throws StunException
{ {
return createBindingErrorResponse(errorCode, null, null); return createBindingErrorResponse(errorCode, null, null);
} }
@ -302,59 +331,59 @@ public class MessageFactory
try try
{ {
allocateRequest.setMessageType(Message.ALLOCATE_REQUEST); allocateRequest.setMessageType(Message.ALLOCATE_REQUEST);
} } catch (IllegalArgumentException ex)
catch (StunException 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); logger.log(Level.FINE, "Failed to set message type.", ex);
} }
return allocateRequest; return allocateRequest;
} }
/** /**
* Create an allocate request to allocate an even port. * Create an allocate request to allocate an even port. Attention this does
* Attention this does not have attributes for long-term * not have attributes for long-term authentication.
* authentication. *
* @param protocol requested protocol number * @param protocol requested protocol number
* @param rFlag R flag for the EVEN-PORT * @param rFlag R flag for the EVEN-PORT
* @return an allocation request * @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 try
{
allocateRequest.setMessageType(Message.ALLOCATE_REQUEST);
/* XXX add enum somewhere for transport number */
if(protocol != 6 && protocol != 17)
{ {
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 */ return allocateRequest;
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/> * Add the required attributes for long-term authentication.<br/>
* This will also add a MESSAGE-INTEGRITY and FINGERPRINT attribute.<br/> * This will also add a MESSAGE-INTEGRITY and FINGERPRINT attribute.<br/>
* Do not add another attributes after called this method. * Do not add another attributes after called this method.
*
* @param request the original request * @param request the original request
* @param username username value * @param username username value
* @param realm realm value * @param realm realm value
@ -363,137 +392,142 @@ public class MessageFactory
* @throws StunException in case we have a problem creating the username * @throws StunException in case we have a problem creating the username
* realm or nonce attributes. * realm or nonce attributes.
*/ */
public static void addLongTermAuthentifcationAttribute(Request request, public static void addLongTermAuthentifcationAttribute(
byte username[], Request request, byte username[], byte realm[],
byte realm[], byte nonce[]) throws StunException
byte nonce[])
throws StunException
{ {
UsernameAttribute usernameAttr UsernameAttribute usernameAttr = AttributeFactory
= AttributeFactory.createUsernameAttribute(username); .createUsernameAttribute(username);
RealmAttribute realmAttr = AttributeFactory.createRealmAttribute(realm); RealmAttribute realmAttr = AttributeFactory
NonceAttribute nonceAttr = AttributeFactory.createNonceAttribute(nonce); .createRealmAttribute(realm);
NonceAttribute nonceAttr = AttributeFactory
.createNonceAttribute(nonce);
request.addAttribute(usernameAttr); request.addAttribute(usernameAttr);
request.addAttribute(realmAttr); request.addAttribute(realmAttr);
request.addAttribute(nonceAttr); request.addAttribute(nonceAttr);
/* TODO calculate MESSAGE-INTEGRITY and FINGERPRINT */ /* TODO calculate MESSAGE-INTEGRITY and FINGERPRINT */
} }
/** /**
* Create a refresh request. * Create a refresh request.
*
* @param lifetime lifetime value * @param lifetime lifetime value
* @return refresh request * @return refresh request
*/ */
public static Request createRefreshRequest(int lifetime) public static Request createRefreshRequest(int lifetime)
{ {
Request refreshRequest = new Request(); Request refreshRequest = new Request();
try try
{ {
refreshRequest.setMessageType(Message.REFRESH_REQUEST); refreshRequest.setMessageType(Message.REFRESH_REQUEST);
/* add a LIFETIME attribute */ /* add a LIFETIME attribute */
LifetimeAttribute lifetimeReq LifetimeAttribute lifetimeReq = AttributeFactory
= AttributeFactory.createLifetimeAttribute(lifetime); .createLifetimeAttribute(lifetime);
refreshRequest.addAttribute(lifetimeReq); refreshRequest.addAttribute(lifetimeReq);
} } catch (IllegalArgumentException ex)
catch(StunException ex) {
{ logger.log(Level.FINE, "Failed to set message type.", ex);
logger.log(Level.FINE, "Failed to set message type.", ex); }
}
return refreshRequest; return refreshRequest;
} }
/** /**
* Create a ChannelBind request. * Create a ChannelBind request.
*
* @param channelNumber the channel number * @param channelNumber the channel number
* @param peerAddress the peer address * @param peerAddress the peer address
* @param tranID the ID of the transaction that we should be using
* *
* @return channel bind request * @return channel bind request
*/ */
public static Request createChannelBindRequest( public static Request createChannelBindRequest(char channelNumber,
char channelNumber, TransportAddress peerAddress, byte[] tranID)
TransportAddress peerAddress)
{ {
Request channelBindRequest = new Request(); Request channelBindRequest = new Request();
try try
{ {
channelBindRequest.setMessageType(Message.CHANNELBIND_REQUEST); channelBindRequest
.setMessageType(Message.CHANNELBIND_REQUEST);
/* add a CHANNEL-NUMBER attribute */ // add a CHANNEL-NUMBER attribute
ChannelNumberAttribute channelNumberAttribute ChannelNumberAttribute channelNumberAttribute = AttributeFactory
= AttributeFactory.createChannelNumberAttribute(channelNumber); .createChannelNumberAttribute(channelNumber);
channelBindRequest.addAttribute(channelNumberAttribute); channelBindRequest.addAttribute(channelNumberAttribute);
/* add a XOR-PEER-ADDRESS */ // add a XOR-PEER-ADDRESS
XorPeerAddressAttribute peerAddressAttribute XorPeerAddressAttribute peerAddressAttribute = AttributeFactory
= AttributeFactory.createXorPeerAddressAttribute(peerAddress); .createXorPeerAddressAttribute(peerAddress,
channelBindRequest.addAttribute(peerAddressAttribute); tranID);
}
catch(StunException ex)
{
logger.log(Level.FINE, "Failed to set message type.", ex);
}
return channelBindRequest; channelBindRequest.addAttribute(peerAddressAttribute);
} catch (IllegalArgumentException ex)
{
logger.log(Level.FINE, "Failed to set message type.", ex);
}
return channelBindRequest;
} }
/** /**
* Create a Send Indication. * Create a Send Indication.
*
* @param peerAddress peer address * @param peerAddress peer address
* @param data data (could be 0 byte) * @param data data (could be 0 byte)
* @param tranID the ID of the transaction that we should be using
*
* @return send indication message * @return send indication message
*/ */
public static Indication createSendIndication(TransportAddress peerAddress, public static Indication createSendIndication(
byte data[]) TransportAddress peerAddress, byte[] data, byte[] tranID)
{ {
Indication sendIndication = new Indication(); Indication sendIndication = new Indication();
try 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.setMessageType(Message.SEND_INDICATION);
sendIndication.addAttribute(dataAttribute);
}
}
catch(StunException ex)
{
logger.log(Level.FINE, "Failed to set message type.", ex);
}
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() public static Request createShareSecretRequest()
{ {
throw new UnsupportedOperationException( throw new UnsupportedOperationException(
"Shared Secret Support is not currently implemented"); "Shared Secret Support is not currently implemented");
} }
public static Response createSharedSecretResponse() public static Response createSharedSecretResponse()
{ {
throw new UnsupportedOperationException( throw new UnsupportedOperationException(
"Shared Secret Support is not currently implemented"); "Shared Secret Support is not currently implemented");
} }
public static Response createSharedSecretErrorResponse() public static Response createSharedSecretErrorResponse()
{ {
throw new UnsupportedOperationException( 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 * Checks whether requestType is a valid request type and if yes sets it
* as the type of the current instance. * as the type of the current instance.
* @param requestType the type to set * @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 * request type
*/ */
public void setMessageType(char requestType) public void setMessageType(char requestType)
throws StunException throws IllegalArgumentException
{ {
if(!isRequestType(requestType)) if(!isRequestType(requestType))
throw new StunException(StunException.ILLEGAL_ARGUMENT, throw new IllegalArgumentException(
(int)(requestType) (int)(requestType)
+ " - is not a valid request type."); + " - 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 * Checks whether responseType is a valid response type and if yes sets it
* as the type of the current instance. * as the type of the current instance.
* @param responseType the type to set * @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 * response type
*/ */
public void setMessageType(char responseType) public void setMessageType(char responseType)
throws StunException throws IllegalArgumentException
{ {
if(!isResponseType(responseType)) if(!isResponseType(responseType))
throw new StunException(StunException.ILLEGAL_ARGUMENT, throw new IllegalArgumentException(
(int)(responseType) (int)(responseType)
+ " - is not a valid response type."); + " - is not a valid response type.");

View File

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

View File

@ -34,21 +34,33 @@ public class StunDatagramPacketFilter
/** /**
* Initializes a new <tt>StunDatagramPacketFilter</tt> which will accept * Initializes a new <tt>StunDatagramPacketFilter</tt> which will accept
* <tt>DatagramPacket</tt>s which represent STUN messages and which are part * <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 * <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) public StunDatagramPacketFilter(TransportAddress stunServer)
{ {
this.stunServer = 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 * Determines whether a specific <tt>DatagramPacket</tt> represents a STUN
* message which is part of the communication with the STUN server * message and whether it is part of the communication with the STUN server
* associated with this instance. * if one was associated with this instance.
* *
* @param p the <tt>DatagramPacket</tt> which is to be checked whether it is * @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 * 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) 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 * The most significant 2 bits of every STUN message MUST be
* zero or more Attributes. * 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)
{ {
/* byte b1 = data[offset + 1];
* The most significant 2 bits of every STUN message MUST be char method = (char) ((b0 & 0xFE) | (b1 & 0xEF));
* 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) return acceptMethod(method);
{
byte b1 = data[offset + 1];
char method = (char) ((b0 & 0xFE) | (b1 & 0xEF));
return acceptMethod(method);
}
} }
} }
return false; return false;