Implements harvesting of relayed candidates through TURN.

This commit is contained in:
lubomir.marinov 2010-06-30 06:58:16 +00:00
parent b4579547da
commit f15437c37b
14 changed files with 2061 additions and 345 deletions

View File

@ -560,7 +560,7 @@ public abstract class Candidate
*/
protected void setMappedAddress(TransportAddress address)
{
this.turnServerAddress = address;
this.mappedAddress = address;
}
/**
@ -594,17 +594,14 @@ public abstract class Candidate
if(this instanceof RemoteCandidate)
return null;
if ( getType () == CandidateType.SERVER_REFLEXIVE_CANDIDATE
|| getType () == CandidateType.PEER_REFLEXIVE_CANDIDATE)
switch (getType())
{
case SERVER_REFLEXIVE_CANDIDATE:
case PEER_REFLEXIVE_CANDIDATE:
return getBase().getTransportAddress();
}
else if ( getType () == CandidateType.RELAYED_CANDIDATE)
{
case RELAYED_CANDIDATE:
return getMappedAddress();
}
else
{
default:
//host candidate
return null;
}

View File

@ -107,8 +107,8 @@ class ConnectivityCheckClient
{
//we don't need to do a canReach() verification here as it has been
//already verified during the gathering process.
DatagramSocket stunSocket = ((HostCandidate)candidatePair
.getLocalCandidate()) .getStunSocket(null);
DatagramSocket stunSocket
= candidatePair.getLocalCandidate() .getStunSocket(null);
Request request = MessageFactory.createBindingRequest();

View File

@ -8,7 +8,6 @@
package org.ice4j.ice;
import java.net.*;
import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.socket.*;
@ -29,12 +28,6 @@ import org.ice4j.socket.*;
*/
public class HostCandidate extends LocalCandidate
{
/**
* The <tt>Logger</tt> used by the <tt>HostCandidate</tt>
* class and its instances for logging output.
*/
private static final Logger logger = Logger
.getLogger(HostCandidate.class.getName());
/**
* If this is a local candidate the field contains the socket that is
@ -62,6 +55,29 @@ public class HostCandidate extends LocalCandidate
setBase(this);
}
/**
* Creates a new <tt>StunDatagramPacketFilter</tt> which is to capture STUN
* messages and make them available to the <tt>DatagramSocket</tt> returned
* by {@link #getStunSocket(TransportAddress)}.
*
* @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>StunDatagramPacketFilter</tt> which is to capture STUN
* messages and make them available to the <tt>DatagramSocket</tt> returned
* by {@link #getStunSocket(TransportAddress)}
* @see LocalCandidate#createStunDatagramPacketFilter(TransportAddress)
*/
@Override
protected StunDatagramPacketFilter createStunDatagramPacketFilter(
TransportAddress serverAddress)
{
/*
* Since we support TURN as well, we have to be able to receive TURN
* messages as well.
*/
return new TurnDatagramPacketFilter(serverAddress);
}
/**
* Gets the <tt>DatagramSocket</tt> associated with this <tt>Candidate</tt>.
*
@ -73,47 +89,4 @@ public class HostCandidate extends LocalCandidate
{
return socket;
}
/**
* 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
* performing connectivity checks.
*/
public DatagramSocket getStunSocket(TransportAddress serverAddress)
{
DatagramSocket hostSocket = getSocket();
DatagramSocket stunSocket = null;
Throwable exception = null;
if (hostSocket instanceof MultiplexingDatagramSocket)
{
try
{
stunSocket
= ((MultiplexingDatagramSocket) hostSocket)
.getSocket( new StunDatagramPacketFilter(
serverAddress));
}
catch (SocketException sex)//don't u just luv da name? ;)
{
logger.log(Level.SEVERE,
"Failed to acquire DatagramSocket"
+ " specific to STUN communication.",
sex);
exception = sex;
}
}
if (stunSocket == null)
throw new IllegalArgumentException("hostCand", exception);
else
return stunSocket;
}
}

View File

@ -8,8 +8,10 @@
package org.ice4j.ice;
import java.net.*;
import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.socket.*;
import org.ice4j.stack.*;
/**
@ -17,10 +19,17 @@ import org.ice4j.stack.*;
* and are then included in outgoing offers or answers.
*
* @author Emil Ivov
* @author Lubomir Marinov
*/
public abstract class LocalCandidate
extends Candidate
{
/**
* The <tt>Logger</tt> used by the <tt>LocalCandidate</tt> class and its
* instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(HostCandidate.class.getName());
/**
* Creates a <tt>LocalCandidate</tt> instance for the specified transport
@ -39,6 +48,31 @@ public abstract class LocalCandidate
super(transportAddress, parentComponent, type);
}
/**
* Gets the actual/host <tt>DatagramSocket</tt> which implements the
* <tt>DatagramSocket</tt>s exposed by this <tt>LocalCandidate</tt>. The
* default implementation is supposed to be good enough for the general case
* and does not try to be universal - it returns the <tt>hostSocket</tt> of
* the <tt>base</tt> of this <tt>LocalCandidate</tt> if the <tt>base</tt> is
* different than <tt>this</tt> or the <tt>socket</tt> of this
* <tt>LocalCandidate</tt> if it equals its <tt>base</tt>. The row reasoning
* for the implementation is that if any <tt>Candidate</tt> knows about the
* actual/host <tt>DatagramSocket</tt>, this <tt>LocalCandidate</tt> would
* be based on it rather be related to it in any other way.
*
* @return the actual/host <tt>DatagramSocket</tt> which implements the
* <tt>DatagramSocket</tt>s exposed by this <tt>LocalCandidate</tt>
*/
protected DatagramSocket getHostSocket()
{
LocalCandidate base = getBase();
return
((base == this) || (base == null))
? getSocket()
: base.getHostSocket();
}
/**
* Gets the <tt>DatagramSocket</tt> associated with this <tt>Candidate</tt>.
*
@ -47,6 +81,68 @@ public abstract class LocalCandidate
*/
public abstract DatagramSocket getSocket();
/**
* 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
* performing connectivity checks.
*/
public DatagramSocket getStunSocket(TransportAddress serverAddress)
{
DatagramSocket hostSocket = getHostSocket();
DatagramSocket stunSocket = null;
Throwable exception = null;
if (hostSocket instanceof MultiplexingDatagramSocket)
{
DatagramPacketFilter stunDatagramPacketFilter
= createStunDatagramPacketFilter(serverAddress);
try
{
stunSocket
= ((MultiplexingDatagramSocket) hostSocket)
.getSocket(stunDatagramPacketFilter);
}
catch (SocketException sex) //don't u just luv da name? ;)
{
logger.log(Level.SEVERE,
"Failed to acquire DatagramSocket"
+ " specific to STUN communication.",
sex);
exception = sex;
}
}
if (stunSocket == null)
throw new IllegalArgumentException("hostCand", exception);
else
return stunSocket;
}
/**
* Creates a new <tt>StunDatagramPacketFilter</tt> which is to capture STUN
* messages and make them available to the <tt>DatagramSocket</tt> returned
* by {@link #getStunSocket(TransportAddress)}.
*
* @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>StunDatagramPacketFilter</tt> which is to capture STUN
* messages and make them available to the <tt>DatagramSocket</tt> returned
* by {@link #getStunSocket(TransportAddress)}
*/
protected StunDatagramPacketFilter createStunDatagramPacketFilter(
TransportAddress serverAddress)
{
return new StunDatagramPacketFilter(serverAddress);
}
/**
* Frees resources allocated by this candidate such as its
* <tt>DatagramSocket</tt> for example.
@ -55,7 +151,16 @@ public abstract class LocalCandidate
{
//remove our socket from the stack.
StunStack.getInstance().removeSocket(getTransportAddress());
getSocket().close();
// Close the socket associated with this Candidate.
DatagramSocket socket = getSocket();
/*
* Allow this LocalCandiate implementation to not create a socket if it
* still hasn't created one.
*/
if (socket != null)
socket.close();
}
/**
@ -71,9 +176,6 @@ public abstract class LocalCandidate
{
Component parentCmp = getParentComponent();
if (parentCmp == null)
return false;
return equals(parentCmp.getDefaultCandidate());
return (parentCmp != null) && equals(parentCmp.getDefaultCandidate());
}
}

View File

@ -59,6 +59,6 @@ public class PeerReflexiveCandidate
*/
public DatagramSocket getSocket()
{
return ((HostCandidate)getBase()).getSocket();
return getBase().getSocket();
}
}

View File

