+ * Note: The method is part of the internal API of + * RelayedCandidate and TurnCandidateHarvest and is not + * intended for public use. + *
+ * + * @return the RelayedCandidateDatagramSocket of this + * RelayedCandidate + */ + public synchronized GoogleRelayedCandidateDatagramSocket + getRelayedCandidateDatagramSocket() + { + if (relayedCandidateDatagramSocket == null) + { + try + { + relayedCandidateDatagramSocket + = new GoogleRelayedCandidateDatagramSocket( + this, + turnCandidateHarvest, + username); + } + catch (SocketException sex) + { + throw new UndeclaredThrowableException(sex); + } + } + return relayedCandidateDatagramSocket; + } + + /** + * Gets the application-purposed DatagramSocket associated with + * this Candidate. + * + * @return the DatagramSocket associated with this + * Candidate + * @see LocalCandidate#getSocket() + */ + public synchronized DatagramSocket getSocket() + { + if (socket == null) + { + try + { + socket + = new MultiplexingDatagramSocket( + getRelayedCandidateDatagramSocket()); + } + catch (SocketException sex) + { + throw new UndeclaredThrowableException(sex); + } + } + return socket; + } +} \ No newline at end of file diff --git a/src/org/ice4j/ice/LocalCandidate.java b/src/org/ice4j/ice/LocalCandidate.java index e0ec25d..a9fe8c9 100644 --- a/src/org/ice4j/ice/LocalCandidate.java +++ b/src/org/ice4j/ice/LocalCandidate.java @@ -24,6 +24,11 @@ import org.ice4j.stack.*; public abstract class LocalCandidate extends Candidate { + /** + * Ufrag for the local candidat + */ + private String ufrag = null; + /** * The Logger used by the LocalCandidate class and its * instances for logging output. @@ -191,4 +196,24 @@ public abstract class LocalCandidate return (parentCmp != null) && equals(parentCmp.getDefaultCandidate()); } + + /** + * Set the local ufrag. + * + * @param ufrag local ufrag + */ + public void setUfrag(String ufrag) + { + this.ufrag = ufrag; + } + + /** + * Get the local ufrag. + * + * @return local ufrag + */ + public String getUfrag() + { + return ufrag; + } } diff --git a/src/org/ice4j/ice/NetworkUtils.java b/src/org/ice4j/ice/NetworkUtils.java index 1c15857..2b860af 100644 --- a/src/org/ice4j/ice/NetworkUtils.java +++ b/src/org/ice4j/ice/NetworkUtils.java @@ -61,17 +61,16 @@ public class NetworkUtils public static final String IN_ADDR_ANY = determineAnyAddress(); /** - * The maximum int value that could correspond to a port nubmer. + * The maximum int value that could correspond to a port number. */ public static final int MAX_PORT_NUMBER = 65535; /** - * The minimum int value that could correspond to a port nubmer bindable - * by the SIP Communicator. + * The minimum int value that could correspond to a port number bindable + * by ice4j. */ public static final int MIN_PORT_NUMBER = 1024; - /** * The random port number generator that we use in getRandomPortNumer() */ diff --git a/src/org/ice4j/ice/RemoteCandidate.java b/src/org/ice4j/ice/RemoteCandidate.java index 51a2467..ee209fa 100644 --- a/src/org/ice4j/ice/RemoteCandidate.java +++ b/src/org/ice4j/ice/RemoteCandidate.java @@ -24,6 +24,11 @@ public class RemoteCandidate */ private TransportAddress raddr; + /** + * Ufrag for the Google Talk candidate. + */ + private String ufrag = null; + /** * Creates a RemoteCandidate instance for the specified transport * address and properties. @@ -49,6 +54,32 @@ public class RemoteCandidate setPriority(priority); } + /** + * Creates a RemoteCandidate instance for the specified transport + * address and properties. + * + * @param transportAddress the transport address that this candidate is + * encapsulating. + * @param parentComponent the Component that this candidate + * belongs to. + * @param type the CandidateType for this Candidate. + * @param foundation the RemoteCandidate's foundation as reported + * by the session description protocol. + * @param priority the RemoteCandidate's priority as reported + * by the session description protocol. + * @param ufrag ufrag for the remote candidate + */ + public RemoteCandidate(TransportAddress transportAddress, + Component parentComponent, + CandidateType type, + String foundation, + long priority, + String ufrag) + { + this(transportAddress, parentComponent, type, foundation, priority); + this.ufrag = ufrag; + } + /** * Sets the priority of this RemoteCandidate. Priority is a unique * priority number that MUST be a positive integer between 1 and @@ -114,4 +145,14 @@ public class RemoteCandidate { this.raddr = relatedAddr; } + + /** + * Get the remote ufrag. + * + * @return remote ufrag + */ + public String getUfrag() + { + return ufrag; + } } diff --git a/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java b/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java new file mode 100644 index 0000000..c3f374b --- /dev/null +++ b/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java @@ -0,0 +1,390 @@ +/* + * 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.util.logging.*; + +import org.ice4j.*; +import org.ice4j.attribute.*; +import org.ice4j.ice.*; +import org.ice4j.message.*; +import org.ice4j.socket.*; +import org.ice4j.stack.*; + +/** + * Represents the harvesting of Google TURN Candidates for a specific + * HostCandidate performed by a specific + * GoogleTurnCandidateHarvester. + * + * @author Lyubomir Marinov + * @author Sebastien Vincent + */ +public class GoogleTurnCandidateHarvest + extends StunCandidateHarvest +{ + /** + * The Logger used by the TurnCandidateHarvest class and + * its instances for logging output. + */ + private static final Logger logger + = Logger.getLogger(GoogleTurnCandidateHarvest.class.getName()); + + /** + * The Request created by the last call to + * {@link #createRequestToStartResolvingCandidate()}. + */ + private Request requestToStartResolvingCandidate; + + /** + * Initializes a new TurnCandidateHarvest which is to represent the + * harvesting of TURN Candidates for a specific + * HostCandidate performed by a specific + * TurnCandidateHarvester. + * + * @param harvester the TurnCandidateHarvester which is performing + * the TURN harvesting + * @param hostCandidate the HostCandidate for which TURN + * Candidates are to be harvested + */ + public GoogleTurnCandidateHarvest( + GoogleTurnCandidateHarvester harvester, + HostCandidate hostCandidate) + { + super(harvester, hostCandidate); + } + + /** + * Creates new Candidates determined by a specific STUN + * Response. + * + * @param response the received STUN Response + * @see StunCandidateHarvest#createCandidates(Response) + */ + @Override + protected void createCandidates(Response response) + { + createRelayedCandidate(response); + } + + /** + * Creates a RelayedCandidate using the + * XOR-RELAYED-ADDRESS attribute in a specific STUN + * Response for the actual TransportAddress 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 Response which is supposed to contain + * the address we should use for the new candidate + */ + private void createRelayedCandidate(Response response) + { + Attribute attribute + = response.getAttribute(Attribute.MAPPED_ADDRESS); + + if(attribute != null) + { + TransportAddress relayedAddress + = ((MappedAddressAttribute) attribute).getAddress(); + GoogleRelayedCandidate relayedCandidate + = createRelayedCandidate( + relayedAddress, + getMappedAddress(response)); + + if (relayedCandidate != null) + { + /* + * The ICE connectivity checks will utilize STUN on the + * (application-purposed) socket of the RelayedCandidate and + * will not add it to the StunStack so we have to do it. + */ + harvester.getStunStack().addSocket( + relayedCandidate.getStunSocket(null)); + + addCandidate(relayedCandidate); + } + } + } + + /** + * Creates a new RelayedCandidate instance which is to represent a + * specific TransportAddress harvested through + * {@link #hostCandidate} and the TURN server associated with + * {@link #harvester}. + * + * @param transportAddress the TransportAddress to be represented + * by the new RelayedCandidate instance + * @param mappedAddress the mapped TransportAddress reported by the + * TURN server with the delivery of the relayed transportAddress to + * be represented by the new RelayedCandidate instance + * @return a new RelayedCandidate instance which represents the + * specified TransportAddress harvested through + * {@link #hostCandidate} and the TURN server associated with + * {@link #harvester} + */ + protected GoogleRelayedCandidate createRelayedCandidate( + TransportAddress transportAddress, + TransportAddress mappedAddress) + { + GoogleRelayedCandidate candidate = + new GoogleRelayedCandidate( + transportAddress, + this, + mappedAddress, + harvester.getShortTermCredentialUsername()); + + candidate.setUfrag(harvester.getShortTermCredentialUsername()); + return candidate; + } + + /** + * Creates a new Request which is to be sent to + * {@link TurnCandidateHarvester#stunServer} in order to start resolving + * {@link #hostCandidate}. + * + * @return a new Request which is to be sent to + * {@link TurnCandidateHarvester#stunServer} in order to start resolving + * {@link #hostCandidate} + * @see StunCandidateHarvest#createRequestToStartResolvingCandidate() + */ + @Override + protected Request createRequestToStartResolvingCandidate() + { + if (requestToStartResolvingCandidate == null) + { + requestToStartResolvingCandidate + = MessageFactory.createGoogleAllocateRequest( + harvester.getShortTermCredentialUsername()); + + return requestToStartResolvingCandidate; + } + else + return null; + } + + /** + * Adds the Attributes to a specific Request which support + * the STUN short-term credential mechanism if the mechanism in question is + * utilized by this StunCandidateHarvest (i.e. by the associated + * StunCandidateHarvester). + * + * @param request the Request to which to add the + * Attributes supporting the STUN short-term credential mechanism + * if the mechanism in question is utilized by this + * StunCandidateHarvest + * @return true if the STUN short-term credential mechanism is + * actually utilized by this StunCandidateHarvest for the specified + * request; otherwise, false + */ + @Override + protected boolean addShortTermCredentialAttributes(Request request) + { + return false; + } + + /** + * Completes the harvesting of Candidates for + * {@link #hostCandidate}. Notifies {@link #harvester} about the completion + * of the harvesting of Candidate for hostCandidate + * performed by this StunCandidateHarvest. + * + * @param request the Request sent by this + * StunCandidateHarvest with which the harvesting of + * Candidates for hostCandidate has completed + * @param response the Response received by this + * StunCandidateHarvest, if any, with which the harvesting of + * Candidates for hostCandidate has completed + * @return true if the harvesting of Candidates for + * hostCandidate performed by this StunCandidateHarvest + * has completed; otherwise, false + * @see StunCandidateHarvest#completedResolvingCandidate(Request, Response) + */ + @Override + protected boolean completedResolvingCandidate( + Request request, + Response response) + { + 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); + } + + /** + * Notifies this TurnCandidateHarvest that a specific + * RelayedCandidateDatagramSocket is closing and that this instance + * is to delete the associated TURN Allocation. + *+ * Note: The method is part of the internal API of + * RelayedCandidateDatagramSocket and TurnCandidateHarvest + * and is not intended for public use. + *
+ * + * @param relayedCandidateSocket the RelayedCandidateDatagramSocket + * which notifies this instance and which requests that the associated TURN + * Allocation be deleted + */ + public void close( + GoogleRelayedCandidateDatagramSocket relayedCandidateSocket) + { + /* + * FIXME As far as logic goes, it seems that it is possible to send a + * TURN Refresh, cancel the STUN keep-alive functionality here and only + * then receive the response to the TURN Refresh which will enable the + * STUN keep-alive functionality again. + */ + setSendKeepAliveMessageInterval( + SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED); + } + + /** + * Sends a specific Request on behalf of a specific + * RelayedCandidateDatagramSocket to the TURN server associated + * with this GoogleTurnCandidateHarvest. + * + * @param relayedCandidateDatagramSocket the + * RelayedCandidateDatagramSocket which sends the specified + * Request and which is to be notified of the result + * @param request the Request to be sent to the TURN server + * associated with this TurnCandidateHarvest + * @return an array of bytes which represents the ID of the + * transaction with which the specified Request has been sent to + * the TURN server + * @throws StunException if anything goes wrong while sending the specified + * Request + */ + public byte[] sendRequest( + RelayedCandidateDatagramSocket relayedCandidateDatagramSocket, + Request request) + throws StunException + { + TransactionID transactionID = TransactionID.createNewTransactionID(); + + transactionID.setApplicationData(relayedCandidateDatagramSocket); + transactionID = sendRequest(request, false, transactionID); + return (transactionID == null) ? null : transactionID.getBytes(); + } + + /** + * Notifies this StunCandidateHarvest that a specific + * Request has either received an error Response or has + * failed to receive any Response. + * + * @param response the error Response which has been received for + * request + * @param request the Request to which Response responds + * @param transactionID the TransactionID of response and + * request because response and request only have + * it as a byte array and TransactionID is required for + * the applicationData property value + * @return true if the error or failure condition has been + * processed and this instance can continue its execution (e.g. the + * resolution of the candidate) as if it was expected; otherwise, + * false + * @see StunCandidateHarvest#processErrorOrFailure(Response, Request, + * TransactionID) + */ + @Override + protected boolean processErrorOrFailure( + Response response, + Request request, + TransactionID transactionID) + { + logger.info("Google TURN processErrorOrFailure"); + /* + * TurnCandidateHarvest uses the applicationData of TransactionID to + * deliver the results of Requests sent by + * RelayedCandidateDatagramSocket back to it. + */ + Object applicationData = transactionID.getApplicationData(); + + if ((applicationData instanceof RelayedCandidateDatagramSocket) + && ((RelayedCandidateDatagramSocket) applicationData) + .processErrorOrFailure(response, request)) + return true; + + return super.processErrorOrFailure(response, request, transactionID); + } + + /** + * Handles a specific STUN success Response to a specific STUN + * Request. + * + * @param response the received STUN success Response which is to + * be handled + * @param request the STUN Request to which response + * responds + * @param transactionID the TransactionID of response and + * request because response and request only have + * it as a byte array and TransactionID is required for + * the applicationData property value + * @see StunCandidateHarvest#processSuccess(Response, Request, + * TransactionID) + */ + @Override + protected void processSuccess( + Response response, + Request request, + TransactionID transactionID) + { + super.processSuccess(response, request, transactionID); + + LifetimeAttribute lifetimeAttribute; + int lifetime /* minutes */ = -1; + + switch (response.getMessageType()) + { + case Message.ALLOCATE_RESPONSE: + // The default lifetime of an allocation is 10 minutes. + // The default lifetime of an allocation is 10 minutes. + lifetimeAttribute + = (LifetimeAttribute) response.getAttribute(Attribute.LIFETIME); + lifetime + = (lifetimeAttribute == null) + ? (10 * 60) + : lifetimeAttribute.getLifetime(); + logger.info("Successful Google TURN allocate"); + break; + default: + break; + } + + if (lifetime >= 0) + { + setSendKeepAliveMessageInterval( + /* milliseconds */ 1000L * lifetime); + } + + /* + * TurnCandidateHarvest uses the applicationData of TransactionID to + * deliver the results of Requests sent by + * RelayedCandidateDatagramSocket back to it. + */ + Object applicationData = transactionID.getApplicationData(); + + if (applicationData instanceof RelayedCandidateDatagramSocket) + { + ((RelayedCandidateDatagramSocket) applicationData) + .processSuccess(response, request); + } + } +} diff --git a/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvester.java b/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvester.java new file mode 100644 index 0000000..015a102 --- /dev/null +++ b/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvester.java @@ -0,0 +1,68 @@ +/* + * 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.ice.*; + +/** + * Implements a CandidateHarvester which gathers Google TURN dialect + * Candidates for a specified {@link Component}. + * + * @author Sebastien Vincent + */ +public class GoogleTurnCandidateHarvester + extends StunCandidateHarvester +{ + /** + * Initializes a new GoogleTurnCandidateHarvester instance which + * is to work with a specific GoogleTURN server. + * + * @param turnServer the TransportAddress of the TURN server the + * new instance is to work with + */ + public GoogleTurnCandidateHarvester(TransportAddress turnServer) + { + this(turnServer, null); + } + + /** + * Initializes a new GoogleTurnCandidateHarvester 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 TransportAddress 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 + * null if the use of the STUN short-term credential mechanism is + * not determined at the time of the construction of the new instance + */ + public GoogleTurnCandidateHarvester(TransportAddress turnServer, + String shortTermCredentialUsername) + { + super(turnServer, shortTermCredentialUsername); + } + + /** + * Creates a new GoogleTurnCandidateHarvest instance which is to + * perform TURN harvesting of a specific HostCandidate. + * + * @param hostCandidate the HostCandidate for which harvesting is + * to be performed by the new TurnCandidateHarvest instance + * @return a new GoogleTurnCandidateHarvest instance which is to + * perform TURN harvesting of the specified hostCandidate + * @see StunCandidateHarvester#createHarvest(HostCandidate) + */ + @Override + protected GoogleTurnCandidateHarvest createHarvest( + HostCandidate hostCandidate) + { + return new GoogleTurnCandidateHarvest(this, hostCandidate); + } +} diff --git a/src/org/ice4j/ice/harvest/HostCandidateHarvester.java b/src/org/ice4j/ice/harvest/HostCandidateHarvester.java index d6a2bc0..69db97c 100644 --- a/src/org/ice4j/ice/harvest/HostCandidateHarvester.java +++ b/src/org/ice4j/ice/harvest/HostCandidateHarvester.java @@ -200,7 +200,6 @@ public class HostCandidateHarvester int port = preferredPort; for (int i = 0; i < bindRetries; i++) { - try { DatagramSocket sock diff --git a/src/org/ice4j/ice/harvest/StunCandidateHarvest.java b/src/org/ice4j/ice/harvest/StunCandidateHarvest.java index 69c7802..bfe57b0 100644 --- a/src/org/ice4j/ice/harvest/StunCandidateHarvest.java +++ b/src/org/ice4j/ice/harvest/StunCandidateHarvest.java @@ -439,6 +439,17 @@ public class StunCandidateHarvest ((XorMappedAddressAttribute) attribute) .getAddress(response.getTransactionID()); } + + // old STUN servers (RFC3489) send MAPPED-ADDRESS address + attribute + = response.getAttribute(Attribute.MAPPED_ADDRESS); + + if(attribute instanceof MappedAddressAttribute) + { + return + ((MappedAddressAttribute) attribute) + .getAddress(); + } else return null; } @@ -991,7 +1002,7 @@ public class StunCandidateHarvest /** * Runs in {@link #sendKeepAliveMessageThread} and sends STUN * keep-alive Messages to the STUN server associated with the - * StunCandidateHarvester of this instance + * StunCandidateHarvester of this instance */ private void runInSendKeepAliveMessageThread() { @@ -1074,11 +1085,11 @@ public class StunCandidateHarvest * Well, if the currentThread is finishing and this instance is * still to send keep-alive messages, we'd better start another * Thread for the purpose to continue the work that the - * currentThread was supposed to carry out. + * currentThread was supposed to carry out. */ if ((sendKeepAliveMessageThread == null) && (sendKeepAliveMessageInterval - != SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED)) + != SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED)) createSendKeepAliveMessageThread(); } } diff --git a/src/org/ice4j/message/Indication.java b/src/org/ice4j/message/Indication.java index 257bf7c..f100e10 100644 --- a/src/org/ice4j/message/Indication.java +++ b/src/org/ice4j/message/Indication.java @@ -36,7 +36,11 @@ public class Indication public void setMessageType(char indicationType) throws IllegalArgumentException { - if(!isIndicationType(indicationType)) + /* old TURN DATA indication type is an indication despite + * 0x0115 & 0x0110 indicates STUN error response type + */ + if(!isIndicationType(indicationType) && + indicationType != OLD_DATA_INDICATION) throw new IllegalArgumentException( (int)(indicationType) + " - is not a valid indication type."); diff --git a/src/org/ice4j/message/Message.java b/src/org/ice4j/message/Message.java index 9a5f32b..f25ca2f 100644 --- a/src/org/ice4j/message/Message.java +++ b/src/org/ice4j/message/Message.java @@ -11,6 +11,7 @@ import java.util.logging.*; import org.ice4j.*; import org.ice4j.attribute.*; +import org.ice4j.ice.*; import org.ice4j.stack.*; /** @@ -34,60 +35,191 @@ public abstract class Message = Logger.getLogger(Message.class.getName()); /* general declaration */ + /** + * STUN request code. + */ public static final char STUN_REQUEST = 0x0000; + + /** + * STUN indication code. + */ public static final char STUN_INDICATION = 0x0010; + + /** + * STUN success response code. + */ public static final char STUN_SUCCESS_RESP = 0x0100; + + /** + * STUN error response code. + */ public static final char STUN_ERROR_RESP = 0x0110; /* STUN methods */ + /** + * STUN binding method. + */ public static final char STUN_METHOD_BINDING = 0x0001; + + /** + * STUN binding request code. + */ public static final char BINDING_REQUEST = (STUN_METHOD_BINDING | STUN_REQUEST); + + /** + * STUN binding success response code. + */ public static final char BINDING_SUCCESS_RESPONSE = (STUN_METHOD_BINDING | STUN_SUCCESS_RESP); + + /** + * STUN binding error response code. + */ public static final char BINDING_ERROR_RESPONSE = (STUN_METHOD_BINDING | STUN_ERROR_RESP); + + /** + * STUN shared secret request. + */ public static final char SHARED_SECRET_REQUEST = 0x0002; + + /** + * STUN shared secret response. + */ public static final char SHARED_SECRET_RESPONSE = 0x0102; + + /** + * STUN shared secret error response. + */ public static final char SHARED_SECRET_ERROR_RESPONSE = 0x0112; /* TURN methods */ + /** + * TURN allocate method code. + */ public static final char TURN_METHOD_ALLOCATE = 0x0003; + + /** + * TURN refresh method code. + */ public static final char TURN_METHOD_REFRESH = 0x0004; + + /** + * TURN send method code. + */ public static final char TURN_METHOD_SEND = 0x0006; + + /** + * TURN data method code. + */ public static final char TURN_METHOD_DATA = 0x0007; + + /** + * TURN CreatePermission method code. + */ public static final char TURN_METHOD_CREATEPERMISSION = 0x0008; + + /** + * TURN ChannelBind method code. + */ public static final char TURN_METHOD_CHANNELBIND = 0x0009; + /** + * TURN allocate request code. + */ public static final char ALLOCATE_REQUEST = (TURN_METHOD_ALLOCATE | STUN_REQUEST); + + /** + * TURN allocate response code. + */ public static final char ALLOCATE_RESPONSE = (TURN_METHOD_ALLOCATE | STUN_SUCCESS_RESP); + + /** + * TURN allocate error response code. + */ public static final char ALLOCATE_ERROR_RESPONSE = (TURN_METHOD_ALLOCATE | STUN_ERROR_RESP); + + /** + * TURN refresh request code. + */ public static final char REFRESH_REQUEST = (TURN_METHOD_REFRESH | STUN_REQUEST); + + /** + * TURN refresh response code. + */ public static final char REFRESH_RESPONSE = (TURN_METHOD_REFRESH | STUN_SUCCESS_RESP); + + /** + * TURN refresh error response code. + */ public static final char REFRESH_ERROR_RESPONSE = (TURN_METHOD_REFRESH | STUN_ERROR_RESP); + + /** + * TURN ChannelBind request code. + */ public static final char CHANNELBIND_REQUEST = (TURN_METHOD_CHANNELBIND | STUN_REQUEST); + + /** + * TURN ChannelBind response code. + */ public static final char CHANNELBIND_RESPONSE = (TURN_METHOD_CHANNELBIND | STUN_SUCCESS_RESP); + + /** + * TURN ChannelBind error response code. + */ public static final char CHANNELBIND_ERROR_RESPONSE = (TURN_METHOD_CHANNELBIND | STUN_ERROR_RESP); + + /** + * TURN CreatePermission request code. + */ public static final char CREATEPERMISSION_REQUEST = (TURN_METHOD_CREATEPERMISSION | STUN_REQUEST); + + /** + * TURN CreatePermission response code. + */ public static final char CREATEPERMISSION_RESPONSE = (TURN_METHOD_CREATEPERMISSION | STUN_SUCCESS_RESP); + + /** + * TURN CreatePermission error response code. + */ public static final char CREATEPERMISSION_ERROR_RESPONSE = (TURN_METHOD_CREATEPERMISSION | STUN_ERROR_RESP); + + /** + * TURN send indication code. + */ public static final char SEND_INDICATION = (TURN_METHOD_SEND | STUN_INDICATION); + + /** + * TURN data indication code. + */ public static final char DATA_INDICATION = (TURN_METHOD_DATA | STUN_INDICATION); + /* Old TURN method */ + /** + * TURN Send request. + */ + public static final char SEND_REQUEST = 0x0004; + + /** + * TURN Send request. + */ + public static final char OLD_DATA_INDICATION = 0x0115; + //Message fields /** * The length of Stun Message Headers in bytes @@ -117,6 +249,11 @@ public abstract class Message */ public static final byte TRANSACTION_ID_LENGTH = 12; + /** + * The length of the RFC3489 transaction id (in bytes). + */ + public static final byte RFC3489_TRANSACTION_ID_LENGTH = 16; + /** * The list of attributes contained by the message. We are using a Map * rather than a uni-dimensional list, in order to facilitate attribute @@ -167,8 +304,25 @@ public abstract class Message * */ public static final byte N_A = 0; + + /** + * C means it's conditional based on some other aspect of the message. + */ public static final byte C = 1; + + /** + * O means the parameter is optional. + * + * @see Message#N_A + */ public static final byte O = 2; + + /** + * M indicates that inclusion of the attribute in the message is + * mandatory. + * + * @see Message#N_A + */ public static final byte M = 3; //Message indices @@ -227,6 +381,9 @@ public abstract class Message protected static final byte ICE_CONTROLLED_PRESENTITY_INDEX = 30; protected static final byte USE_CANDIDATE_PRESENTITY_INDEX = 31; + /* Old TURN attributes */ + protected static final byte DESTINATION_ADDRESS_PRESENTITY_INDEX = 29; + protected final static byte attributePresentities[][] = new byte[][]{ // Binding Shared Shared Shared Alloc Alloc Rfrsh Rfrsh ChnlBnd ChnlBnd Send Data // Binding Binding Error Secret Secret Secret Req. Resp. Req. Resp. Req. Resp. Indic. Indic. @@ -236,7 +393,7 @@ public abstract class Message /*MAPPED-ADDRESS*/ { N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, /*RESPONSE-ADDRESS*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, /*CHANGE-REQUEST*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, - /*SOURCE-ADDRESS*/ { N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, + /*SOURCE-ADDRESS*/ { N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, M}, /*CHANGED-ADDRESS*/ { N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, /*USERNAME*/ { O, N_A, N_A, N_A, M, N_A, O, N_A, O, N_A, O, N_A, N_A, N_A}, /*PASSWORD*/ { N_A, N_A, N_A, N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, @@ -244,7 +401,7 @@ public abstract class Message /*ERROR-CODE*/ { N_A, N_A, M, N_A, N_A, M, N_A, M, N_A, M, N_A, M, N_A, N_A}, /*UNKNOWN-ATTRIBUTES*/{ N_A, N_A, C, N_A, N_A, C, N_A, C, N_A, C, N_A, C, N_A, N_A}, /*REFLECTED-FROM*/ { N_A, C, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, - /*XOR-MAPPED-ADDRESS*/{ N_A, M, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A, N_A, N_A, N_A}, + /*XOR-MAPPED-ADDRESS*/{ N_A, C, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A, N_A, N_A, N_A}, /*XOR-ONLY*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, /*SOFTWARE*/ { N_A, O, O, N_A, O, O, O, O, O, O, O, O, O, N_A}, /*UNKNOWN_OPTIONAL*/ { O, O, O, O, O, O, O, O, O, O, O, O, N_A, N_A}, @@ -253,9 +410,9 @@ public abstract class Message /*NONCE*/ { O, N_A, N_A, N_A, M, N_A, O, O, O, O, O, O, N_A, N_A}, /*FINGERPRINT*/ { O, O, O, O, O, O, O, O, O, O, O, O, N_A, N_A}, /*CHANNEL-NUMBER*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A}, - /*LIFETIME*/ { N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, M, N_A, N_A, N_A, N_A, N_A}, + /*LIFETIME*/ { N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, O, N_A, N_A, N_A, N_A, N_A}, /*XOR-PEER-ADDRESS*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, M, M}, - /*DATA*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, O, M}, + /*DATA*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, N_A, N_A, O, M}, /*XOR-RELAYED-ADDRESS*/{N_A, N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A, N_A, N_A, N_A}, /*EVEN-PORT*/ { N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, /*REQUESTED-TRANSPORT*/{N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, @@ -265,6 +422,7 @@ public abstract class Message /*ICE-CONTROLLING*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, /*ICE-CONTROLLED*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, /*USE-CANDIDATE*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, + /*DESTINATION-ADDRESS*/{N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, N_A, N_A, M, N_A}, }; /** @@ -377,8 +535,6 @@ public abstract class Message return attributes.size(); } - - /** * Sets this message's type to be messageType. Method is package access * as it should not permit changing the type of message once it has been @@ -414,13 +570,16 @@ public abstract class Message throws StunException { if(tranID == null - || tranID.length != TRANSACTION_ID_LENGTH) + || (tranID.length != TRANSACTION_ID_LENGTH && + tranID.length != RFC3489_TRANSACTION_ID_LENGTH)) throw new StunException(StunException.ILLEGAL_ARGUMENT, - "Invalid transaction id"); + "Invalid transaction id length"); - this.transactionID = new byte[TRANSACTION_ID_LENGTH]; + int tranIDLength = tranID.length; + + this.transactionID = new byte[tranIDLength]; System.arraycopy(tranID, 0, - this.transactionID, 0, TRANSACTION_ID_LENGTH); + this.transactionID, 0, tranIDLength); } /** @@ -635,6 +794,18 @@ public abstract class Message //make sure we have everything necessary to encode a proper message validateAttributePresentity(); + if(stunStack.getCompatibilityMode() == CompatibilityMode.GTALK) + { + /* Google Talk will return error response if it sees unknown + * attributes (typically attributes introduced in RFC5349 and + */ + if(getAttribute(Attribute.SOFTWARE) != null) + removeAttribute(Attribute.SOFTWARE); + + if(getAttribute(Attribute.FINGERPRINT) != null) + removeAttribute(Attribute.FINGERPRINT); + } + final char dataLength = getDataLength(); byte binMsg[] = new byte[HEADER_LENGTH + dataLength]; int offset = 0; @@ -648,11 +819,24 @@ public abstract class Message offset += 2; - System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4); - offset+=4; - System.arraycopy(getTransactionID(), 0, binMsg, offset, - TRANSACTION_ID_LENGTH); - offset+=TRANSACTION_ID_LENGTH; + byte tranID[] = getTransactionID(); + + if(tranID.length == 12) + { + System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4); + offset += 4; + System.arraycopy(tranID, 0, binMsg, offset, + TRANSACTION_ID_LENGTH); + offset += TRANSACTION_ID_LENGTH; + } + else + { + /* RFC3489 behavior */ + System.arraycopy(tranID, 0, binMsg, offset, + RFC3489_TRANSACTION_ID_LENGTH); + offset += RFC3489_TRANSACTION_ID_LENGTH; + + } Iterator+ * If there is a security manager, its checkConnect method is first + * called with the host address and -1 as its arguments to see if + * the operation is allowed. + *
+ * + * @return the local address to which the socket is bound, or an + * InetAddress representing any local address if either the socket + * is not bound, or the security manager checkConnect method does + * not allow the operation + * @see #getLocalSocketAddress() + * @see DatagramSocket#getLocalAddress() + */ + @Override + public InetAddress getLocalAddress() + { + return getLocalSocketAddress().getAddress(); + } + + /** + * Returns the port number on the local host to which this socket is bound. + * GoogleRelayedCandidateDatagramSocket returns the port + * of its localSocketAddress. + * + * @return the port number on the local host to which this socket is bound + * @see #getLocalSocketAddress() + * @see DatagramSocket#getLocalPort() + */ + @Override + public int getLocalPort() + { + return getLocalSocketAddress().getPort(); + } + + /** + * Returns the address of the endpoint this socket is bound to, or + * null if it is not bound yet. Since + * GoogleRelayedCandidateDatagramSocket represents an + * application-purposed DatagramSocket relaying data to and from a + * TURN server, the localSocketAddress is the + * transportAddress of the respective RelayedCandidate. + * + * @return a SocketAddress representing the local endpoint of this + * socket, or null if it is not bound yet + * @see DatagramSocket#getLocalSocketAddress() + */ + @Override + public InetSocketAddress getLocalSocketAddress() + { + return getRelayedCandidate().getTransportAddress(); + } + + /** + * Gets the RelayedCandidate which uses this instance as the value + * of its socket property. + * + * @return the RelayedCandidate which uses this instance as the + * value of its socket property + */ + public final GoogleRelayedCandidate getRelayedCandidate() + { + return relayedCandidate; + } + + /** + * Notifies this MessageEventHandler that a specific STUN message + * has been received, parsed and is ready for delivery. + * GoogleRelayedCandidateDatagramSocket handles STUN indications sent + * from the associated TURN server and received at the associated local + * TransportAddress. + * + * @param e a StunMessageEvent which encapsulates the received STUN + * message + */ + public void handleMessageEvent(StunMessageEvent e) + { + Message message = e.getMessage(); + char messageType = message.getMessageType(); + + if (messageType != Message.OLD_DATA_INDICATION) + return; + + if (!turnCandidateHarvest.hostCandidate.getTransportAddress().equals( + e.getLocalAddress())) + return; + + // Is it from our TURN server? + if (!turnCandidateHarvest.harvester.stunServer.equals( + e.getRemoteAddress())) + return; + + logger.finest("handle old DATA Indication"); + + /* as REMOTE-ADDRESS and XOR-PEER-ADDRESS has the same attribute type + * we cast it to XorPeerAddressAttribute but we do not apply XOR to get + * the address + */ + XorPeerAddressAttribute peerAddressAttribute + = (XorPeerAddressAttribute) + message.getAttribute(Attribute.REMOTE_ADDRESS); + + if (peerAddressAttribute == null) + { + logger.info("peerAddressAttribute is null"); + return; + } + + DataAttribute dataAttribute + = (DataAttribute) message.getAttribute(Attribute.DATA); + + if (dataAttribute == null) + { + logger.info("data is null"); + return; + } + + TransportAddress peerAddress + = peerAddressAttribute.getAddress(); + if (peerAddress == null) + return; + + byte[] data = dataAttribute.getData(); + + if (data == null) + return; + + DatagramPacket packetToReceive; + + try + { + packetToReceive + = new DatagramPacket(data, 0, data.length, peerAddress); + } + catch (SocketException sex) + { + packetToReceive = null; + } + + if (packetToReceive != null) + { + synchronized (packetsToReceive) + { + packetsToReceive.add(packetToReceive); + packetsToReceive.notifyAll(); + } + } + } + + /** + * Notifies this GoogleRelayedCandidateDatagramSocket that a + * specific Request it has sent has either failed or received a + * STUN error Response. + * + * @param response the Response which responds to request + * @param request the Request sent by this instance to which + * response responds + * @return true if the failure or error condition has been handled + * and the caller should assume this instance has recovered from it; + * otherwise, false + */ + public boolean processErrorOrFailure(Response response, Request request) + { + return false; + } + + /** + * Notifies this GoogleRelayedCandidateDatagramSocket that a + * specific Request it has sent has received a STUN success + * Response. + * + * @param response the Response which responds to request + * @param request the Request sent by this instance to which + * response responds + */ + public void processSuccess(Response response, Request request) + { + } + + /** + * Dispatch the specified response. + * + * @param response the response to dispatch. + */ + public void processResponse(StunResponseEvent response) + { + + } + + /** + * Notifies this 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. + * + * @param event the StunTimeoutEvent containing a reference to the + * transaction that has just failed. + */ + public void processTimeout(StunTimeoutEvent event) + { + } + + /** + * Receives a datagram packet from this socket. When this method returns, + * the DatagramPacket'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 DatagramPacket 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 + { + synchronized (packetsToReceive) + { + while (true) + { + /* + * According to the javadoc of DatagramSocket#close(), any + * thread currently blocked in #receive(DatagramPacket) upon + * this socket will throw a SocketException. + */ + if (closed) + { + throw + new SocketException( + GoogleRelayedCandidateDatagramSocket.class + .getSimpleName() + + " has been closed."); + } + else if (packetsToReceive.isEmpty()) + { + try + { + packetsToReceive.wait(); + } + catch (InterruptedException iex) + { + } + continue; + } + else + { + DatagramPacket packetToReceive = packetsToReceive.remove(0); + + MultiplexingDatagramSocket.copy(packetToReceive, p); + packetsToReceive.notifyAll(); + break; + } + } + } + } + + /** + * Sends a datagram packet from this socket. The DatagramPacket + * 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 DatagramPacket to be sent + * @throws IOException if an I/O error occurs + * @see DatagramSocket#send(DatagramPacket) + */ + @Override + public void send(DatagramPacket p) + throws IOException + { + synchronized (packetsToSend) + { + if (closed) + { + throw + new IOException( + GoogleRelayedCandidateDatagramSocket.class. + getSimpleName() + " has been closed."); + } + else + { + packetsToSend.add(MultiplexingDatagramSocket.clone(p)); + + if (sendThread == null) + createSendThread(); + else + packetsToSend.notifyAll(); + } + } + } + + /** + * Creates {@link #sendThread} which is to send {@link #packetsToSend} to + * the associated TURN server. + */ + private void createSendThread() + { + sendThread + = new Thread() + { + @Override + public void run() + { + try + { + runInSendThread(); + } + finally + { + /* + * If sendThread is dying and there are packetsToSend, + * then spawn a new sendThread. + */ + synchronized (packetsToSend) + { + if (sendThread == Thread.currentThread()) + sendThread = null; + if ((sendThread == null) + && !closed + && !packetsToSend.isEmpty()) + createSendThread(); + } + } + } + }; + sendThread.start(); + } + + /** + * Runs in {@link #sendThread} to send {@link #packetsToSend} to the + * associated TURN server. + */ + private void runInSendThread() + { + synchronized (packetsToSend) + { + while (!closed) + { + if (packetsToSend.isEmpty()) + { + try + { + packetsToSend.wait(); + } + catch (InterruptedException iex) + { + } + continue; + } + + int packetToSendCount = packetsToSend.size(); + + for (int packetToSendIndex = 0; + packetToSendIndex < packetToSendCount; + packetToSendIndex++) + { + DatagramPacket packetToSend = packetsToSend.remove(0); + TransportAddress peerAddress + = new TransportAddress( + packetToSend.getAddress(), + packetToSend.getPort(), + Transport.UDP); + byte[] pData = packetToSend.getData(); + int pOffset = packetToSend.getOffset(); + int pLength = packetToSend.getLength(); + byte[] data; + + if ((pOffset == 0) && (pLength == pData.length)) + data = pData; + else + { + data = new byte[pLength]; + System.arraycopy(pData, pOffset, data, 0, pLength); + } + + byte[] transactionID + = TransactionID.createNewTransactionID().getBytes(); + Request sendRequest + = MessageFactory.createSendRequest(username, + peerAddress, + data); + + try + { + sendRequest.setTransactionID(transactionID); + turnCandidateHarvest.harvester.getStunStack(). + sendRequest(sendRequest, + turnCandidateHarvest.harvester.stunServer, + turnCandidateHarvest.hostCandidate. + getTransportAddress(), + this); + } + catch(Exception e) + { + logger.fine("Failed to send TURN Send request: " + e); + } + } + + /* + * If no packetToSend has been sent by the current iteration, + * then we must be waiting for some condition to change in order + * to be able to send. + */ + if (packetsToSend.size() == packetToSendCount) + { + try + { + packetsToSend.wait(); + } + catch (InterruptedException iex) + { + } + } + } + } + } +} \ No newline at end of file diff --git a/src/org/ice4j/socket/StunDatagramPacketFilter.java b/src/org/ice4j/socket/StunDatagramPacketFilter.java index d218d05..2ffdfd5 100644 --- a/src/org/ice4j/socket/StunDatagramPacketFilter.java +++ b/src/org/ice4j/socket/StunDatagramPacketFilter.java @@ -130,4 +130,28 @@ public class StunDatagramPacketFilter return false; } } + + /** + * Indicates whether some other DatagramPacketFilter is "equal to" this one. + * + * @param obj the reference object with which to compare. + * @returntrue if this StunDatagramPacketFilter is
+ * equal to the obj argument; false otherwise.
+ *
+ * @throws java.lang.NullPointerException if obj is null;
+ */
+ @Override
+ public boolean equals(Object obj)
+ throws NullPointerException
+ {
+ if(obj == this)
+ return true;
+
+ if(obj.getClass().equals(getClass()))
+ {
+ return true;
+ }
+
+ return false;
+ }
}
diff --git a/src/org/ice4j/socket/TurnDatagramPacketFilter.java b/src/org/ice4j/socket/TurnDatagramPacketFilter.java
index 122c3ec..737b8ff 100644
--- a/src/org/ice4j/socket/TurnDatagramPacketFilter.java
+++ b/src/org/ice4j/socket/TurnDatagramPacketFilter.java
@@ -105,6 +105,7 @@ public class TurnDatagramPacketFilter
case Message.TURN_METHOD_DATA:
case Message.TURN_METHOD_REFRESH:
case Message.TURN_METHOD_SEND:
+ case 0x0005: /* old TURN DATA indication */
return true;
default:
return false;
diff --git a/src/org/ice4j/stack/Connector.java b/src/org/ice4j/stack/Connector.java
index 2cdff90..8f0029d 100644
--- a/src/org/ice4j/stack/Connector.java
+++ b/src/org/ice4j/stack/Connector.java
@@ -252,7 +252,7 @@ class Connector
sock.send(datagramPacket);
- // no exception packet is successfully sent, log it
+ // no exception packet is successfully sent, log it
if(StunStack.isPacketLoggerEnabled())
{
StunStack.getPacketLogger().logPacket(
diff --git a/src/org/ice4j/stack/EventDispatcher.java b/src/org/ice4j/stack/EventDispatcher.java
index e8303fe..7337a9f 100644
--- a/src/org/ice4j/stack/EventDispatcher.java
+++ b/src/org/ice4j/stack/EventDispatcher.java
@@ -49,7 +49,7 @@ public class EventDispatcher
/**
* Registers a specific MessageEventHandler for notifications about
* STUN indications received at a specific local TransportAddress.
- *
+ *
* @param localAddr the local TransportAddress STUN indications
* received at which are to be reported to the specified
* indicationListener
@@ -66,6 +66,26 @@ public class EventDispatcher
new IndicationEventHandler(indicationListener));
}
+ /**
+ * Registers a specific MessageEventHandler for notifications about
+ * old indications received at a specific local TransportAddress.
+ *
+ * @param localAddr the local TransportAddress STUN indications
+ * received at which are to be reported to the specified
+ * indicationListener
+ * @param indicationListener the MessageEventHandler which is to be
+ * registered for notifications about old indications received at the
+ * specified local TransportAddress
+ */
+ public void addOldIndicationListener(
+ TransportAddress localAddr,
+ MessageEventHandler indicationListener)
+ {
+ addMessageListener(
+ localAddr,
+ new OldIndicationEventHandler(indicationListener));
+ }
+
/**
* Registers a specific MessageTypeEventHandler for notifications
* about received STUN messages.
@@ -325,13 +345,52 @@ public class EventDispatcher
}
}
+ /**
+ * Implements MessageEventHandler for a
+ * MessageEventHandler which handles old DATA indications (0x0115).
+ *
+ * @author Lubomir Marinov
+ * @author Sebastien Vincent
+ */
+ private static class OldIndicationEventHandler
+ extends MessageTypeEventHandler