Resolves several conflicts

This commit is contained in:
emcho 2010-02-15 15:53:00 +00:00
parent fda00cfa8a
commit a8c22244fb
8 changed files with 229 additions and 52 deletions

View File

@ -1,8 +1,8 @@
/* /*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
* *
* Distributable under LGPL license. * Distributable under LGPL license. See terms of license at gnu.org.
* See terms of license at gnu.org.
*/ */
package org.ice4j; package org.ice4j;
@ -12,15 +12,13 @@ import java.net.*;
* The interface is used as a callback when sending a request. The response * The interface is used as a callback when sending a request. The response
* collector is then used as a means of dispatching the response. * collector is then used as a means of dispatching the response.
* *
* <p>Organization: Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p>
* @author Emil Ivov * @author Emil Ivov
* @version 0.1
*/ */
public interface ResponseCollector public interface ResponseCollector
{ {
/** /**
* Dispatch the specified response. * Dispatch the specified response.
*
* @param response the response to dispatch. * @param response the response to dispatch.
*/ */
public void processResponse(StunMessageEvent response); public void processResponse(StunMessageEvent response);

View File

@ -7,7 +7,14 @@
*/ */
package org.ice4j.ice.harvest; package org.ice4j.ice.harvest;
import java.io.*;
import java.net.*;
import java.util.*;
import org.ice4j.*;
import org.ice4j.ice.*; import org.ice4j.ice.*;
import org.ice4j.message.*;
import org.ice4j.stack.*;
/** /**
* A <tt>StunCandidateHarvester</tt> gathers STUN <tt>Candidate</tt>s for a * A <tt>StunCandidateHarvester</tt> gathers STUN <tt>Candidate</tt>s for a
@ -16,19 +23,150 @@ import org.ice4j.ice.*;
* @author Emil Ivov * @author Emil Ivov
*/ */
public class StunCandidateHarvester public class StunCandidateHarvester
implements CandidateHarvester implements CandidateHarvester,
ResponseCollector
{ {
/**
* The stack to use for STUN communication.
*/
private final StunStack stunStack;
/**
* The address of the STUN server that we will be sending our requests to.
*/
private final TransportAddress stunServer;
/**
* The list of candidates that we are currently resolving.
*/
private final List<HostCandidate> resolveList
= new LinkedList<HostCandidate>();
/**
* Creates a new STUN harvester that will be running against the specified
* <tt>stunServer</tt>.
*
* @param stunServer the address of the STUN server that we will be querying
* for our public bindings
*/
public StunCandidateHarvester(TransportAddress stunServer)
{
stunStack = StunStack.getInstance();
this.stunServer = stunServer;
//these should be configurable.
System.setProperty("org.ice4j.MAX_WAIT_INTERVAL", "400");
System.setProperty("org.ice4j.MAX_RETRANSMISSIONS", "2");
}
/** /**
* Gathers STUN candidates for all host <tt>Candidate</tt>s that are already * Gathers STUN candidates for all host <tt>Candidate</tt>s that are already
* present in the specified <tt>component</tt>. * present in the specified <tt>component</tt>. This method relies on the
* specified <tt>component</tt> to already contain all its host candidates
* so that it would resolve them.
* *
* @param component the {@link Component} that we'd like to gather candidate * @param component the {@link Component} that we'd like to gather candidate
* STUN <tt>Candidate</tt>s for. * STUN <tt>Candidate</tt>s for.
*/ */
public void harvest(Component component) public void harvest(Component component)
{ {
//todo implement List<Candidate> localCandidates = component.getLocalCandidates();
for(Candidate cand : localCandidates)
{
if ( !(cand instanceof HostCandidate) )
continue;
HostCandidate hostCand = (HostCandidate)cand;
startResolvingCandidate(hostCand);
waitForResolutionEnd();
}
}
/**
* Sends a binding request to our stun server through the specified
* <tt>hostCand</tt> candidate and adds it to the list of addresses still
* waiting for resolution.
*
* @param hostCand the <tt>HostCandidate</tt> that we'd like to resolve.
*/
private void startResolvingCandidate(HostCandidate hostCand)
{
DatagramSocket sock = hostCand.getSocket();
stunStack.addSocket(sock);
synchronized(resolveList)
{
resolveList.add(hostCand);
}
try
{
stunStack.sendRequest(MessageFactory.createBindingRequest(),
stunServer, sock, this);
}
catch (Exception e)
{
synchronized(resolveList)
{
resolveList.remove(hostCand);
}
}
}
/**
* Blocks the current thread until all resolutions in this harverster
* have terminated one way or another.
*/
private void waitForResolutionEnd()
{
synchronized(resolveList)
{
if(resolveList.isEmpty())
return;
try
{
resolveList.wait();
}
catch (InterruptedException e){}
}
}
/**
* Try to figure out .
*
* @param response the response to dispatch.
*/
public void processResponse(StunMessageEvent response)
{
response.getMessage().getTransactionID();
}
/**
* Notify the collector that no response had been received
* after repeated retransmissions of the original request (as described
* by rfc3489) and that the request should be considered unanswered.
*/
public void processTimeout()
{
}
/**
* Called when one of our requests results in a
* <tt>PortUnreachableException</tt> ... which is actually quite rare
* because of the oddities of the BSD and Java socket implementations, which
* is why we currently ignore this method.
*
* @param exception the <tt>PortUnreachableException</tt> which signaled
* that the destination of the request was found to be unreachable
*/
public void processUnreachable(PortUnreachableException exception)
{
} }
} }

View File

@ -18,11 +18,8 @@ import org.ice4j.attribute.*;
* STUN attributes, the set of which depends on the message type. The STUN * STUN attributes, the set of which depends on the message type. The STUN
* header contains a STUN message type, transaction ID, and length. * header contains a STUN message type, transaction ID, and length.
* *
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p>
* @author Emil Ivov * @author Emil Ivov
* @author Sebastien Vincent * @author Sebastien Vincent
* @version 0.1
*/ */
public abstract class Message public abstract class Message
{ {
@ -97,7 +94,8 @@ public abstract class Message
* so we'll be using a LinkedHashMap * so we'll be using a LinkedHashMap
*/ */
//not sure this is the best solution but I'm trying to keep entry order //not sure this is the best solution but I'm trying to keep entry order
protected LinkedHashMap<Character, Attribute> attributes = new LinkedHashMap<Character, Attribute>(); protected LinkedHashMap<Character, Attribute> attributes
= new LinkedHashMap<Character, Attribute>();
/** /**
* Desribes which attributes are present in which messages. An * Desribes which attributes are present in which messages. An
@ -187,7 +185,7 @@ public abstract class Message
protected static final byte PRIORITY_PRESENTITY_INDEX = 28; protected static final byte PRIORITY_PRESENTITY_INDEX = 28;
protected static final byte ICE_CONTROLLING_PRESENTITY_INDEX = 29; protected static final byte ICE_CONTROLLING_PRESENTITY_INDEX = 29;
protected static final byte ICE_CONTROLLED_PRESENTITY_INDEX = 30; protected static final byte ICE_CONTROLLED_PRESENTITY_INDEX = 30;
protected static final byte USE_CANDIDATE_PRESENTITY_INDEX = 31; protected static final byte USE_CANDIDATE_PRESENTITY_INDEX = 31;
protected final static byte attributePresentities[][] = new byte[][]{ protected final static byte attributePresentities[][] = new byte[][]{
// Binding Shared Shared Shared Alloc Alloc Rfrsh Rfrsh ChnlBnd ChnlBnd Send Data // Binding Shared Shared Shared Alloc Alloc Rfrsh Rfrsh ChnlBnd ChnlBnd Send Data
@ -213,7 +211,7 @@ public abstract class Message
/*ALTERNATE_SERVER*/ { O, O, O, O, O, O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, /*ALTERNATE_SERVER*/ { O, O, O, O, O, O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
/*REALM*/ { O, N_A, N_A, N_A, M, N_A, O, O, O, O, O, O, N_A, N_A}, /*REALM*/ { O, N_A, N_A, N_A, M, N_A, O, O, O, O, O, O, N_A, N_A},
/*NONCE*/ { O, N_A, N_A, N_A, M, N_A, O, O, O, O, O, O, N_A, N_A}, /*NONCE*/ { O, N_A, N_A, N_A, M, N_A, O, O, O, O, O, O, N_A, N_A},
/*FINGERPRINT*/ { O, O, O, O, O, O, O, O, O, O, O, O, N_A, N_A}, /*FINGERPRINT*/ { O, O, O, O, O, O, O, O, O, O, O, O, N_A, N_A},
/*CHANNEL-NUMBER*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A}, /*CHANNEL-NUMBER*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A},
/*LIFETIME*/ { N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, M, N_A, N_A, N_A, N_A, N_A}, /*LIFETIME*/ { N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, M, N_A, N_A, N_A, N_A, N_A},
/*XOR-PEER-ADDRESS*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, M, M}, /*XOR-PEER-ADDRESS*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, M, M},
@ -493,12 +491,13 @@ public abstract class Message
/** /**
* Returns a binary representation of this message. * Returns a binary representation of this message.
*
* @return a binary representation of this message. * @return a binary representation of this message.
* @throws StunException if the message does not have all required * @throws IllegalStateException if the message does not have all
* attributes. * required attributes.
*/ */
public byte[] encode() public byte[] encode()
throws StunException throws IllegalStateException
{ {
//make sure we have everything necessary to encode a proper message //make sure we have everything necessary to encode a proper message
validateAttributePresentity(); validateAttributePresentity();
@ -514,11 +513,18 @@ public abstract class Message
System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4); System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4);
offset+=4; offset+=4;
System.arraycopy(getTransactionID(), 0, binMsg, offset, TRANSACTION_ID_LENGTH); System.arraycopy(getTransactionID(), 0, binMsg, offset,
TRANSACTION_ID_LENGTH);
offset+=TRANSACTION_ID_LENGTH; offset+=TRANSACTION_ID_LENGTH;
for (Attribute attribute : attributes.values()) Iterator<Map.Entry<Character, Attribute>> iter
= attributes.entrySet().iterator();
while (iter.hasNext())
{ {
Attribute attribute
= ((Map.Entry<Character, Attribute>)iter.next()).getValue();
byte[] attBinValue = attribute.encode(); byte[] attBinValue = attribute.encode();
System.arraycopy(attBinValue, 0, binMsg, offset, attBinValue.length); System.arraycopy(attBinValue, 0, binMsg, offset, attBinValue.length);
offset += attBinValue.length; offset += attBinValue.length;
@ -567,7 +573,7 @@ public abstract class Message
/* copy the cookie */ /* copy the cookie */
byte cookie[] = new byte[4]; byte cookie[] = new byte[4];
System.arraycopy(binMessage, offset, cookie, 0, 4); System.arraycopy(binMessage, offset, cookie, 0, 4);
offset+=4; offset+=4;
if(arrayLen - offset - TRANSACTION_ID_LENGTH < length) if(arrayLen - offset - TRANSACTION_ID_LENGTH < length)
throw new StunException(StunException.ILLEGAL_ARGUMENT, throw new StunException(StunException.ILLEGAL_ARGUMENT,
@ -596,18 +602,16 @@ public abstract class Message
* Verify that the message has all obligatory attributes and throw an * Verify that the message has all obligatory attributes and throw an
* exception if this is not the case. * exception if this is not the case.
* *
* @throws StunException (ILLEGAL_STATE)if the message does not have all * @throws IllegalStateException if the message does not have all
* required attributes. * required attributes.
*/ */
protected void validateAttributePresentity() protected void validateAttributePresentity()
throws StunException throws IllegalStateException
{ {
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 StunException(StunException.ILLEGAL_STATE, throw new IllegalStateException(
"A mandatory attribute (type=" "A mandatory attribute (type=" +(int)i + ") is missing!");
+(int)i
+ ") is missing!");
} }
@ -665,6 +669,11 @@ public abstract class Message
return ((type & 0x0110) == STUN_REQUEST); return ((type & 0x0110) == STUN_REQUEST);
} }
/**
* Returns a <tt>String</tt> representation of this message.
*
* @return a <tt>String</tt> representation of this message.
*/
public String toString() public String toString()
{ {
return getName()+"("+getMessageType() return getName()+"("+getMessageType()

View File

@ -83,11 +83,8 @@ class Connector
/** /**
* Start the network listening thread. * Start the network listening thread.
*
* @throws IOException if we fail to setup the socket.
*/ */
void start() void start()
throws IOException
{ {
this.isRunning = true; this.isRunning = true;
Thread thread = new Thread(this); Thread thread = new Thread(this);

View File

@ -138,11 +138,8 @@ class NetAccessManager
* has no effect. * has no effect.
* *
* @param socket the socket that the access point should use. * @param socket the socket that the access point should use.
*
* @throws IOException if we fail to setup the socket.
*/ */
protected void addSocket(DatagramSocket socket) protected void addSocket(DatagramSocket socket)
throws IOException
{ {
//no null check - let it through a null pointer exception //no null check - let it through a null pointer exception
TransportAddress localAddr = new TransportAddress( TransportAddress localAddr = new TransportAddress(
@ -261,12 +258,11 @@ class NetAccessManager
* through the network socket. * through the network socket.
* @throws IllegalArgumentException if the apDescriptor references an * @throws IllegalArgumentException if the apDescriptor references an
* access point that had not been installed, * access point that had not been installed,
* @throws StunException if message encoding fails,
*/ */
void sendMessage(Message stunMessage, void sendMessage(Message stunMessage,
TransportAddress srcAddr, TransportAddress srcAddr,
TransportAddress remoteAddr) TransportAddress remoteAddr)
throws IOException, IllegalArgumentException, StunException throws IOException, IllegalArgumentException
{ {
byte[] bytes = stunMessage.encode(); byte[] bytes = stunMessage.encode();
Connector ap = netAccessPoints.get(srcAddr); Connector ap = netAccessPoints.get(srcAddr);

View File

@ -231,11 +231,16 @@ class StunClientTransaction
* @throws IOException if an error occurs while sending message bytes * @throws IOException if an error occurs while sending message bytes
* through the network socket. * through the network socket.
* @throws IllegalArgumentException if the apDescriptor references an * @throws IllegalArgumentException if the apDescriptor references an
<<<<<<< HEAD
* access point that had not been installed * access point that had not been installed
* @throws StunException if message encoding fails * @throws StunException if message encoding fails
=======
* access point that had not been installed,
*
>>>>>>> Makes stun transactions more visible to users of the stun stack
*/ */
void sendRequest() void sendRequest()
throws StunException, IllegalArgumentException, IOException throws IllegalArgumentException, IOException
{ {
sendRequest0(); sendRequest0();
@ -249,10 +254,9 @@ class StunClientTransaction
* through the network socket. * through the network socket.
* @throws IllegalArgumentException if the apDescriptor references an * @throws IllegalArgumentException if the apDescriptor references an
* access point that had not been installed, * access point that had not been installed,
* @throws StunException if message encoding fails,
*/ */
private void sendRequest0() private void sendRequest0()
throws StunException, IllegalArgumentException, IOException throws IllegalArgumentException, IOException
{ {
if(cancelled) if(cancelled)
{ {

View File

@ -92,10 +92,8 @@ public class StunStack
* specified socket and returns a relevant descriptor. * specified socket and returns a relevant descriptor.
* *
* @param sock The socket that the new access point should represent. * @param sock The socket that the new access point should represent.
* @throws IOException if we fail to setup the socket.
*/ */
public void addSocket(DatagramSocket sock) public void addSocket(DatagramSocket sock)
throws IOException
{ {
netAccessManager.addSocket(sock); netAccessManager.addSocket(sock);
} }
@ -195,17 +193,19 @@ public class StunStack
* @param collector the instance to notify when a response arrives or the * @param collector the instance to notify when a response arrives or the
* the transaction timeouts * the transaction timeouts
* *
* @return the <tt>TransactionID</tt> of the <tt>StunClientTransaction</tt>
* that we used in order to send the request.
*
* @throws IOException if an error occurs while sending message bytes * @throws IOException if an error occurs while sending message bytes
* through the network socket. * through the network socket.
* @throws IllegalArgumentException if the apDescriptor references an * @throws IllegalArgumentException if the apDescriptor references an
* access point that had not been installed, * access point that had not been installed,
* @throws StunException if message encoding fails
*/ */
public void sendRequest( Request request, public TransactionID sendRequest( Request request,
TransportAddress sendTo, TransportAddress sendTo,
TransportAddress sendThrough, TransportAddress sendThrough,
ResponseCollector collector ) ResponseCollector collector )
throws StunException, IOException, IllegalArgumentException throws IOException, IllegalArgumentException
{ {
StunClientTransaction clientTransaction StunClientTransaction clientTransaction
= new StunClientTransaction(this, request, sendTo, sendThrough, = new StunClientTransaction(this, request, sendTo, sendThrough,
@ -215,6 +215,38 @@ public class StunStack
clientTransaction); clientTransaction);
clientTransaction.sendRequest(); clientTransaction.sendRequest();
return clientTransaction.getTransactionID();
}
/**
* Sends the specified request through the specified access point, and
* registers the specified ResponseCollector for later notification.
* @param request the request to send
* @param sendTo the destination address of the request.
* @param sendThrough the socket that we should send the request through.
* @param collector the instance to notify when a response arrives or the
* the transaction timeouts
*
* @return the <tt>TransactionID</tt> of the <tt>StunClientTransaction</tt>
* that we used in order to send the request.
*
* @throws IOException if an error occurs while sending message bytes
* through the network socket.
* @throws IllegalArgumentException if the apDescriptor references an
* access point that had not been installed,
*/
public TransactionID sendRequest( Request request,
TransportAddress sendTo,
DatagramSocket sendThrough,
ResponseCollector collector )
throws IOException, IllegalArgumentException
{
TransportAddress sendThroughAddr = new TransportAddress(
sendThrough.getLocalAddress(), sendThrough.getLocalPort(),
Transport.UDP);
return sendRequest(request, sendTo, sendThroughAddr, collector);
} }
/** /**

View File

@ -37,19 +37,22 @@ class TransactionID
*/ */
private int hashCode = 0; private int hashCode = 0;
/**
* Limits access to <tt>TransactionID</tt> instantiation.
*/
private TransactionID() private TransactionID()
{ {
} }
/** /**
* Creates a transaction id object.The transaction id itself is genereated * Creates a transaction id object.The transaction id itself is generated
* using the folloing algorithm: * using the following algorithm:
* *
* The first 6 bytes of the id are given the value of System.currentTimeMillis() * The first 6 bytes of the id are given the value of
* Putting the right most bits first so that we get a more optimized equals() * <tt>System.currentTimeMillis()</tt>. Putting the right most bits first
* method. * so that we get a more optimized equals() method.
* *
* @return A TransactionID object with a unique transaction id. * @return A <tt>TransactionID</tt> object with a unique transaction id.
*/ */
static TransactionID createTransactionID() static TransactionID createTransactionID()
{ {