@ -0,0 +1,117 @@
/*
* 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 org.ice4j.*;
import org.ice4j.ice.harvest.*;
import org.ice4j.socket.*;
/**
* Represents a <tt>Candidate</tt> obtained by sending a TURN Allocate request
* from a <tt>HostCandidate</tt> to a TURN server. The relayed candidate is
* resident on the TURN server, and the TURN server relays packets back towards
* the agent.
*
* @author Lubomir Marinov
*/
public class RelayedCandidate
extends LocalCandidate
{
/**
* The <tt>RelayedCandidateDatagramSocket</tt> which represents the
* application-purposed <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>.
*/
private RelayedCandidateDatagramSocket socket;
/**
* The <tt>TurnCandidateHarvest</tt> which has harvested this
* <tt>RelayedCandidate</tt>.
*/
private final TurnCandidateHarvest turnCandidateHarvest;
/**
* Initializes a new <tt>RelayedCandidate</tt> which is to represent a
* specific <tt>TransportAddress</tt> harvested through a specific
* <tt>HostCandidate</tt> and a TURN server with a specific
* <tt>TransportAddress</tt>.
*
* @param transportAddress the <tt>TransportAddress</tt> to be represented
* by the new instance
* @param turnCandidateHarvest the <tt>TurnCandidateHarvest</tt> which has
* harvested the new instance
* @param mappedAddress the mapped <tt>TransportAddress</tt> reported by the
* TURN server with the delivery of the replayed <tt>transportAddress</tt>
* to be represented by the new instance
*/
public RelayedCandidate(
TransportAddress transportAddress,
TurnCandidateHarvest turnCandidateHarvest,
TransportAddress mappedAddress)
{
super(
transportAddress,
turnCandidateHarvest.hostCandidate.getParentComponent(),
CandidateType.RELAYED_CANDIDATE);
this.turnCandidateHarvest = turnCandidateHarvest;
// RFC 5245: The base of a relayed candidate is that candidate itself.
setBase(this);
setTurnServerAddress(turnCandidateHarvest.harvester.stunServer);
setMappedAddress(mappedAddress);
}
/**
* Gets the actual/host <tt>DatagramSocket</tt> which implements the
* <tt>DatagramSocket</tt>s exposed by this <tt>LocalCandidate</tt>. The
* default implementation is supposed to be good enough for the general case
* and does not try to be universal - it returns the <tt>hostSocket</tt> of
* the <tt>base</tt> of this <tt>LocalCandidate</tt> if the <tt>base</tt> is
* different than <tt>this</tt> or the <tt>socket</tt> of this
* <tt>LocalCandidate</tt> if it equals its <tt>base</tt>. The row reasoning
* for the implementation is that if any <tt>Candidate</tt> knows about the
* actual/host <tt>DatagramSocket</tt>, this <tt>LocalCandidate</tt> would
* be based on it rather be related to it in any other way.
*
* @return the actual/host <tt>DatagramSocket</tt> which implements the
* <tt>DatagramSocket</tt>s exposed by this <tt>LocalCandidate</tt>
* @see LocalCandidate#getHostSocket()
*/
@Override
protected DatagramSocket getHostSocket()
{
return turnCandidateHarvest.hostCandidate.getSocket();
}
/**
* Gets the <tt>DatagramSocket</tt> associated with this <tt>Candidate</tt>.
*
* @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>
* @see LocalCandidate#getSocket()
*/
public synchronized DatagramSocket getSocket()
{
if (socket == null)
{
try
{
socket = new RelayedCandidateDatagramSocket();
}
catch (SocketException sex)
{
throw new UndeclaredThrowableException(sex);
}
}
return socket;
}
}

View File

@ -60,6 +60,6 @@ public class ServerReflexiveCandidate
*/
public DatagramSocket getSocket()
{
return ((HostCandidate)getBase()).getSocket();
return getBase().getSocket();
}
}

View File

@ -0,0 +1,862 @@
/*
* 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.util.*;
import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.ice.*;
import org.ice4j.message.*;
import org.ice4j.security.*;
import org.ice4j.stack.*;
/**
* Represents the harvesting of STUN <tt>Candidates</tt> for a specific
* <tt>HostCandidate</tt> performed by a specific
* <tt>StunCandidateHarvester</tt>.
*
* @author Lubomir Marinov
*/
public class StunCandidateHarvest
extends AbstractResponseCollector
{
/**
* The <tt>Logger</tt> used by the <tt>StunCandidateHarvest</tt> class and
* its instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(StunCandidateHarvest.class.getName());
/**
* The constant which defines an empty array with <tt>Candidate</tt> element
* type. Explicitly defined in order to reduce unnecessary allocations.
*/
private static final Candidate[] NO_CANDIDATES = new Candidate[0];
/**
* The list of <tt>Candidate</tt>s harvested for {@link #hostCandidate} by
* this harvest.
*/
private final List<Candidate> candidates = new LinkedList<Candidate>();
/**
* The indicator which determines whether this <tt>StunCandidateHarvest</tt>
* has completed the harvesting of <tt>Candidate</tt>s for
* {@link #hostCandidate}.
*/
private boolean completedResolvingCandidate = false;
/**
* The <tt>StunCandidateHarvester</tt> performing the harvesting of STUN
* <tt>Candidate</tt>s for a <tt>Component</tt> which this harvest is part
* of.
*/
public final StunCandidateHarvester harvester;
/**
* The <tt>HostCandidate</tt> the STUN harvesting of which is represented by
* this instance.
*/
public final HostCandidate hostCandidate;
/**
* The <tt>LongTermCredential</tt> used by this instance.
*/
private LongTermCredentialSession longTermCredentialSession;
/**
* The STUN <tt>Request</tt>s which have been sent by this instance, have
* not received a STUN <tt>Response</tt> yet and have not timed out. Put in
* place to avoid a limitation of the <tt>ResponseCollector</tt> and its use
* of <tt>StunMessageEvent</tt> which do not make the STUN <tt>Request</tt>
* to which a STUN <tt>Response</tt> responds available though it is known
* in <tt>StunClientTransaction</tt>.
*/
private final Map<TransactionID, Request> requests
= new HashMap<TransactionID, Request>();
/**
* Initializes a new <tt>StunCandidateHarvest</tt> which is to represent the
* harvesting of STUN <tt>Candidate</tt>s for a specific
* <tt>HostCandidate</tt> performed by a specific
* <tt>StunCandidateHarvester</tt>.
*
* @param harvester the <tt>StunCandidateHarvester</tt> which is performing
* the STUN harvesting
* @param hostCandidate the <tt>HostCandidate</tt> for which STUN
* <tt>Candidate</tt>s are to be harvested
*/
public StunCandidateHarvest(
StunCandidateHarvester harvester,
HostCandidate hostCandidate)
{
this.harvester = harvester;
this.hostCandidate = hostCandidate;
}
/**
* Adds a specific <tt>LocalCandidate</tt> to the list of
* <tt>LocalCandidate</tt>s harvested for {@link #hostCandidate} by this
* harvest.
*
* @param candidate the <tt>LocalCandidate</tt> to be added to the list of
* <tt>LocalCandidate</tt>s harvested for {@link #hostCandidate} by this
* harvest
*/
protected void addCandidate(LocalCandidate candidate)
{
if (!candidates.contains(candidate))
{
hostCandidate.getParentComponent().addLocalCandidate(candidate);
candidates.add(candidate);
}
}
/**
* Adds the <tt>Attribute</tt>s to a specific <tt>Request</tt> which support
* the STUN short-term credential mechanism if the mechanism in question is
* utilized by this <tt>StunCandidateHarvest</tt> (i.e. by the associated
* <tt>StunCandidateHarvester</tt>).
*
* @param request the <tt>Request</tt> to which to add the
* <tt>Attribute</tt>s supporting the STUN short-term credential mechanism
* if the mechanism in question is utilized by this
* <tt>StunCandidateHarvest</tt>
* @return <tt>true</tt> if the STUN short-term credential mechanism is
* actually utilized by this <tt>StunCandidateHarvest</tt> for the specified
* <tt>request</tt>; otherwise, <tt>false</tt>
*/
protected boolean addShortTermCredentialAttributes(Request request)
{
String shortTermCredentialUsername
= harvester.getShortTermCredentialUsername();
if (shortTermCredentialUsername != null)
{
request.addAttribute(
AttributeFactory.createUsernameAttribute(
shortTermCredentialUsername));
request.addAttribute(
AttributeFactory.createMessageIntegrityAttribute(
shortTermCredentialUsername));
return true;
}
else
return false;
}
/**
* Completes the harvesting of <tt>Candidate</tt>s for
* {@link #hostCandidate}. Notifies {@link #harvester} about the completion
* of the harvesting of <tt>Candidate</tt> for <tt>hostCandidate</tt>
* performed by this <tt>StunCandidateHarvest</tt>.
*
* @param request the <tt>Request</tt> sent by this
* <tt>StunCandidateHarvest</tt> with which the harvesting of
* <tt>Candidate</tt>s for <tt>hostCandidate</tt> has completed
* @param response the <tt>Response</tt> received by this
* <tt>StunCandidateHarvest</tt>, if any, with which the harvesting of
* <tt>Candidate</tt>s for <tt>hostCandidate</tt> has completed
* @return <tt>true</tt> if the harvesting of <tt>Candidate</tt>s for
* <tt>hostCandidate</tt> performed by this <tt>StunCandidateHarvest</tt>
* has completed; otherwise, <tt>false</tt>
*/
protected boolean completedResolvingCandidate(
Request request,
Response response)
{
if (!completedResolvingCandidate)
{
completedResolvingCandidate = true;
try
{
if (((response == null) || !response.isSuccessResponse())
&& (longTermCredentialSession != null))
{
harvester.stunStack.getCredentialsManager().unregisterAuthority(
longTermCredentialSession);
longTermCredentialSession = null;
}
}
finally
{
harvester.completedResolvingCandidate(this);
}
}
return completedResolvingCandidate;
}
/**
* Creates new <tt>Candidate</tt>s determined by a specific STUN
* <tt>Response</tt>.
*
* @param response the received STUN <tt>Response</tt>
*/
protected void createCandidates(Response response)
{
createServerReflexiveCandidate(response);
}
/**
* Creates a new <tt>Request</tt> instance which is to be sent by this
* <tt>StunCandidateHarvest</tt> in order to retry a specific
* <tt>Request</tt>. For example, the long-term credential mechanism
* dictates that a <tt>Request</tt> is first sent by the client without any
* credential-related attributes, then it gets challenged by the server and
* the client retries the original <tt>Request</tt> with the appropriate
* credential-related attributes in response.
*
* @param request the <tt>Request</tt> which is to be retried by this
* <tt>StunCandidateHarvest</tt>
* @return the new <tt>Request</tt> instance which is to be sent by this
* <tt>StunCandidateHarvest</tt> in order to retry the specified
* <tt>request</tt>
*/
protected Request createRequestToRetry(Request request)
{
switch (request.getMessageType())
{
case Message.BINDING_REQUEST:
return MessageFactory.createBindingRequest();
default:
throw new IllegalArgumentException("request.messageType");
}
}
/**
* Creates a new <tt>Request</tt> which is to be sent to {@link #stunServer}
* in order to start resolving {@link #hostCandidate}.
*
* @return a new <tt>Request</tt> which is to be sent to {@link #stunServer}
* in order to start resolving {@link #hostCandidate}
*/
protected Request createRequestToStartResolvingCandidate()
{
return MessageFactory.createBindingRequest();
}
/**
* Creates a <tt>ServerReflexiveCandidate</tt> using {@link #hostCandidate}
* as its base and the <tt>XOR-MAPPED-ADDRESS</tt> attribute in
* <tt>response</tt> for the actual <tt>TransportAddress</tt> of the new
* candidate. If the message is malformed and/or does not contain the
* corresponding attribute, this method simply has no effect.
*
* @param response the STUN <tt>Response</tt> which is supposed to contain
* the address we should use for the new candidate
*/
protected void createServerReflexiveCandidate(Response response)
{
TransportAddress addr = getMappedAddress(response);
if (addr != null)
{
ServerReflexiveCandidate srvrRflxCand
= createServerReflexiveCandidate(addr);
if (srvrRflxCand != null)
addCandidate(srvrRflxCand);
}
}
/**
* Creates a new <tt>ServerReflexiveCandidate</tt> instance which is to
* represent a specific <tt>TransportAddress</tt> harvested through
* {@link #hostCandidate} and the STUN server associated with
* {@link #harvester}.
*
* @param transportAddress the <tt>TransportAddress</tt> to be represented
* by the new <tt>ServerReflexiveCandidate</tt> instance
* @return a new <tt>ServerReflexiveCandidate</tt> instance which represents
* the specified <tt>TransportAddress</tt> harvested through
* {@link #hostCandidate} and the STUN server associated with
* {@link #harvester}
*/
protected ServerReflexiveCandidate createServerReflexiveCandidate(
TransportAddress transportAddress)
{
return
new ServerReflexiveCandidate(
transportAddress,
hostCandidate,
harvester.stunServer);
}
/**
* Gets the number of <tt>Candidate</tt>s harvested for
* {@link #hostCandidate} during this harvest.
*
* @return the number of <tt>Candidate</tt>s harvested for
* {@link #hostCandidate} during this harvest
*/
int getCandidateCount()
{
return candidates.size();
}
/**
* Gets the <tt>Candidate</tt>s harvested for {@link #hostCandidate} during
* this harvest.
*
* @return an array containing the <tt>Candidate</tt>s harvested for
* {@link #hostCandidate} during this harvest
*/
Candidate[] getCandidates()
{
return candidates.toArray(NO_CANDIDATES);
}
/**
* Gets the <tt>TransportAddress</tt> specified in the XOR-MAPPED-ADDRESS
* attribute of a specific <tt>Response</tt>.
*
* @param response the <tt>Response</tt> from which the XOR-MAPPED-ADDRESS
* attribute is to be retrieved and its <tt>TransportAddress</tt> value is
* to be returned
* @return the <tt>TransportAddress</tt> specified in the XOR-MAPPED-ADDRESS
* attribute of <tt>response</tt>
*/
protected TransportAddress getMappedAddress(Response response)
{
Attribute attribute
= response.getAttribute(Attribute.XOR_MAPPED_ADDRESS);
if(attribute instanceof XorMappedAddressAttribute)
{
return
((XorMappedAddressAttribute) attribute)
.getAddress(response.getTransactionID());
}
else
return null;
}
/**
* Notifies this <tt>StunCandidateHarvest</tt> that a specific STUN
* <tt>Request</tt> has been challenged for a long-term credential (as the
* short-term credential mechanism does not utilize challenging) in a
* specific <tt>realm</tt> and with a specific <tt>nonce</tt>.
*
* @param realm the realm in which the specified STUN <tt>Request</tt> has
* been challenged for a long-term credential
* @param nonce the nonce with which the specified STUN <tt>Request</tt> has
* been challenged for a long-term credential
* @param request the STUN <tt>Request</tt> which has been challenged for a
* long-term credential
* @return <tt>true</tt> if the challenge has been processed and this
* <tt>StunCandidateHarvest</tt> is to continue processing STUN
* <tt>Response</tt>s; otherwise, <tt>false</tt>
* @throws StunException if anything goes wrong while processing the
* challenge
*/
private boolean processChallenge(
byte[] realm,
byte[] nonce,
Request request)
throws StunException
{
UsernameAttribute usernameAttribute
= (UsernameAttribute) request.getAttribute(Attribute.USERNAME);
if (usernameAttribute == null)
{
if (longTermCredentialSession == null)
{
LongTermCredential longTermCredential
= harvester.createLongTermCredential(this, realm);
if (longTermCredential == null)
{
// The long-term credential mechanism is not being utilized.
return false;
}
else
{
longTermCredentialSession
= new LongTermCredentialSession(
longTermCredential,
realm);
harvester
.stunStack
.getCredentialsManager()
.registerAuthority(longTermCredentialSession);
}
}
else
{
/*
* If we're going to use the long-term credential to retry the
* request, the long-term credential should be for the request
* in terms of realm.
*/
if (!longTermCredentialSession.realmEquals(realm))
return false;
}
}
else
{
/*
* If we sent a USERNAME in our request, then we had the long-term
* credential at the time we sent the request in question.
*/
if (longTermCredentialSession == null)
return false;
else
{
/*
* If we're going to use the long-term credential to retry the
* request, the long-term credential should be for the request
* in terms of username.
*/
if (!longTermCredentialSession.usernameEquals(
usernameAttribute.getUsername()))
return false;
else
{
// And it terms of realm, of course.
if (!longTermCredentialSession.realmEquals(realm))
return false;
}
}
}
/*
* The nonce is either becoming known for the first time or being
* updated after the old one has gone stale.
*/
longTermCredentialSession.setNonce(nonce);
Request retryRequest = createRequestToRetry(request);
TransactionID retryRequestTransactionID = null;
if (retryRequest != null)
{
longTermCredentialSession.addAttributes(retryRequest);
retryRequestTransactionID = sendRequest(retryRequest);
}
return (retryRequestTransactionID != null);
}
/**
* Notifies this <tt>StunCandidateHarvest</tt> that a specific STUN
* <tt>Response</tt> has been received and it challenges a specific STUN
* <tt>Request</tt> for a long-term credential (as the short-term credential
* mechanism does not utilize challenging).
*
* @param response the STUN <tt>Response</tt> which has been received
* @param request the STUN <tt>Request</tt> to which <tt>response</tt>
* responds and which it challenges for a long-term credential
* @return <tt>true</tt> if the challenge has been processed and this
* <tt>StunCandidateHarvest</tt> is to continue processing STUN
* <tt>Response</tt>s; otherwise, <tt>false</tt>
* @throws StunException if anything goes wrong while processing the
* challenge
*/
private boolean processChallenge(Response response, Request request)
throws StunException
{
boolean retried = false;
if (response.getAttributeCount() > 0)
{
/*
* The response SHOULD NOT contain a USERNAME or
* MESSAGE-INTEGRITY attribute.
*/
char[] excludedResponseAttributeTypes
= new char[]
{
Attribute.USERNAME,
Attribute.MESSAGE_INTEGRITY
};
boolean challenge = true;
for (char excludedResponseAttributeType
: excludedResponseAttributeTypes)
{
if (response.containsAttribute(excludedResponseAttributeType))
{
challenge = false;
break;
}
}
if (challenge)
{
// This response MUST include a REALM value.
RealmAttribute realmAttribute
= (RealmAttribute) response.getAttribute(Attribute.REALM);
if (realmAttribute == null)
challenge = false;
else
{
// The response MUST include a NONCE.
NonceAttribute nonceAttribute
= (NonceAttribute)
response.getAttribute(Attribute.NONCE);
if (nonceAttribute == null)
challenge = false;
else
{
retried
= processChallenge(
realmAttribute.getRealm(),
nonceAttribute.getNonce(),
request);
}
}
}
}
return retried;
}
/**
* Notifies this <tt>ResponseCollector</tt> that a transaction described by
* the specified <tt>BaseStunMessageEvent</tt> has failed. The possible
* reasons for the failure include timeouts, unreachable destination, etc.
*
* @param event the <tt>BaseStunMessageEvent</tt> which describes the failed
* transaction and the runtime type of which specifies the failure reason
* @see AbstractResponseCollector#processFailure(BaseStunMessageEvent)
*/
protected void processFailure(BaseStunMessageEvent event)
{
TransactionID transactionID = event.getTransactionID();
logger.finest("A transaction expired: tranid=" + transactionID);
logger.finest("localAddr=" + hostCandidate);
/*
* Clean up for the purposes of the workaround which determines the STUN
* Request to which a STUN Response responds.
*/
Request request;
synchronized (requests)
{
request = requests.remove(transactionID);
}
if (request == null)
{
Message message = event.getMessage();
if (message instanceof Request)
request = (Request) message;
}
completedResolvingCandidate(request, null);
}
/**
* Notifies this <tt>ResponseCollector</tt> that a STUN response described
* by the specified <tt>StunResponseEvent</tt> has been received.
*
* @param event the <tt>StunResponseEvent</tt> which describes the received
* STUN response
* @see ResponseCollector#processResponse(StunResponseEvent)
*/
public void processResponse(StunResponseEvent event)
{
TransactionID transactionID = event.getTransactionID();
logger.finest("Received a message: tranid= " + transactionID);
logger.finest("localCand= " + hostCandidate);
/*
* Clean up for the purposes of the workaround which determines the STUN
* Request to which a STUN Response responds.
*/
synchronized (requests)
{
requests.remove(transactionID);
}
// At long last, do start handling the received STUN Response.
Response response = event.getResponse();
Request request = event.getRequest();
boolean completedResolvingCandidate = true;
try
{
if (response.isSuccessResponse())
{
// Authentication and Message-Integrity Mechanisms
if (request.containsAttribute(Attribute.MESSAGE_INTEGRITY))
{
MessageIntegrityAttribute messageIntegrityAttribute
= (MessageIntegrityAttribute)
response.getAttribute(Attribute.MESSAGE_INTEGRITY);
/*
* RFC 5389: If MESSAGE-INTEGRITY was absent, the response
* MUST be discarded, as if it was never received.
*/
if (messageIntegrityAttribute == null)
return;
UsernameAttribute usernameAttribute
= (UsernameAttribute)
request.getAttribute(Attribute.USERNAME);
/*
* For a request or indication message, the agent MUST
* include the USERNAME and MESSAGE-INTEGRITY attributes in
* the message.
*/
if (usernameAttribute == null)
return;
if (!harvester.stunStack.validateMessageIntegrity(
messageIntegrityAttribute,
LongTermCredential.toString(
usernameAttribute.getUsername()),
!request.containsAttribute(Attribute.REALM)
&& !request.containsAttribute(Attribute.NONCE),
event.getRawMessage()))
return;
}
createCandidates(response);
}
else
{
ErrorCodeAttribute errorCodeAttr
= (ErrorCodeAttribute)
response.getAttribute(Attribute.ERROR_CODE);
if ((errorCodeAttr != null)
&& (errorCodeAttr.getErrorClass() == 4))
{
try
{
switch (errorCodeAttr.getErrorNumber())
{
case 1: // 401 Unauthorized
if (processUnauthorized(response, request))
completedResolvingCandidate = false;
break;
case 38: // 438 Stale Nonce
if (processStaleNonce(response, request))
completedResolvingCandidate = false;
break;
}
}
catch (StunException sex)
{
completedResolvingCandidate = true;
}
}
}
}
finally
{
if (completedResolvingCandidate)
completedResolvingCandidate(request, response);
}
}
/**
* Handles a specific STUN error <tt>Response</tt> with error code
* "438 Stale Nonce" to a specific STUN <tt>Request</tt>.
*
* @param response the received STUN error <tt>Response</tt> with error code
* "438 Stale Nonce" which is to be handled
* @param request the STUN <tt>Request</tt> to which <tt>response</tt>
* responds
* @return <tt>true</tt> if the specified STUN error <tt>response</tt> was
* successfully handled; <tt>false</tt>, otherwise
*/
private boolean processStaleNonce(Response response, Request request)
throws StunException
{
/*
* The request MUST contain USERNAME, REALM, NONCE and MESSAGE-INTEGRITY
* attributes.
*/
boolean challenge;
if (request.getAttributeCount() > 0)
{
char[] includedRequestAttributeTypes
= new char[]
{
Attribute.USERNAME,
Attribute.REALM,
Attribute.NONCE,
Attribute.MESSAGE_INTEGRITY
};
challenge = true;
for (char includedRequestAttributeType
: includedRequestAttributeTypes)
{
if (!request.containsAttribute(includedRequestAttributeType))
{
challenge = false;
break;
}
}
}
else
challenge = false;
return (challenge && processChallenge(response, request));
}
/**
* Handles a specific STUN error <tt>Response</tt> with error code
* "401 Unauthorized" to a specific STUN <tt>Request</tt>.
*
* @param response the received STUN error <tt>Response</tt> with error code
* "401 Unauthorized" which is to be handled
* @param request the STUN <tt>Request</tt> to which <tt>response</tt>
* responds
* @return <tt>true</tt> if the specified STUN error <tt>response</tt> was
* successfully handled; <tt>false</tt>, otherwise
*/
private boolean processUnauthorized(Response response, Request request)
throws StunException
{
/*
* If the response is a challenge, retry the request with a new
* transaction.
*/
boolean challenge = true;
/*
* The client SHOULD omit the USERNAME, MESSAGE-INTEGRITY, REALM, and
* NONCE attributes from the "First Request".
*/
if (request.getAttributeCount() > 0)
{
char[] excludedRequestAttributeTypes
= new char[]
{
Attribute.USERNAME,
Attribute.MESSAGE_INTEGRITY,
Attribute.REALM,
Attribute.NONCE
};
for (char excludedRequestAttributeType
: excludedRequestAttributeTypes)
{
if (request.containsAttribute(excludedRequestAttributeType))
{
challenge = false;
break;
}
}
}
return (challenge && processChallenge(response, request));
}
/**
* Sends a specific <tt>Request</tt> to the STUN server associated with this
* <tt>StunCandidateHarvest</tt>.
*
* @param request
* @return
* @throws StunException
*/
protected TransactionID sendRequest(Request request)
throws StunException
{
StunStack stunStack = harvester.stunStack;
TransportAddress stunServer = harvester.stunServer;
TransportAddress hostCandidateTransportAddress
= hostCandidate.getTransportAddress();
TransactionID transactionID;
synchronized (requests)
{
try
{
transactionID
= stunStack
.sendRequest(
request,
stunServer,
hostCandidateTransportAddress,
this);
}
catch (IllegalArgumentException iaex)
{
if (logger.isLoggable(Level.INFO))
{
logger.log(
Level.INFO,
"Failed to send "
+ request
+ " through " + hostCandidateTransportAddress
+ " to " + stunServer,
iaex);
}
throw new StunException(
StunException.ILLEGAL_ARGUMENT,
iaex.getMessage(),
iaex);
}
catch (IOException ioex)
{
if (logger.isLoggable(Level.INFO))
{
logger.log(
Level.INFO,
"Failed to send "
+ request
+ " through " + hostCandidateTransportAddress
+ " to " + stunServer,
ioex);
}
throw new StunException(
StunException.NETWORK_ERROR,
ioex.getMessage(),
ioex);
}
requests.put(transactionID, request);
}
return transactionID;
}
/**
* Starts the harvesting of <tt>Candidate</tt>s to be performed for
* {@link #hostCandidate}.
*
* @return <tt>true</tt> if this <tt>StunCandidateHarvest</tt> has started
* the harvesting of <tt>Candidate</tt>s for {@link #hostCandidate};
* otherwise, <tt>false</tt>
* @throws Exception if anything goes wrong while starting the harvesting of
* <tt>Candidate</tt>s to be performed for {@link #hostCandidate}
*/
boolean startResolvingCandidate()
throws Exception
{
Request requestToStartResolvingCandidate;
if (!completedResolvingCandidate
&& ((requestToStartResolvingCandidate
= createRequestToStartResolvingCandidate())
!= null))
{
// Short-Term Credential Mechanism
addShortTermCredentialAttributes(requestToStartResolvingCandidate);
sendRequest(requestToStartResolvingCandidate);
return true;
}
else
return false;
}
}

View File

@ -7,15 +7,12 @@
*/
package org.ice4j.ice.harvest;
import java.net.*;
import java.util.*;
import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.ice.*;
import org.ice4j.message.*;
import org.ice4j.socket.*;
import org.ice4j.security.*;
import org.ice4j.stack.*;
/**
@ -27,39 +24,41 @@ import org.ice4j.stack.*;
* @author Lubomir Marinov
*/
public class StunCandidateHarvester
extends AbstractResponseCollector
implements CandidateHarvester
{
/**
* The <tt>Logger</tt> used by the <tt>StunCandidateHarvester</tt>
* class and its instances for logging output.
* The <tt>Logger</tt> used by the <tt>StunCandidateHarvester</tt> class and
* its instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(StunCandidateHarvester.class.getName());
/**
* The list of candidates that this harvester has allocated and that it
* needs to keep alive.
* The list of <tt>StunCandidateHarvest</tt>s which have been successfully
* completed i.e. have harvested <tt>Candidate</tt>s.
*/
private List<ServerReflexiveCandidate> allocatedCandidates
= new LinkedList<ServerReflexiveCandidate>();
private final List<StunCandidateHarvest> completedHarvests
= new LinkedList<StunCandidateHarvest>();
/**
* The list of candidates that we are currently resolving.
* The username used by this <tt>StunCandidateHarvester</tt> for the
* purposes of the STUN short-term credential mechanism.
*/
private final Map<TransactionID, HostCandidate> resolveMap
= new Hashtable<TransactionID, HostCandidate>();
private final String shortTermCredentialUsername;
/**
* The <tt>DatagramPacketFilter</tt> which accepts only STUN messages and
* which are part of the communication with {@link #stunServer}.
* The list of <tt>StunCandidateHarvest</tt>s which have been started to
* harvest <tt>Candidate</tt>s for <tt>HostCandidate</tt>s and which have
* not completed yet so {@link #harvest(Component)} has to wait for them.
*/
private DatagramPacketFilter stunDatagramPacketFilter;
private final List<StunCandidateHarvest> startedHarvests
= new LinkedList<StunCandidateHarvest>();
/**
* The address of the STUN server that we will be sending our requests to.
*/
protected final TransportAddress stunServer;
public final TransportAddress stunServer;
/**
* The stack to use for STUN communication.
@ -68,14 +67,35 @@ public class StunCandidateHarvester
/**
* Creates a new STUN harvester that will be running against the specified
* <tt>stunServer</tt>.
* <tt>stunServer</tt> using a specific username for the purposes of the
* STUN short-term credential mechanism.
*
* @param stunServer the address of the STUN server that we will be querying
* for our public bindings
*/
public StunCandidateHarvester(TransportAddress stunServer)
{
this(stunServer, null);
}
/**
* Creates a new STUN harvester that will be running against the specified
* <tt>stunServer</tt> using a specific username for the purposes of the
* STUN short-term credential mechanism.
*
* @param stunServer the address of the STUN server that we will be querying
* for our public bindings
* @param shortTermCredentialUsername the username to be used by the new
* instance for the purposes of the STUN short-term credential mechanism or
* <tt>null</tt> if the use of the STUN short-term credential mechanism is
* not determined at the time of the construction of the new instance
*/
public StunCandidateHarvester(
TransportAddress stunServer,
String shortTermCredentialUsername)
{
this.stunServer = stunServer;
this.shortTermCredentialUsername = shortTermCredentialUsername;
//these should be configurable.
System.setProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER, "400");
@ -83,166 +103,87 @@ public class StunCandidateHarvester
}
/**
* Creates a new <tt>Candidate</tt> determined by a specific STUN response
* and with a specific <tt>HostCandidate</tt> base.
* Notifies this <tt>StunCandidateHarvester</tt> that a specific
* <tt>StunCandidateHarvest</tt> has been completed. If the specified
* harvest has harvested <tt>Candidates</tt>, it is moved from
* {@link #startedHarvests} to {@link #completedHarvests}. Otherwise, it is
* just removed from {@link #startedHarvests}.
*
* @param responseEvent a <tt>StunMessageEvent</tt> which represents the
* STUN response which has been received
* @param localCand the <tt>HostCandidate</tt> for which harvesting is
* executing, the STUN response is associated with and which is to be the
* base of the newly created <tt>Candidate</tt>
* @param harvest the <tt>StunCandidateHarvest</tt> which has been completed
*/
protected void createCandidate(
StunMessageEvent responseEvent,
HostCandidate localCand)
void completedResolvingCandidate(StunCandidateHarvest harvest)
{
createServerReflexiveCandidate(responseEvent.getMessage(), localCand);
}
/**
* Creates a new <tt>Request</tt> which is to be sent to {@link #stunServer}
* in order to start resolving a specific <tt>HostCandidate</tt>.
*
* @param hostCand the <tt>HostCandidate</tt> for which a <tt>Request</tt>
* to start resolving is to be created
* @return a new <tt>Request</tt> which is to be sent to {@link #stunServer}
* in order to start resolving the specified <tt>HostCandidate</tt>
*/
protected Request createRequestToStartResolvingCandidate(
HostCandidate hostCand)
{
return MessageFactory.createBindingRequest();
}
/**
* Creates a <tt>ServerReflexiveCandidate</tt> using <tt>base</tt> as its
* and the <tt>XOR-MAPPED-ADDRESS</tt> attributes in <tt>response</tt> for
* the actual <tt>TransportAddress</tt> of the new candidate. If the message
* is somehow malformed and does not contain the corresponding attribute
* this method simply has no effect.
*
* @param response the <tt>Message</tt> that is supposed to contain the
* address we should use for this candidate.
* @param base the <tt>HostCandidate</tt> that we should use as a base
* for the new <tt>ServerReflexiveCandidate</tt>.
*/
protected void createServerReflexiveCandidate(Message response,
HostCandidate base)
{
Attribute attribute
= response.getAttribute(Attribute.XOR_MAPPED_ADDRESS);
if(attribute instanceof XorMappedAddressAttribute)
synchronized (startedHarvests)
{
TransportAddress addr
= ((XorMappedAddressAttribute) attribute)
.getAddress(response.getTransactionID());
ServerReflexiveCandidate srvrRflxCand
= createServerReflexiveCandidate(addr, base);
startedHarvests.remove(harvest);
if (srvrRflxCand != null)
base.getParentComponent().addLocalCandidate(srvrRflxCand);
//if this was the last candidate, we are done with the STUN
//resolution and need to notify the waiters.
if (startedHarvests.isEmpty())
startedHarvests.notify();
}
synchronized (completedHarvests)
{
if (harvest.getCandidateCount() < 1)
completedHarvests.remove(harvest);
else if (!completedHarvests.contains(harvest))
completedHarvests.add(harvest);
}
}
/**
* Creates a new <tt>ServerReflexiveCandidate</tt> instance which is to
* represent a specific <tt>TransportAddress</tt> harvested through a
* specific <tt>HostCandidate</tt> and the STUN server associated with this
* instance.
* Creates a new <tt>StunCandidateHarvest</tt> instance which is to perform
* STUN harvesting of a specific <tt>HostCandidate</tt>.
*
* @param transportAddress the <tt>TransportAddress</tt> to be represented
* by the new <tt>ServerReflexiveCandidate</tt> instance
* @param base the <tt>HostCandidate</tt> through which the specified
* <tt>TransportAddress</tt> has been harvested
* @return a new <tt>ServerReflexiveCandidate</tt> instance which represents
* the specified <tt>TransportAddress</tt> harvested through the specified
* <tt>HostCandidate</tt> and the STUN server associated with this instance
* @param hostCandidate the <tt>HostCandidate</tt> for which harvesting is
* to be performed by the new <tt>StunCandidateHarvest</tt> instance
* @return a new <tt>StunCandidateHarvest</tt> instance which is to perform
* STUN harvesting of the specified <tt>hostCandidate</tt>
*/
protected ServerReflexiveCandidate createServerReflexiveCandidate(
TransportAddress transportAddress,
HostCandidate base)
protected StunCandidateHarvest createHarvest(HostCandidate hostCandidate)
{
return new ServerReflexiveCandidate(transportAddress, base, stunServer);
return new StunCandidateHarvest(this, hostCandidate);
}
/**
* Creates the <tt>DatagramPacketFilter</tt> which is to be associated with
* the <tt>DatagramSocket</tt> to be used for communication with
* {@link #stunServer} when gathering <tt>Candidate</tt>s for a specific
* <tt>HostCandidate</tt>.
* Creates a <tt>LongTermCredential</tt> to be used by a specific
* <tt>StunCandidateHarvest</tt> for the purposes of the long-term
* credential mechanism in a specific <tt>realm</tt> of the STUN server
* associated with this <tt>StunCandidateHarvester</tt>. The default
* implementation returns <tt>null</tt> and allows extenders to override in
* order to support the long-term credential mechanism.
*
* @return the <tt>DatagramPacketFilter</tt> which is to be associated with
* the <tt>DatagramSocket</tt> to be used for communication with
* {@link #stunServer} when gathering <tt>Candidate</tt>s for a specific
* <tt>HostCandidate</tt>
* @param harvest the <tt>StunCandidateHarvest</tt> which asks for the
* <tt>LongTermCredential</tt>
* @param realm the realm of the STUN server associated with this
* <tt>StunCandidateHarvester</tt> in which <tt>harvest</tt> will use the
* returned <tt>LongTermCredential</tt>
* @return a <tt>LongTermCredential</tt> to be used by <tt>harvest</tt> for
* the purposes of the long-term credential mechanism in the specified
* <tt>realm</tt> of the STUN server associated with this
* <tt>StunCandidateHarvester</tt>
*/
protected DatagramPacketFilter createStunDatagramPacketFilter()
protected LongTermCredential createLongTermCredential(
StunCandidateHarvest harvest,
byte[] realm)
{
return new StunDatagramPacketFilter(stunServer);
// The long-term credential mechanism is not utilized by default.
return null;
}
/**
* Gets the <tt>DatagramPacketFilter</tt> which is to be associated with the
* <tt>DatagramSocket</tt> to be used for communication with
* {@link #stunServer} when gathering <tt>Candidate</tt>s for a specific
* <tt>HostCandidate</tt>.
* Gets the username to be used by this <tt>StunCandidateHarvester</tt> for
* the purposes of the STUN short-term credential mechanism.
*
* @param hostCand the <tt>HostCandidate</tt> for which STUN
* <tt>Candidate</tt>s are to be harvested by this <tt>CandidateHarvester</tt>
* @return the <tt>DatagramPacketFilter</tt> which is to be associated with
* the <tt>DatagramSocket</tt> to be used for communication with
* {@link #stunServer} when gathering <tt>Candidate</tt>s for the specified
* <tt>HostCandidate</tt>
* @return the username to be used by this <tt>StunCandidateHarvester</tt>
* for the purposes of the STUN short-term credential mechanism or
* <tt>null</tt> if the STUN short-term credential mechanism is not to be
* utilized
*/
protected DatagramPacketFilter getStunDatagramPacketFilter(
HostCandidate hostCand)
protected String getShortTermCredentialUsername()
{
if (stunDatagramPacketFilter == null)
stunDatagramPacketFilter = createStunDatagramPacketFilter();
return stunDatagramPacketFilter;
}
/**
* Gets the <tt>DatagramSocket</tt> to be used by this
* <tt>CandidateHarvester</tt> for STUN communication for the purposes of
* harvesting STUN <tt>Candidate</tt>s for a specific
* <tt>HostCandidate</tt>.
*
* @param hostCand the <tt>HostCandidate</tt> for which STUN
* <tt>Candidate</tt>s are to be harvested by this
* <tt>CandidateHarvester</tt>
* @return the <tt>DatagramSocket</tt> to be used by this
* <tt>CandidateHarvester</tt> for STUN communication for the purposes of
* harvesting STUN <tt>Candidate</tt>s for the specified
* <tt>HostCandidate</tt>
*/
private DatagramSocket getStunSocket(HostCandidate hostCand)
{
DatagramSocket hostSocket = hostCand.getSocket();
DatagramSocket stunSocket = null;
Throwable exception = null;
if (hostSocket instanceof MultiplexingDatagramSocket)
try
{
stunSocket
= ((MultiplexingDatagramSocket) hostSocket)
.getSocket(getStunDatagramPacketFilter(hostCand));
}
catch (SocketException sex)
{
logger.log(
Level.SEVERE,
"Failed to acquire DatagramSocket"
+ " specific to STUN communication.",
sex);
exception = sex;
}
if (stunSocket == null)
throw new IllegalArgumentException("hostCand", exception);
else
return stunSocket;
return shortTermCredentialUsername;
}
/**
@ -258,102 +199,11 @@ public class StunCandidateHarvester
{
for (Candidate cand : component.getLocalCandidates())
if (cand instanceof HostCandidate)
{
HostCandidate hostCand = (HostCandidate) cand;
startResolvingCandidate(hostCand);
}
startResolvingCandidate((HostCandidate) cand);
waitForResolutionEnd();
}
/**
* Notifies this <tt>ResponseCollector</tt> that a transaction described by
* the specified <tt>BaseStunMessageEvent</tt> has failed. The possible
* reasons for the failure include timeouts, unreachable destination, etc.
*
* @param event the <tt>BaseStunMessageEvent</tt> which describes the failed
* transaction and the runtime type of which specifies the failure reason
* @see AbstractResponseCollector#processFailure(BaseStunMessageEvent)
*/
protected void processFailure(BaseStunMessageEvent event)
{
processFailure(event.getTransactionID());
}
/**
* Removes the corresponding local candidate from the list of candidates
* that we are waiting on in order to complete the harvest.
*
* @param transactionID the ID of the transaction that has just ended.
*/
private void processFailure(TransactionID transactionID)
{
synchronized (resolveMap)
{
Candidate localCand = resolveMap.remove(transactionID);
//if this was the last candidate, we are done with the STUN
//resolution and need to notify the waiters.
if(resolveMap.isEmpty())
resolveMap.notify();
logger.finest("a tran expired tranid=" + transactionID);
logger.finest("localAddr=" + localCand);
}
}
/**
* Matches the response to one of the local candidates and creates a
* <tt>ServerReflexiveCandidate</tt> using it as a base.
*
* @param response the response that we've just received from a StunServer.
*/
public void processResponse(StunResponseEvent response)
{
synchronized (resolveMap)
{
TransactionID tranID = response.getTransactionID();
HostCandidate localCand = resolveMap.remove(tranID);
if (localCand != null)
createCandidate(response, localCand);
//if this was the last candidate, we are done with the STUN
//resolution and need to notify the waiters.
if (resolveMap.isEmpty())
resolveMap.notify();
logger.finest("received a message tranid=" + tranID);
logger.finest("localCand=" + localCand);
}
}
/**
* Resends a binding request to our stun server through the specified
* <tt>srflxCand</tt> candidate so that it would keep the potential NAT
* mapping valid.
*
* @param srflxCand the <tt>ServerReflexiveCandidate</tt> that we'd like to
* refresh and keep alive.
*/
private void refreshCandidate(ServerReflexiveCandidate srflxCand)
{
try
{
stunStack.sendRequest( MessageFactory.createBindingRequest(),
stunServer,
srflxCand.getBase().getTransportAddress(),
this);
}
catch (Exception exception)
{
logger.log(Level.INFO, "Failed to send a refresh for a candidate",
exception);
}
}
/**
* Sends a binding request to our stun server through the specified
* <tt>hostCand</tt> candidate and adds it to the list of addresses still
@ -368,29 +218,37 @@ public class StunCandidateHarvester
if (!hostCand.getTransportAddress().canReach(stunServer))
return;
synchronized(resolveMap)
StunCandidateHarvest harvest = createHarvest(hostCand);
if (harvest == null)
return;
synchronized (startedHarvests)
{
Request request = createRequestToStartResolvingCandidate(hostCand);
TransactionID tran;
startedHarvests.add(harvest);
boolean started = false;
try
{
tran = stunStack.sendRequest(request, stunServer,
hostCand.getTransportAddress(), this);
started = harvest.startResolvingCandidate();
}
catch (Exception exception)
catch (Exception ex)
{
logger.log(
Level.INFO,
"Failed to send "
+ request
+ " through " + hostCand.getTransportAddress()
+ " to " + stunServer,
exception);
return;
started = false;
if (logger.isLoggable(Level.INFO))
{
logger.log(
Level.INFO,
"Failed to start resolving host candidate "
+ hostCand,
ex);
}
}
finally
{
if (!started)
startedHarvests.remove(harvest);
}
resolveMap.put(tran, hostCand);
}
}
@ -400,15 +258,15 @@ public class StunCandidateHarvester
*/
private void waitForResolutionEnd()
{
synchronized(resolveMap)
synchronized(startedHarvests)
{
boolean interrupted = false;
// Handle spurious wakeups.
while (!resolveMap.isEmpty())
while (!startedHarvests.isEmpty())
try
{
resolveMap.wait();
startedHarvests.wait();
}
catch (InterruptedException iex)
{

View File

@ -0,0 +1,245 @@
/*
* 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.*;
import org.ice4j.attribute.*;
import org.ice4j.ice.*;
import org.ice4j.message.*;
/**
* Represents the harvesting of TURN <tt>Candidates</tt> for a specific
* <tt>HostCandidate</tt> performed by a specific
* <tt>TurnCandidateHarvester</tt>.
*
* @author Lubomir Marinov
*/
public class TurnCandidateHarvest
extends StunCandidateHarvest
{
/**
* The <tt>Request</tt> created by the last call to
* {@link #createRequestToStartResolvingCandidate()}.
*/
private Request requestToStartResolvingCandidate;
/**
* Initializes a new <tt>TurnCandidateHarvest</tt> which is to represent the
* harvesting of TURN <tt>Candidate</tt>s for a specific
* <tt>HostCandidate</tt> performed by a specific
* <tt>TurnCandidateHarvester</tt>.
*
* @param harvester the <tt>TurnCandidateHarvester</tt> which is performing
* the TURN harvesting
* @param hostCandidate the <tt>HostCandidate</tt> for which TURN
* <tt>Candidate</tt>s are to be harvested
*/
public TurnCandidateHarvest(
TurnCandidateHarvester harvester,
HostCandidate hostCandidate)
{
super(harvester, hostCandidate);
}
/**
* Completes the harvesting of <tt>Candidate</tt>s for
* {@link #hostCandidate}. Notifies {@link #harvester} about the completion
* of the harvesting of <tt>Candidate</tt> for <tt>hostCandidate</tt>
* performed by this <tt>StunCandidateHarvest</tt>.
*
* @param request the <tt>Request</tt> sent by this
* <tt>StunCandidateHarvest</tt> with which the harvesting of
* <tt>Candidate</tt>s for <tt>hostCandidate</tt> has completed
* @param response the <tt>Response</tt> received by this
* <tt>StunCandidateHarvest</tt>, if any, with which the harvesting of
* <tt>Candidate</tt>s for <tt>hostCandidate</tt> has completed
* @return <tt>true</tt> if the harvesting of <tt>Candidate</tt>s for
* <tt>hostCandidate</tt> performed by this <tt>StunCandidateHarvest</tt>
* has completed; otherwise, <tt>false</tt>
* @see StunCandidateHarvest#completedResolvingCandidate(Request, Response)
*/
@Override
protected boolean completedResolvingCandidate(
Request request,
Response response)
{
/*
* TODO If the Allocate request is rejected because the server lacks
* resources to fulfill it, the agent SHOULD instead send a Binding
* request to obtain a server reflexive candidate.
*/
if ((response == null)
|| (!response.isSuccessResponse()
&& (request.getMessageType()
== Message.ALLOCATE_REQUEST)))
{
try
{
if (startResolvingCandidate())
return false;
}
catch (Exception ex)
{
/*
* Complete the harvesting of Candidates for hostCandidate
* because the new attempt has just failed.
*/
}
}
return super.completedResolvingCandidate(request, response);
}
/**
* Creates new <tt>Candidate</tt>s determined by a specific STUN
* <tt>Response</tt>.
*
* @param response the received STUN <tt>Response</tt>
* @see StunCandidateHarvester#createCandidates(Response)
*/
@Override
protected void createCandidates(Response response)
{
createRelayedCandidate(response);
// Let the super create the ServerReflexiveCandidate.
super.createCandidates(response);
}
/**
* Creates a <tt>RelayedCandidate</tt> using the
* <tt>XOR-RELAYED-ADDRESS</tt> attribute in a specific STUN
* <tt>Response</tt> for the actual <tt>TransportAddress</tt> of the new
* candidate. If the message is malformed and/or does not contain the
* corresponding attribute, this method simply has no effect.
*
* @param response the STUN <tt>Response</tt> which is supposed to contain
* the address we should use for the new candidate
*/
private void createRelayedCandidate(Response response)
{
Attribute attribute
= response.getAttribute(Attribute.XOR_RELAYED_ADDRESS);
if (attribute instanceof XorRelayedAddressAttribute)
{
TransportAddress relayedAddress
= ((XorRelayedAddressAttribute) attribute).getAddress(
response.getTransactionID());
RelayedCandidate relayedCandidate
= createRelayedCandidate(
relayedAddress,
getMappedAddress(response));
if (relayedCandidate != null)
addCandidate(relayedCandidate);
}
}
/**
* Creates a new <tt>RelayedCandidate</tt> instance which is to represent a
* specific <tt>TransportAddress</tt> harvested through
* {@link #hostCandidate} and the TURN server associated with
* {@link #harvester}.
*
* @param transportAddress the <tt>TransportAddress</tt> to be represented
* by the new <tt>RelayedCandidate</tt> instance
* @param mappedAddress the mapped <tt>TransportAddress</tt> reported by the
* TURN server with the delivery of the relayed <tt>transportAddress</tt> to
* be represented by the new <tt>RelayedCandidate</tt> instance
* @return a new <tt>RelayedCandidate</tt> instance which represents the
* specified <tt>TransportAddress</tt> harvested through
* {@link #hostCandidate} and the TURN server associated with
* {@link #harvester}
*/
protected RelayedCandidate createRelayedCandidate(
TransportAddress transportAddress,
TransportAddress mappedAddress)
{
return
new RelayedCandidate(
transportAddress,
this,
mappedAddress);
}
/**
* Creates a new <tt>Request</tt> instance which is to be sent by this
* <tt>StunCandidateHarvest</tt> in order to retry a specific
* <tt>Request</tt>. For example, the long-term credential mechanism
* dictates that a <tt>Request</tt> is first sent by the client without any
* credential-related attributes, then it gets challenged by the server and
* the client retries the original <tt>Request</tt> with the appropriate
* credential-related attributes in response.
*
* @param request the <tt>Request</tt> which is to be retried by this
* <tt>StunCandidateHarvest</tt>
* @return the new <tt>Request</tt> instance which is to be sent by this
* <tt>StunCandidateHarvest</tt> in order to retry the specified
* <tt>request</tt>
* @see StunCandidateHarvest#createRequestToRetry(Request)
*/
@Override
protected Request createRequestToRetry(Request request)
{
switch (request.getMessageType())
{
case Message.ALLOCATE_REQUEST:
RequestedTransportAttribute requestedTransportAttribute
= (RequestedTransportAttribute)
request.getAttribute(Attribute.REQUESTED_TRANSPORT);
int requestedTransport
= (requestedTransportAttribute == null)
? 17 /* User Datagram Protocol */
: requestedTransportAttribute.getRequestedTransport();
EvenPortAttribute evenPortAttribute
= (EvenPortAttribute) request.getAttribute(Attribute.EVEN_PORT);
boolean rFlag
= (evenPortAttribute == null)
? false
: evenPortAttribute.isRFlag();
return
MessageFactory.createAllocateRequest(
(byte) requestedTransport,
rFlag);
default:
return super.createRequestToRetry(request);
}
}
/**
* Creates a new <tt>Request</tt> which is to be sent to {@link #stunServer}
* in order to start resolving {@link #hostCandidate}.
*
* @return a new <tt>Request</tt> which is to be sent to {@link #stunServer}
* in order to start resolving {@link #hostCandidate}
* @see StunCandidateHarvest#createRequestToStartResolvingCandidate()
*/
@Override
protected Request createRequestToStartResolvingCandidate()
{
if (requestToStartResolvingCandidate == null)
{
requestToStartResolvingCandidate
= MessageFactory.createAllocateRequest(
(byte) 17 /* User Datagram Protocol */,
false);
return requestToStartResolvingCandidate;
}
else if (requestToStartResolvingCandidate.getMessageType()
== Message.ALLOCATE_REQUEST)
{
requestToStartResolvingCandidate
= super.createRequestToStartResolvingCandidate();
return requestToStartResolvingCandidate;
}
else
return null;
}
}

View File

@ -7,26 +7,122 @@
*/
package org.ice4j.ice.harvest;
import org.ice4j.*;
import org.ice4j.ice.*;
import org.ice4j.security.*;
/**
* A <tt>TurnCandidateHarvester</tt> gathers TURN <tt>Candidate</tt>s for a
* specified {@link org.ice4j.ice.Component}.
* Implements a <tt>CandidateHarvester</tt> which gathers TURN
* <tt>Candidate</tt>s for a specified {@link Component}.
*
* @author Emil Ivov
* @author Lubomir Marinov
*/
public class TurnCandidateHarvester
implements CandidateHarvester
extends StunCandidateHarvester
{
/**
* 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.
* The <tt>LongTermCredential</tt> to be used with the TURN server with
* which this instance works.
*/
public void harvest(Component component)
private final LongTermCredential longTermCredential;
/**
* Initializes a new <tt>TurnCandidateHarvester</tt> instance which is to
* work with a specific TURN server.
*
* @param turnServer the <tt>TransportAddress</tt> of the TURN server the
* new instance is to work with
*/
public TurnCandidateHarvester(TransportAddress turnServer)
{
//todo implement
this(turnServer, (LongTermCredential) null);
}
}
/**
* Initializes a new <tt>TurnCandidateHarvester</tt> instance which is to
* work with a specific TURN server using a specific
* <tt>LongTermCredential</tt>.
*
* @param turnServer the <tt>TransportAddress</tt> of the TURN server the
* new instance is to work with
* @param longTermCredential the <tt>LongTermCredential</tt> to use with the
* specified <tt>turnServer</tt> or <tt>null</tt> if the use of the
* long-term credential mechanism is not determined at the time of the
* initialization of the new <tt>TurnCandidateHarvester</tt> instance
*/
public TurnCandidateHarvester(
TransportAddress turnServer,
LongTermCredential longTermCredential)
{
super(turnServer);
this.longTermCredential = longTermCredential;
}
/**
* Initializes a new <tt>TurnCandidateHarvester</tt> instance which is to
* work with a specific TURN server using a specific username for the
* purposes of the STUN short-term credential mechanism.
*
* @param turnServer the <tt>TransportAddress</tt> of the TURN server the
* new instance is to work with
* @param shortTermCredentialUsername the username to be used by the new
* instance for the purposes of the STUN short-term credential mechanism or
* <tt>null</tt> if the use of the STUN short-term credential mechanism is
* not determined at the time of the construction of the new instance
*/
public TurnCandidateHarvester(
TransportAddress turnServer,
String shortTermCredentialUsername)
{
super(turnServer, shortTermCredentialUsername);
this.longTermCredential = null;
}
/**
* Creates a new <tt>TurnCandidateHarvest</tt> instance which is to perform
* TURN harvesting of a specific <tt>HostCandidate</tt>.
*
* @param hostCandidate the <tt>HostCandidate</tt> for which harvesting is
* to be performed by the new <tt>TurnCandidateHarvest</tt> instance
* @return a new <tt>TurnCandidateHarvest</tt> instance which is to perform
* TURN harvesting of the specified <tt>hostCandidate</tt>
* @see StunCandidateHarvester#createHarvest(HostCandidate)
*/
@Override
protected TurnCandidateHarvest createHarvest(HostCandidate hostCandidate)
{
return new TurnCandidateHarvest(this, hostCandidate);
}
/**
* Creates a <tt>LongTermCredential</tt> to be used by a specific
* <tt>StunCandidateHarvest</tt> for the purposes of the long-term
* credential mechanism in a specific <tt>realm</tt> of the TURN server
* associated with this <tt>TurnCandidateHarvester</tt>. The default
* implementation returns <tt>null</tt> and allows extenders to override in
* order to support the long-term credential mechanism.
*
* @param harvest the <tt>StunCandidateHarvest</tt> which asks for the
* <tt>LongTermCredential</tt>
* @param realm the realm of the TURN server associated with this
* <tt>TurnCandidateHarvester</tt> in which <tt>harvest</tt> will use the
* returned <tt>LongTermCredential</tt>
* @return a <tt>LongTermCredential</tt> to be used by <tt>harvest</tt> for
* the purposes of the long-term credential mechanism in the specified
* <tt>realm</tt> of the TURN server associated with this
* <tt>TurnsCandidateHarvester</tt>
* @see StunCandidateHarvester#createLongTermCredential(
* StunCandidateHarvest,byte[])
*/
@Override
protected LongTermCredential createLongTermCredential(
StunCandidateHarvest harvest,
byte[] realm)
{
return longTermCredential;
}
}

View File

@ -0,0 +1,271 @@
/*
* 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.security;
import java.lang.reflect.*;
import java.security.*;
import java.util.*;
import org.ice4j.*;
import org.ice4j.message.*;
/**
* Represents a use of a <tt>LongTermCredential</tt> and implements
* <tt>CredentialsAuthority</tt> for it.
*
* @author Lubomir Marinov
*/
public class LongTermCredentialSession
implements CredentialsAuthority
{
/**
* The <tt>LongTermCredential</tt> a use of which is represented by this
* instance.
*/
private final LongTermCredential longTermCredential;
/**
* The value of the NONCE attribute currently associated with the use of
* {@link #longTermCredential} represented by this instance.
*/
private byte[] nonce;
/**
* The realm (i.e. the value of the REALM attribute) in which a use of
* {@link #longTermCredential} is represented by this instance.
*/
private final byte[] realm;
/**
* Initializes a new <tt>LongTermCredentialSession</tt> instance which
* is to represent a use of a specific <tt>LongTermCredential</tt> in a
* specific realm.
*
* @param longTermCredential the <tt>LongTermCredential</tt> a use of
* which is to be represented by the new instance
* @param realm the realm in which the specified
* <tt>LongTermCredential</tt> is to be used
*/
public LongTermCredentialSession(
LongTermCredential longTermCredential,
byte[] realm)
{
this.longTermCredential = longTermCredential;
this.realm = (realm == null) ? null : realm.clone();
}
/**
* Adds the <tt>Attribute</tt>s to a specific <tt>Request</tt> which support
* the long-term credential mechanism using the <tt>LongTermCredential</tt>
* associated with this instance.
*
* @param request the <tt>Request</tt> in which the <tt>Attribute</tt>
* supporting the STUN long-term credential mechanism are to be added
* @throws StunException if anything goes wrong while adding the
* <tt>Attribute</tt>s to <tt>request</tt> which support the STUN long-term
* credential mechanism
*/
public void addAttributes(Request request)
throws StunException
{
MessageFactory.addLongTermCredentialAttributes(
request,
getUsername(), getRealm(), getNonce());
}
/**
* Determines whether <tt>username</tt> is currently known to this authority
*
* @param username the user name whose validity we'd like to check
* @return <tt>true</tt> if <tt>username</tt> is known to this
* <tt>CredentialsAuthority</tt>; <tt>false</tt>, otherwise
* @see CredentialsAuthority#checkLocalUserName(String)
*/
public boolean checkLocalUserName(String username)
{
/*
* The value of USERNAME is a variable-length value. It MUST contain
* a UTF-8 [RFC3629] encoded sequence of less than 513 bytes, and
* MUST have been processed using SASLprep [RFC4013].
*/
return usernameEquals(LongTermCredential.getBytes(username));
}
/**
* Returns the key (password) that corresponds to the specified local
* username or user frag, an empty array if there was no password for
* that username or <tt>null</tt> if the username is not a local user
* name recognized by this <tt>CredentialsAuthority</tt>.
*
* @param username the local user name or user frag whose credentials
* we'd like to obtain
* @return the key (password) that corresponds to the specified local
* username or user frag, an empty array if there was no password for
* that username or <tt>null</tt> if the username is not a local user
* name recognized by this <tt>CredentialsAuthority</tt>
* @see CredentialsAuthority#getLocalKey(String)
*/
public byte[] getLocalKey(String username)
{
if (!checkLocalUserName(username))
return null;
// MD5(username ":" realm ":" SASLprep(password))
StringBuilder localKeyBuilder = new StringBuilder();
if (username != null)
localKeyBuilder.append(username);
localKeyBuilder.append(':');
String realm = LongTermCredential.toString(getRealm());
if (realm != null)
localKeyBuilder.append(realm);
localKeyBuilder.append(':');
String password = LongTermCredential.toString(getPassword());
if (password != null)
{
// TODO SASLprep
localKeyBuilder.append(password);
}
MessageDigest md5;
try
{
md5 = MessageDigest.getInstance("MD5");
}
catch (NoSuchAlgorithmException nsaex)
{
throw new UndeclaredThrowableException(nsaex);
}
return
md5.digest(LongTermCredential.getBytes(localKeyBuilder.toString()));
}
/**
* Gets the value of the NONCE attribute currently associated with the use
* of the <tt>LongTermCredential</tt> represented by this instance.
*
* @return the value of the NONCE attribute currently associated with the
* use of the <tt>LongTermCredential</tt> represented by this instance
*/
public byte[] getNonce()
{
return (nonce == null) ? null : nonce.clone();
}
/**
* Gets the password of the <tt>LongTermCredential</tt> used by this
* instance.
*
* @return the password of the <tt>LongTermCredential</tt> used by this
* instance
*/
public byte[] getPassword()
{
return longTermCredential.getPassword();
}
/**
* Gets the realm (i.e. the value of the REALM attribute) in which this
* instance uses the <tt>LongTermCredential</tt> associated with it.
*
* @return the realm (i.e. the value of the REALM attribute) in which this
* instance uses the <tt>LongTermCredential</tt> associated with it
*/
public byte[] getRealm()
{
return (realm == null) ? null : realm.clone();
}
/**
* Returns the key (password) that corresponds to the specified remote
* username or user frag, an empty array if there was no password for
* that username or <tt>null</tt> if the username is not a remote user
* name recognized by this <tt>CredentialsAuthority</tt>.
*
* @param username the remote user name or user frag whose credentials
* we'd like to obtain
* @return the key (password) that corresponds to the specified remote
* username or user frag, an empty array if there was no password for
* that username or <tt>null</tt> if the username is not a remote user
* name recognized by this <tt>CredentialsAuthority</tt>
* @see CredentialsAuthority#getRemoteKey(String)
*/
public byte[] getRemoteKey(String username)
{
// The password is the same on the local and the remote sides.
return getLocalKey(username);
}
/**
* Gets the username of the <tt>LongTermCredential</tt> used by this
* instance.
*
* @return the username of the <tt>LongTermCredential</tt> used by this
* instance
*/
public byte[] getUsername()
{
return longTermCredential.getUsername();
}
/**
* Determines whether the realm of this <tt>LongTermCredentialSession</tt>
* is equal to a specific realm.
*
* @param realm the realm to compare for equality to the realm of this
* <tt>LongTermCredentialSession</tt>
* @return <tt>true</tt> if the specified <tt>realm</tt> is equal to the
* realm of this <tt>LongTermCredentialSession</tt>; otherwise,
* <tt>false</tt>
*/
public boolean realmEquals(byte[] realm)
{
return
(realm == null)
? (this.realm == null)
: Arrays.equals(realm, this.realm);
}
/**
* Sets the value of the NONCE attribute to be associated with the use of
* the <tt>LongTermCredential</tt> represented by this instance.
*
* @param nonce the value of the NONCE attribute to be associated with the
* use of the <tt>LongTermCredential</tt> represented by this instance
*/
public void setNonce(byte[] nonce)
{
this.nonce = (nonce == null) ? null : nonce.clone();
}
/**
* Determines whether the username of the <tt>LongTermCredential</tt> used
* by this instance is equal to a specific username.
*
* @param username the username to compare for equality to the username of
* the <tt>LongTermCredential</tt> used by this instance
* @return <tt>true</tt> if the specified <tt>username</tt> is equal to the
* username of the <tt>LongTermCredential</tt> used by this instance;
* otherwise, <tt>false</tt>
*/
public boolean usernameEquals(byte[] username)
{
byte[] thisUsername = getUsername();
return
(username == null)
? (thisUsername == null)
: Arrays.equals(username, thisUsername);
}
}

View File

@ -0,0 +1,83 @@
/*
* 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.socket;
import java.io.*;
import java.net.*;
/**
* Represents an application-purposed (as opposed to a ICE-specific)
* <tt>DatagramSocket</tt> for a <tt>RelayedCandidate</tt> harvested by a
* <tt>TurnCandidateHarvest</tt> (and its associated
* <tt>TurnCandidateHarvester</tt>, of course).
* <tt>RelayedCandidateDatagramSocket</tt> is associated with a successful
* Allocation on a TURN server and implements sends and receives through it
* using TURN messages to and from that TURN server.
*
* @author Lubomir Marinov
*/
public class RelayedCandidateDatagramSocket
extends SafeCloseDatagramSocket
{
/**
* Initializes a new <tt>RelayedCandidateDatagramSocket</tt> instance.
*
* @throws SocketException if anything goes wrong while initializing the new
* <tt>RelayedCandidateDatagramSocket</tt> instance
*/
public RelayedCandidateDatagramSocket()
throws SocketException
{
super(null /* bindaddr */);
}
/**
* Closes this datagram socket.
*
* @see DatagramSocket#close()
*/
@Override
public void close()
{
// TODO Auto-generated method stub
}
/**
* Receives a datagram packet from this socket. When this method returns,
* the <tt>DatagramPacket</tt>'s buffer is filled with the data received.
* The datagram packet also contains the sender's IP address, and the port
* number on the sender's machine.
*
* @param p the <tt>DatagramPacket</tt> into which to place the incoming
* data
* @throws IOException if an I/O error occurs
* @see DatagramSocket#receive(DatagramPacket)
*/
@Override
public void receive(DatagramPacket p)
throws IOException
{
// TODO Auto-generated method stub
}
/**
* Sends a datagram packet from this socket. The <tt>DatagramPacket</tt>
* includes information indicating the data to be sent, its length, the IP
* address of the remote host, and the port number on the remote host.
*
* @param p the <tt>DatagramPacket</tt> to be sent
* @throws IOException if an I/O error occurs
* @see DatagramSocket#send(DatagramPacket)
*/
@Override
public void send(DatagramPacket p)
throws IOException
{
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,112 @@
/*
* 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.socket;
import java.net.*;
import org.ice4j.*;
import org.ice4j.message.*;
/**
* Implements a <tt>DatagramPacketFilter</tt> which accepts
* <tt>DatagramPacket</tt>s which represent TURN messages defined in
* draft-ietf-behave-turn-16 "Traversal Using Relays around NAT (TURN): Relay
* Extensions to Session Traversal Utilities for NAT (STUN)" and which are part
* of the communication with a specific TURN server.
*
* @author Lubomir Marinov
*/
public class TurnDatagramPacketFilter
extends StunDatagramPacketFilter
{
/**
* Initializes a new <tt>TurnDatagramPacketFilter</tt> which will accept
* <tt>DatagramPacket</tt>s which represent TURN messages and which are part
* of the communication with a specific TURN server.
*
* @param turnServer the <tt>TransportAddress</tt> of the TURN server
* <tt>DatagramPacket</tt>s representing TURN messages from and to which
* will be accepted by the new instance
*/
public TurnDatagramPacketFilter(TransportAddress turnServer)
{
super(turnServer);
}
/**
* Determines whether a specific <tt>DatagramPacket</tt> represents a TURN
* message which is part of the communication with the TURN server
* associated with this instance.
*
* @param p the <tt>DatagramPacket</tt> to be checked whether it represents
* a TURN message which is part of the communicator with the TURN server
* associated with this instance
* @return <tt>true</tt> if the specified <tt>DatagramPacket</tt> represents
* a TURN message which is part of the communication with the TURN server
* associated with this instance; otherwise, <tt>false</tt>
*/
@Override
public boolean accept(DatagramPacket p)
{
if (super.accept(p))
{
/*
* The specified DatagramPacket represents a STUN message with a
* TURN method.
*/
return true;
}
else if ((stunServer != null)
&& stunServer.equals(p.getSocketAddress()))
{
// TODO Accept ChannelData messages.
return false;
}
else
{
/*
* The specified DatagramPacket does not come from or is not being
* sent to the TURN server associated with this instance.
*/
return false;
}
}
/**
* Determines whether this <tt>DatagramPacketFilter</tt> accepts a
* <tt>DatagramPacket</tt> which represents a STUN message with a specific
* STUN method. <tt>TurnDatagramPacketFilter</tt> accepts TURN methods.
*
* @param method the STUN method of a STUN message represented by a
* <tt>DatagramPacket</tt> to be checked whether it is accepted by this
* <tt>DatagramPacketFilter</tt>
* @return <tt>true</tt> if this <tt>DatagramPacketFilter</tt> accepts the
* <tt>DatagramPacket</tt> which represents a STUN message with the
* specified STUN method; otherwise, <tt>false</tt>
* @see StunDatagramPacketFilter#acceptMethod(char)
*/
@Override
protected boolean acceptMethod(char method)
{
if (super.acceptMethod(method))
return true;
else
switch (method)
{
case Message.TURN_METHOD_ALLOCATE:
case Message.TURN_METHOD_CHANNELBIND:
case Message.TURN_METHOD_DATA:
case Message.TURN_METHOD_REFRESH:
case Message.TURN_METHOD_SEND:
return true;
default:
return false;
}
}
}