From 8928f9daa663b4a1634247e0de5ee2514361cf38 Mon Sep 17 00:00:00 2001 From: "lubomir.marinov" Date: Fri, 9 Jul 2010 15:41:07 +0000 Subject: [PATCH] Implements relaying data through a TURN server for RelayedCandidate. --- src/org/ice4j/ice/Component.java | 127 ++- src/org/ice4j/ice/LocalCandidate.java | 79 +- src/org/ice4j/ice/RelayedCandidate.java | 61 +- .../ice/harvest/StunCandidateHarvest.java | 438 +++++++++- .../ice/harvest/StunCandidateHarvester.java | 2 +- .../ice/harvest/TurnCandidateHarvest.java | 272 +++++++ src/org/ice4j/message/Message.java | 53 +- src/org/ice4j/message/MessageFactory.java | 66 ++ .../socket/DelegatingDatagramSocket.java | 712 ++++++++++++++++ .../socket/MultiplexedDatagramSocket.java | 487 +---------- .../socket/MultiplexingDatagramSocket.java | 105 ++- .../RelayedCandidateDatagramSocket.java | 770 +++++++++++++++++- .../ice4j/socket/SafeCloseDatagramSocket.java | 38 +- .../socket/TurnDatagramPacketFilter.java | 1 + src/org/ice4j/stack/Connector.java | 87 +- src/org/ice4j/stack/EventDispatcher.java | 358 ++++++-- src/org/ice4j/stack/RawMessage.java | 14 +- src/org/ice4j/stack/StunStack.java | 93 +++ test/test/Ice.java | 69 +- 19 files changed, 3057 insertions(+), 775 deletions(-) create mode 100644 src/org/ice4j/socket/DelegatingDatagramSocket.java diff --git a/src/org/ice4j/ice/Component.java b/src/org/ice4j/ice/Component.java index 78b078c..63295c5 100644 --- a/src/org/ice4j/ice/Component.java +++ b/src/org/ice4j/ice/Component.java @@ -67,8 +67,8 @@ public class Component /** * The list locally gathered candidates for this media stream. */ - private List localCandidates - = new LinkedList(); + private final List localCandidates + = new LinkedList(); /** * The list of candidates that the peer agent sent for this stream. @@ -79,8 +79,8 @@ public class Component * A Comparator that we use for sorting Candidates by * their priority. */ - private CandidatePrioritizer candidatePrioritizer - = new CandidatePrioritizer(); + private final CandidatePrioritizer candidatePrioritizer + = new CandidatePrioritizer(); /** * The default Candidate for this component or in other words, the @@ -368,9 +368,7 @@ public class Component //first compute the actual priorities for (Candidate cand : candidates) - { cand.computePriority(); - } //sort Arrays.sort(candidates, candidatePrioritizer); @@ -452,31 +450,38 @@ public class Component */ protected void eliminateRedundantCandidates() { - List candidatesCopy = getLocalCandidates(); - - for (Candidate cand : candidatesCopy) + /* + * Find and remove all candidates that have the same address and base as + * cand and a lower priority. The algorithm implemented bellow does rely + * on localCandidates being ordered in decreasing order (as said in its + * javadoc that the eliminateRedundantCandidates method is called only + * after prioritizeCandidates. + */ + synchronized (localCandidates) { - //find and remove all candidates that have the same address and - //base as cand and a lower priority. - synchronized(localCandidates) + for (int i = 0; i < localCandidates.size(); i++) { - Iterator localCandsIter - = localCandidates.iterator(); + LocalCandidate cand = localCandidates.get(i); - while (localCandsIter.hasNext()) + for (int j = i + 1; j < localCandidates.size();) { - Candidate cand2 = localCandsIter.next(); + LocalCandidate cand2 = localCandidates.get(j); - if( cand != cand2 - && cand.getTransportAddress() - .equals(cand2.getTransportAddress()) - && cand.getBase().equals(cand2.getBase()) - && cand.getPriority() >= cand2.getPriority() ) + if ((cand != cand2) + && cand.getTransportAddress().equals( + cand2.getTransportAddress()) + && cand.getBase().equals(cand2.getBase()) + && (cand.getPriority() >= cand2.getPriority())) { - localCandsIter.remove(); - if(logger.isLoggable(Level.FINEST)) - logger.finest("eliminating redundant cand: "+ cand2); + localCandidates.remove(j); + if(logger.isLoggable(Level.FINEST)) + { + logger.finest( + "eliminating redundant cand: "+ cand2); + } } + else + j++; } } } @@ -572,12 +577,76 @@ public class Component { synchronized (localCandidates) { - Iterator cndIter = localCandidates.iterator(); - while( cndIter.hasNext()) + /* + * Since the sockets of the non-HostCandidate LocalCandidates may + * depend on the socket of the HostCandidate for which they have + * been harvested, order the freeing. + */ + CandidateType[] candidateTypes + = new CandidateType[] + { + CandidateType.RELAYED_CANDIDATE, + CandidateType.PEER_REFLEXIVE_CANDIDATE, + CandidateType.SERVER_REFLEXIVE_CANDIDATE + }; + + for (CandidateType candidateType : candidateTypes) { - LocalCandidate candidate = cndIter.next(); - candidate.free(); - cndIter.remove(); + Iterator localCandidateIter + = localCandidates.iterator(); + + while (localCandidateIter.hasNext()) + { + LocalCandidate localCandidate = localCandidateIter.next(); + + if (candidateType.equals(localCandidate.getType())) + { + free(localCandidate); + localCandidateIter.remove(); + } + } + } + + // Free whatever's left. + Iterator localCandidateIter + = localCandidates.iterator(); + + while (localCandidateIter.hasNext()) + { + LocalCandidate localCandidate = localCandidateIter.next(); + + free(localCandidate); + localCandidateIter.remove(); + } + } + } + + /** + * Frees a specific LocalCandidate and swallows any + * Throwable it throws while freeing itself in order to prevent its + * failure to affect the rest of the execution. + * + * @param localCandidate the LocalCandidate to be freed + */ + private void free(LocalCandidate localCandidate) + { + try + { + localCandidate.free(); + } + catch (Throwable t) + { + /* + * Don't let the failing of a single LocalCandidate to free itself + * to fail the freeing of the other LocalCandidates. + */ + if (t instanceof ThreadDeath) + throw (ThreadDeath) t; + if (logger.isLoggable(Level.INFO)) + { + logger.log( + Level.INFO, + "Failed to free LocalCandidate: " + localCandidate); } } } diff --git a/src/org/ice4j/ice/LocalCandidate.java b/src/org/ice4j/ice/LocalCandidate.java index ea90cba..511a548 100644 --- a/src/org/ice4j/ice/LocalCandidate.java +++ b/src/org/ice4j/ice/LocalCandidate.java @@ -48,31 +48,6 @@ public abstract class LocalCandidate super(transportAddress, parentComponent, type); } - /** - * Gets the actual/host DatagramSocket which implements the - * DatagramSockets exposed by this LocalCandidate. The - * default implementation is supposed to be good enough for the general case - * and does not try to be universal - it returns the hostSocket of - * the base of this LocalCandidate if the base is - * different than this or the socket of this - * LocalCandidate if it equals its base. The row reasoning - * for the implementation is that if any Candidate knows about the - * actual/host DatagramSocket, this LocalCandidate would - * be based on it rather be related to it in any other way. - * - * @return the actual/host DatagramSocket which implements the - * DatagramSockets exposed by this LocalCandidate - */ - protected DatagramSocket getHostSocket() - { - LocalCandidate base = getBase(); - - return - ((base == this) || (base == null)) - ? getSocket() - : base.getHostSocket(); - } - /** * Gets the DatagramSocket associated with this Candidate. * @@ -96,14 +71,14 @@ public abstract class LocalCandidate */ public DatagramSocket getStunSocket(TransportAddress serverAddress) { - DatagramSocket hostSocket = getHostSocket(); + DatagramSocket hostSocket = getSocket(); DatagramSocket stunSocket = null; - Throwable exception = null; if (hostSocket instanceof MultiplexingDatagramSocket) { DatagramPacketFilter stunDatagramPacketFilter = createStunDatagramPacketFilter(serverAddress); + Throwable exception = null; try { @@ -119,11 +94,24 @@ public abstract class LocalCandidate sex); exception = sex; } + if (stunSocket == null) + { + throw + new IllegalStateException( + "Failed to acquire DatagramSocket" + + " specific to STUN communication", + exception); + } } - if (stunSocket == null) - throw new IllegalArgumentException("hostCand", exception); else - return stunSocket; + { + throw + new IllegalStateException( + "The socket of " + + getClass().getSimpleName() + + " must be a MultiplexingDatagramSocket instance"); + } + return stunSocket; } /** @@ -145,22 +133,33 @@ public abstract class LocalCandidate /** * Frees resources allocated by this candidate such as its - * DatagramSocket for example. + * DatagramSocket, for example. The socket of this + * LocalCandidate is closed only if it is not the socket + * of the base of this LocalCandidate. */ protected void free() { - //remove our socket from the stack. - StunStack.getInstance().removeSocket(getTransportAddress()); - - // Close the socket associated with this Candidate. + // Close the socket associated with this LocalCandidate. DatagramSocket socket = getSocket(); - /* - * Allow this LocalCandiate implementation to not create a socket if it - * still hasn't created one. - */ if (socket != null) - socket.close(); + { + LocalCandidate base = getBase(); + + if ((base == null) + || (base == this) + || (base.getSocket() != socket)) + { + //remove our socket from the stack. + StunStack.getInstance().removeSocket(getTransportAddress()); + + /* + * Allow this LocalCandiate implementation to not create a + * socket if it still hasn't created one. + */ + socket.close(); + } + } } /** diff --git a/src/org/ice4j/ice/RelayedCandidate.java b/src/org/ice4j/ice/RelayedCandidate.java index 9b63eab..355ea92 100644 --- a/src/org/ice4j/ice/RelayedCandidate.java +++ b/src/org/ice4j/ice/RelayedCandidate.java @@ -25,12 +25,18 @@ import org.ice4j.socket.*; public class RelayedCandidate extends LocalCandidate { + /** - * The RelayedCandidateDatagramSocket which represents the - * application-purposed DatagramSocket associated with this + * The RelayedCandidateDatagramSocket of this + * RelayedCandidate. + */ + private RelayedCandidateDatagramSocket relayedCandidateDatagramSocket; + + /** + * The application-purposed DatagramSocket associated with this * Candidate. */ - private RelayedCandidateDatagramSocket socket; + private DatagramSocket socket; /** * The TurnCandidateHarvest which has harvested this @@ -71,29 +77,40 @@ public class RelayedCandidate } /** - * Gets the actual/host DatagramSocket which implements the - * DatagramSockets exposed by this LocalCandidate. The - * default implementation is supposed to be good enough for the general case - * and does not try to be universal - it returns the hostSocket of - * the base of this LocalCandidate if the base is - * different than this or the socket of this - * LocalCandidate if it equals its base. The row reasoning - * for the implementation is that if any Candidate knows about the - * actual/host DatagramSocket, this LocalCandidate would - * be based on it rather be related to it in any other way. + * Gets the RelayedCandidateDatagramSocket of this + * RelayedCandidate. + *

+ * Note: The method is part of the internal API of + * RelayedCandidate and TurnCandidateHarvest and is not + * intended for public use. + *

* - * @return the actual/host DatagramSocket which implements the - * DatagramSockets exposed by this LocalCandidate - * @see LocalCandidate#getHostSocket() + * @return the RelayedCandidateDatagramSocket of this + * RelayedCandidate */ - @Override - protected DatagramSocket getHostSocket() + public synchronized RelayedCandidateDatagramSocket + getRelayedCandidateDatagramSocket() { - return turnCandidateHarvest.hostCandidate.getSocket(); + if (relayedCandidateDatagramSocket == null) + { + try + { + relayedCandidateDatagramSocket + = new RelayedCandidateDatagramSocket( + this, + turnCandidateHarvest); + } + catch (SocketException sex) + { + throw new UndeclaredThrowableException(sex); + } + } + return relayedCandidateDatagramSocket; } /** - * Gets the DatagramSocket associated with this Candidate. + * Gets the application-purposed DatagramSocket associated with + * this Candidate. * * @return the DatagramSocket associated with this * Candidate @@ -105,7 +122,9 @@ public class RelayedCandidate { try { - socket = new RelayedCandidateDatagramSocket(); + socket + = new MultiplexingDatagramSocket( + getRelayedCandidateDatagramSocket()); } catch (SocketException sex) { diff --git a/src/org/ice4j/ice/harvest/StunCandidateHarvest.java b/src/org/ice4j/ice/harvest/StunCandidateHarvest.java index 9e7673a..f16b5e4 100644 --- a/src/org/ice4j/ice/harvest/StunCandidateHarvest.java +++ b/src/org/ice4j/ice/harvest/StunCandidateHarvest.java @@ -37,16 +37,28 @@ public class StunCandidateHarvest = Logger.getLogger(StunCandidateHarvest.class.getName()); /** - * The constant which defines an empty array with Candidate element - * type. Explicitly defined in order to reduce unnecessary allocations. + * The constant which defines an empty array with LocalCandidate + * element type. Explicitly defined in order to reduce unnecessary + * allocations. */ - private static final Candidate[] NO_CANDIDATES = new Candidate[0]; + private static final LocalCandidate[] NO_CANDIDATES = new LocalCandidate[0]; + + /** + * The value of the sendKeepAliveMessage property of + * StunCandidateHarvest which specifies that no sending of STUN + * keep-alive messages is to performed for the purposes of keeping the + * Candidates harvested by the StunCandidateHarvester in + * question alive. + */ + protected static final long SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED + = 0; /** * The list of Candidates harvested for {@link #hostCandidate} by * this harvest. */ - private final List candidates = new LinkedList(); + private final List candidates + = new LinkedList(); /** * The indicator which determines whether this StunCandidateHarvest @@ -84,6 +96,38 @@ public class StunCandidateHarvest private final Map requests = new HashMap(); + /** + * The interval in milliseconds at which a new STUN keep-alive message is to + * be sent to the STUN server associated with the + * StunCandidateHarvester of this instance in order to keep one of + * the Candidates harvested by this instance alive. + */ + private long sendKeepAliveMessageInterval + = SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED; + + /** + * The Object used to synchronize access to the members related to + * the sending of STUN keep-alive messages to the STUN server associated + * with the StunCandidateHarvester of this instance. + */ + private final Object sendKeepAliveMessageSyncRoot = new Object(); + + /** + * The Thread which sends the STUN keep-alive messages to the STUN + * server associated with the StunCandidateHarvester of this + * instance in order to keep the Candidates harvested by this + * instance alive. + */ + private Thread sendKeepAliveMessageThread; + + /** + * The time stamp of the last call to {@link #sendKeepAliveMessage()} which + * completed without throwing an exception (note: it doesn't mean that the + * keep-alive message was a STUN Request and it received a success + * STUN Response). + */ + private long sendKeepAliveMessageTimeStamp = -1; + /** * Initializes a new StunCandidateHarvest which is to represent the * harvesting of STUN Candidates for a specific @@ -206,6 +250,38 @@ public class StunCandidateHarvest createServerReflexiveCandidate(response); } + /** + * Creates a new STUN Message to be sent to the STUN server + * associated with the StunCandidateHarvester of this instance in + * order to keep a specific LocalCandidate (harvested by this + * instance) alive. + * + * @param candidate the LocalCandidate (harvested by this instance) + * to create a new keep-alive STUN message for + * @return a new keep-alive STUN Message for the specified + * candidate or null if no keep-alive sending is to occur + * @throws StunException if anything goes wrong while creating the new + * keep-alive STUN Message for the specified candidate + * or the candidate is of an unsupported CandidateType + */ + protected Message createKeepAliveMessage(LocalCandidate candidate) + throws StunException + { + /* + * We'll not be keeping a STUN Binding alive for now. If we decide to in + * the future, we'll have to create a Binding Indication and add support + * for sending it. + */ + if (CandidateType.SERVER_REFLEXIVE_CANDIDATE.equals( + candidate.getType())) + return null; + else + { + throw + new StunException(StunException.ILLEGAL_ARGUMENT, "candidate"); + } + } + /** * Creates a new Request instance which is to be sent by this * StunCandidateHarvest in order to retry a specific @@ -246,6 +322,29 @@ public class StunCandidateHarvest return MessageFactory.createBindingRequest(); } + /** + * Creates and starts the {@link #sendKeepAliveMessageThread} which is to + * send STUN keep-alive Messages to the STUN server associated with + * the StunCandidateHarvester of this instance in order to keep the + * Candidates harvested by this instance alive. + */ + private void createSendKeepAliveMessageThread() + { + synchronized (sendKeepAliveMessageSyncRoot) + { + sendKeepAliveMessageThread + = new Thread() + { + @Override + public void run() + { + runInSendKeepAliveMessageThread(); + } + }; + sendKeepAliveMessageThread.start(); + } + } + /** * Creates a ServerReflexiveCandidate using {@link #hostCandidate} * as its base and the XOR-MAPPED-ADDRESS attribute in @@ -312,7 +411,7 @@ public class StunCandidateHarvest * @return an array containing the Candidates harvested for * {@link #hostCandidate} during this harvest */ - Candidate[] getCandidates() + LocalCandidate[] getCandidates() { return candidates.toArray(NO_CANDIDATES); } @@ -363,7 +462,8 @@ public class StunCandidateHarvest private boolean processChallenge( byte[] realm, byte[] nonce, - Request request) + Request request, + TransactionID requestTransactionID) throws StunException { UsernameAttribute usernameAttribute @@ -442,7 +542,27 @@ public class StunCandidateHarvest if (retryRequest != null) { - retryRequestTransactionID = sendRequest(retryRequest, false); + if (requestTransactionID != null) + { + Object applicationData + = requestTransactionID.getApplicationData(); + + if (applicationData != null) + { + byte[] retryRequestTransactionIDAsBytes + = retryRequest.getTransactionID(); + + retryRequestTransactionID + = (retryRequestTransactionIDAsBytes == null) + ? TransactionID.createNewTransactionID() + : TransactionID.createTransactionID( + retryRequestTransactionIDAsBytes); + retryRequestTransactionID.setApplicationData( + applicationData); + } + } + retryRequestTransactionID + = sendRequest(retryRequest, false, retryRequestTransactionID); } return (retryRequestTransactionID != null); } @@ -462,7 +582,10 @@ public class StunCandidateHarvest * @throws StunException if anything goes wrong while processing the * challenge */ - private boolean processChallenge(Response response, Request request) + private boolean processChallenge( + Response response, + Request request, + TransactionID transactionID) throws StunException { boolean retried = false; @@ -513,7 +636,8 @@ public class StunCandidateHarvest = processChallenge( realmAttribute.getRealm(), nonceAttribute.getNonce(), - request); + request, + transactionID); } } } @@ -521,6 +645,29 @@ public class StunCandidateHarvest return retried; } + /** + * Notifies this StunCandidateHarvest that a specific + * Request has either received an error Response or has + * failed to receive any Response. Allows extenders to override and + * process unhandled error Responses or failures. The default + * implementation does no processing. + * + * @param response the error Response which has been received for + * request + * @param request the Request to which Response responds + * @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 + */ + protected boolean processErrorOrFailure( + Response response, + Request request, + TransactionID transactionID) + { + return false; + } + /** * Notifies this ResponseCollector that a transaction described by * the specified BaseStunMessageEvent has failed. The possible @@ -554,7 +701,18 @@ public class StunCandidateHarvest if (message instanceof Request) request = (Request) message; } - completedResolvingCandidate(request, null); + + boolean completedResolvingCandidate = true; + try + { + if (processErrorOrFailure(null, request, transactionID)) + completedResolvingCandidate = false; + } + finally + { + if (completedResolvingCandidate) + completedResolvingCandidate(request, null); + } } /** @@ -625,7 +783,7 @@ public class StunCandidateHarvest return; } - createCandidates(response); + processSuccess(response, request, transactionID); } else { @@ -641,11 +799,17 @@ public class StunCandidateHarvest switch (errorCodeAttr.getErrorNumber()) { case 1: // 401 Unauthorized - if (processUnauthorized(response, request)) + if (processUnauthorized( + response, + request, + transactionID)) completedResolvingCandidate = false; break; case 38: // 438 Stale Nonce - if (processStaleNonce(response, request)) + if (processStaleNonce( + response, + request, + transactionID)) completedResolvingCandidate = false; break; } @@ -655,6 +819,12 @@ public class StunCandidateHarvest completedResolvingCandidate = true; } } + if (completedResolvingCandidate + && processErrorOrFailure( + response, + request, + transactionID)) + completedResolvingCandidate = false; } } finally @@ -675,7 +845,10 @@ public class StunCandidateHarvest * @return true if the specified STUN error response was * successfully handled; false, otherwise */ - private boolean processStaleNonce(Response response, Request request) + private boolean processStaleNonce( + Response response, + Request request, + TransactionID transactionID) throws StunException { /* @@ -709,7 +882,26 @@ public class StunCandidateHarvest else challenge = false; - return (challenge && processChallenge(response, request)); + return + (challenge && processChallenge(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 + */ + protected void processSuccess( + Response response, + Request request, + TransactionID transactionID) + { + if (!completedResolvingCandidate) + createCandidates(response); } /** @@ -723,7 +915,10 @@ public class StunCandidateHarvest * @return true if the specified STUN error response was * successfully handled; false, otherwise */ - private boolean processUnauthorized(Response response, Request request) + private boolean processUnauthorized( + Response response, + Request request, + TransactionID transactionID) throws StunException { /* @@ -758,7 +953,162 @@ public class StunCandidateHarvest } } - return (challenge && processChallenge(response, request)); + return + (challenge && processChallenge(response, request, transactionID)); + } + + /** + * Runs in {@link #sendKeepAliveMessageThread} and sends STUN + * keep-alive Messages to the STUN server associated with the + * StunCandidateHarvester of this instance + */ + private void runInSendKeepAliveMessageThread() + { + try + { + while (true) + { + synchronized (sendKeepAliveMessageSyncRoot) + { + /* + * Since we're going to #wait, make sure we're not canceled + * yet. + */ + if (sendKeepAliveMessageInterval + == SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED) + break; + + /* + * Determine the amount of milliseconds that we'll have to + * #wait. + */ + long timeout; + + if (sendKeepAliveMessageTimeStamp == -1) + { + /* + * If we're just starting, don't just go and send a new + * STUN keep-alive message but rather wait for the whole + * interval. + */ + timeout = sendKeepAliveMessageInterval; + } + else + { + timeout + = sendKeepAliveMessageTimeStamp + + sendKeepAliveMessageInterval + - System.currentTimeMillis(); + } + // At long last, #wait if necessary. + if (timeout > 0) + { + try + { + sendKeepAliveMessageSyncRoot.wait(timeout); + } + catch (InterruptedException iex) + { + } + /* + * Apart from being the time to send the STUN keep-alive + * message, it could be that we've experienced a + * spurious wake-up or that we've been canceled. + */ + continue; + } + } + + sendKeepAliveMessageTimeStamp = System.currentTimeMillis(); + try + { + sendKeepAliveMessage(); + } + catch (StunException sex) + { + logger.log( + Level.INFO, + "Failed to send STUN keep-alive message.", + sex); + } + } + } + finally + { + synchronized (sendKeepAliveMessageSyncRoot) + { + if (sendKeepAliveMessageThread == Thread.currentThread()) + sendKeepAliveMessageThread = null; + /* + * 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. + */ + if ((sendKeepAliveMessageThread == null) + && (sendKeepAliveMessageInterval + != SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED)) + createSendKeepAliveMessageThread(); + } + } + } + + /** + * Sends a new STUN Message to the STUN server associated with the + * StunCandidateHarvester of this instance in order to keep a + * LocalCandidate harvested by this instance alive. + * + * @throws StunException if anything goes wrong while sending a new + * keep-alive STUN Message + */ + protected void sendKeepAliveMessage() + throws StunException + { + for (LocalCandidate candidate : getCandidates()) + if (sendKeepAliveMessage(candidate)) + break; + } + + /** + * Sends a new STUN Message to the STUN server associated with the + * StunCandidateHarvester of this instance in order to keep a + * specific LocalCandidate alive. + * + * @param candidate the LocalCandidate to send a new keep-alive + * STUN Message for + * @return true if a new STUN Message was sent to the + * STUN server associated with the StunCandidateHarvester of this + * instance or false if the STUN kee-alive functionality was not + * been used for the specified candidate + * @throws StunException if anything goes wrong while sending the new + * keep-alive STUN Message for the specified candidate + */ + protected boolean sendKeepAliveMessage(LocalCandidate candidate) + throws StunException + { + Message keepAliveMessage = createKeepAliveMessage(candidate); + + /* + * The #createKeepAliveMessage method javadoc says it returns null when + * the STUN keep-alive functionality of this StunCandidateHarvest is to + * not be utilized. + */ + if (keepAliveMessage == null) + return false; + if (keepAliveMessage instanceof Request) + { + return + (sendRequest((Request) keepAliveMessage, false, null) != null); + } + else + { + throw + new StunException( + StunException.ILLEGAL_ARGUMENT, + "Failed to create keep-alive STUN message " + + "for candidate: " + + candidate); + } } /** @@ -777,7 +1127,10 @@ public class StunCandidateHarvest * Request to the STUN server associated with this * StunCandidateHarvest */ - protected TransactionID sendRequest(Request request, boolean firstRequest) + protected TransactionID sendRequest( + Request request, + boolean firstRequest, + TransactionID transactionID) throws StunException { if (!firstRequest && (longTermCredentialSession != null)) @@ -788,8 +1141,15 @@ public class StunCandidateHarvest TransportAddress hostCandidateTransportAddress = hostCandidate.getTransportAddress(); - TransactionID transactionID; + if (transactionID == null) + { + byte[] transactionIDAsBytes = request.getTransactionID(); + transactionID + = (transactionIDAsBytes == null) + ? TransactionID.createNewTransactionID() + : TransactionID.createTransactionID(transactionIDAsBytes); + } synchronized (requests) { try @@ -800,7 +1160,8 @@ public class StunCandidateHarvest request, stunServer, hostCandidateTransportAddress, - this); + this, + transactionID); } catch (IllegalArgumentException iaex) { @@ -842,6 +1203,41 @@ public class StunCandidateHarvest return transactionID; } + /** + * Sets the interval in milliseconds at which a new STUN keep-alive message + * is to be sent to the STUN server associated with the + * StunCandidateHarvester of this instance in order to keep one of + * the Candidates harvested by this instance alive. + * + * @param sendKeepAliveMessageInterval the interval in milliseconds at which + * a new STUN keep-alive message is to be sent to the STUN server associated + * with the StunCandidateHarvester of this instance in order to + * keep one of the Candidates harvested by this instance alive or + * {@link #SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED} if the keep-alive + * functionality is to not be utilized + */ + protected void setSendKeepAliveMessageInterval( + long sendKeepAliveMessageInterval) + { + if ((sendKeepAliveMessageInterval + != SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED) + && (sendKeepAliveMessageInterval < 1)) + throw new IllegalArgumentException("sendKeepAliveMessageInterval"); + + synchronized (sendKeepAliveMessageSyncRoot) + { + this.sendKeepAliveMessageInterval = sendKeepAliveMessageInterval; + if (sendKeepAliveMessageThread == null) + { + if (this.sendKeepAliveMessageInterval + != SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED) + createSendKeepAliveMessageThread(); + } + else + sendKeepAliveMessageSyncRoot.notify(); + } + } + /** * Starts the harvesting of Candidates to be performed for * {@link #hostCandidate}. @@ -865,7 +1261,7 @@ public class StunCandidateHarvest // Short-Term Credential Mechanism addShortTermCredentialAttributes(requestToStartResolvingCandidate); - sendRequest(requestToStartResolvingCandidate, true); + sendRequest(requestToStartResolvingCandidate, true, null); return true; } else diff --git a/src/org/ice4j/ice/harvest/StunCandidateHarvester.java b/src/org/ice4j/ice/harvest/StunCandidateHarvester.java index ca4f8ab..808e399 100644 --- a/src/org/ice4j/ice/harvest/StunCandidateHarvester.java +++ b/src/org/ice4j/ice/harvest/StunCandidateHarvester.java @@ -63,7 +63,7 @@ public class StunCandidateHarvester /** * The stack to use for STUN communication. */ - protected final StunStack stunStack = StunStack.getInstance(); + public final StunStack stunStack = StunStack.getInstance(); /** * Creates a new STUN harvester that will be running against the specified diff --git a/src/org/ice4j/ice/harvest/TurnCandidateHarvest.java b/src/org/ice4j/ice/harvest/TurnCandidateHarvest.java index 8bc9b4c..cfa4620 100644 --- a/src/org/ice4j/ice/harvest/TurnCandidateHarvest.java +++ b/src/org/ice4j/ice/harvest/TurnCandidateHarvest.java @@ -7,10 +7,15 @@ */ package org.ice4j.ice.harvest; +import java.lang.reflect.*; +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 TURN Candidates for a specific @@ -23,6 +28,13 @@ public class TurnCandidateHarvest extends StunCandidateHarvest { + /** + * The Logger used by the TurnCandidateHarvest class and + * its instances for logging output. + */ + private static final Logger logger + = Logger.getLogger(TurnCandidateHarvest.class.getName()); + /** * The Request created by the last call to * {@link #createRequestToStartResolvingCandidate()}. @@ -47,6 +59,48 @@ public class TurnCandidateHarvest super(harvester, hostCandidate); } + /** + * 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(RelayedCandidateDatagramSocket 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); + + /* + * TURN Refresh with a LIFETIME value equal to zero deletes the TURN + * Allocation. + */ + try + { + sendRequest(MessageFactory.createRefreshRequest(0), false, null); + } + catch (StunException sex) + { + logger.log( + Level.INFO, + "Failed to send TURN Refresh request to delete Allocation", + sex); + } + } + /** * Completes the harvesting of Candidates for * {@link #hostCandidate}. Notifies {@link #harvester} about the completion @@ -111,6 +165,54 @@ public class TurnCandidateHarvest super.createCandidates(response); } + /** + * Creates a new STUN Message to be sent to the STUN server + * associated with the StunCandidateHarvester of this instance in + * order to keep a specific LocalCandidate (harvested by this + * instance) alive. + * + * @param candidate the LocalCandidate (harvested by this instance) + * to create a new keep-alive STUN message for + * @return a new keep-alive STUN Message for the specified + * candidate or null if no keep-alive sending is to occur + * @throws StunException if anything goes wrong while creating the new + * keep-alive STUN Message for the specified candidate + * or the candidate is of an unsupported CandidateType + * @see StunCandidateHarvest#createKeepAliveMessage(LocalCandidate) + */ + @Override + protected Message createKeepAliveMessage(LocalCandidate candidate) + throws StunException + { + switch (candidate.getType()) + { + case RELAYED_CANDIDATE: + return MessageFactory.createRefreshRequest(); + case SERVER_REFLEXIVE_CANDIDATE: + /* + * RFC 5245: The Refresh requests will also refresh the server + * reflexive candidate. + */ + boolean existsRelayedCandidate = false; + + for (Candidate aCandidate : getCandidates()) + { + if (CandidateType.RELAYED_CANDIDATE.equals( + aCandidate.getType())) + { + existsRelayedCandidate = true; + break; + } + } + return + existsRelayedCandidate + ? null + : super.createKeepAliveMessage(candidate); + default: + return super.createKeepAliveMessage(candidate); + } + } + /** * Creates a RelayedCandidate using the * XOR-RELAYED-ADDRESS attribute in a specific STUN @@ -137,7 +239,17 @@ public class TurnCandidateHarvest 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.stunStack.addSocket( + relayedCandidate.getStunSocket(null)); + addCandidate(relayedCandidate); + } } } @@ -208,6 +320,44 @@ public class TurnCandidateHarvest MessageFactory.createAllocateRequest( (byte) requestedTransport, rFlag); + + case Message.CREATEPERMISSION_REQUEST: + XorPeerAddressAttribute peerAddressAttribute + = (XorPeerAddressAttribute) + request.getAttribute(Attribute.XOR_PEER_ADDRESS); + TransportAddress peerAddress + = peerAddressAttribute.getAddress(request.getTransactionID()); + byte[] retryTransactionID + = TransactionID.createNewTransactionID().getBytes(); + Request retryCreatePermissionRequest + = MessageFactory.createCreatePermissionRequest( + peerAddress, + retryTransactionID); + + try + { + retryCreatePermissionRequest.setTransactionID( + retryTransactionID); + } + catch (StunException sex) + { + throw new UndeclaredThrowableException(sex); + } + return retryCreatePermissionRequest; + + case Message.REFRESH_REQUEST: + LifetimeAttribute lifetimeAttribute + = (LifetimeAttribute) request.getAttribute(Attribute.LIFETIME); + + if (lifetimeAttribute == null) + return MessageFactory.createRefreshRequest(); + else + { + return + MessageFactory.createRefreshRequest( + lifetimeAttribute.getLifetime()); + } + default: return super.createRequestToRetry(request); } @@ -242,4 +392,126 @@ public class TurnCandidateHarvest else return null; } + + /** + * 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 + * @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 + */ + @Override + protected boolean processErrorOrFailure( + Response response, + Request request, + TransactionID transactionID) + { + + /* + * 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 + * @see StunCandidateHarvest#processSuccess(Response, Request) + */ + @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. + lifetimeAttribute + = (LifetimeAttribute) response.getAttribute(Attribute.LIFETIME); + lifetime + = (lifetimeAttribute == null) + ? (10 * 60) + : lifetimeAttribute.getLifetime(); + break; + case Message.REFRESH_RESPONSE: + lifetimeAttribute + = (LifetimeAttribute) response.getAttribute(Attribute.LIFETIME); + if (lifetimeAttribute != null) + lifetime = lifetimeAttribute.getLifetime(); + 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); + } + } + + /** + * Sends a specific Request on behalf of a specific + * RelayedCandidateDatagramSocket to the TURN server associated + * with this TurnCandidateHarvest. + * + * @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(); + } } diff --git a/src/org/ice4j/message/Message.java b/src/org/ice4j/message/Message.java index ff0ebf9..418524d 100644 --- a/src/org/ice4j/message/Message.java +++ b/src/org/ice4j/message/Message.java @@ -22,6 +22,7 @@ import org.ice4j.stack.*; * * @author Emil Ivov * @author Sebastien Vincent + * @author Lubomir Marinov */ public abstract class Message { @@ -51,8 +52,9 @@ public abstract class Message /* TURN methods */ public static final char TURN_METHOD_ALLOCATE = 0x0003; public static final char TURN_METHOD_REFRESH = 0x0004; - public static final char TURN_METHOD_SEND = 0x0006;; - public static final char TURN_METHOD_DATA = 0x0007;; + public static final char TURN_METHOD_SEND = 0x0006; + public static final char TURN_METHOD_DATA = 0x0007; + public static final char TURN_METHOD_CREATEPERMISSION = 0x0008; public static final char TURN_METHOD_CHANNELBIND = 0x0009; public static final char ALLOCATE_REQUEST = (TURN_METHOD_ALLOCATE | STUN_REQUEST); @@ -64,6 +66,9 @@ public abstract class Message public static final char CHANNELBIND_REQUEST = (TURN_METHOD_CHANNELBIND | STUN_REQUEST); public static final char CHANNELBIND_RESPONSE = (TURN_METHOD_CHANNELBIND | STUN_SUCCESS_RESP); public static final char CHANNELBIND_ERROR_RESPONSE = (TURN_METHOD_CHANNELBIND | STUN_ERROR_RESP); + public static final char CREATEPERMISSION_REQUEST = (TURN_METHOD_CREATEPERMISSION | STUN_REQUEST); + public static final char CREATEPERMISSION_RESPONSE = (TURN_METHOD_CREATEPERMISSION | STUN_SUCCESS_RESP); + public static final char CREATEPERMISSION_ERROR_RESPONSE = (TURN_METHOD_CREATEPERMISSION | STUN_ERROR_RESP); public static final char SEND_INDICATION = (TURN_METHOD_SEND | STUN_INDICATION); public static final char DATA_INDICATION = (TURN_METHOD_DATA | STUN_INDICATION); @@ -116,7 +121,7 @@ public abstract class Message private static boolean rfc3489CompatibilityMode = false; /** - * Desribes which attributes are present in which messages. An + * Describes which attributes are present in which messages. An * M indicates that inclusion of the attribute in the message is * mandatory, O means its optional, C means it's conditional based on * some other aspect of the message, and N/A means that the attribute is @@ -440,6 +445,16 @@ public abstract class Message case CHANNELBIND_REQUEST: msgIndex = CHANNELBIND_REQUEST_PRESENTITY_INDEX; break; case SEND_INDICATION: msgIndex = SEND_INDICATION_PRESENTITY_INDEX; break; case DATA_INDICATION: msgIndex = DATA_INDICATION_PRESENTITY_INDEX; break; + default: + if (logger.isLoggable(Level.FINE)) + { + logger.log( + Level.FINE, + "Attribute presentity not defined for STUN message type: " + + ((int) messageType) + + ". Will assume optional."); + } + return O; } switch (attributeType) @@ -494,12 +509,20 @@ public abstract class Message case BINDING_REQUEST: return "BINDING-REQUEST"; case BINDING_SUCCESS_RESPONSE: return "BINDING-RESPONSE"; case BINDING_ERROR_RESPONSE: return "BINDING-ERROR-RESPONSE"; + case CREATEPERMISSION_REQUEST: return "CREATE-PERMISSION-REQUEST"; + case CREATEPERMISSION_RESPONSE: return "CREATE-PERMISSION-RESPONSE"; + case CREATEPERMISSION_ERROR_RESPONSE: + return "CREATE-PERMISSION-ERROR-RESPONSE"; + case DATA_INDICATION: return "DATA-INDICATION"; + case REFRESH_REQUEST: return "REFRESH-REQUEST"; + case REFRESH_RESPONSE: return "REFRESH-RESPONSE"; + case REFRESH_ERROR_RESPONSE: return "REFRESH-ERROR-RESPONSE"; + case SEND_INDICATION: return "SEND-INDICATION"; case SHARED_SECRET_REQUEST: return "SHARED-SECRET-REQUEST"; case SHARED_SECRET_RESPONSE: return "SHARED-SECRET-RESPONSE"; case SHARED_SECRET_ERROR_RESPONSE: return "SHARED-SECRET-ERROR-RESPONSE"; + default: return "UNKNOWN-MESSAGE"; } - - return "UNKNOWN-MESSAGE"; } /** @@ -691,17 +714,11 @@ public abstract class Message | (binMessage[offset++]&0xFF)); Message message; if (Message.isResponseType(messageType)) - { message = new Response(); - } else if(Message.isRequestType(messageType)) - { message = new Request(); - } else /* indication */ - { message = new Indication(); - } message.setMessageType(messageType); @@ -715,9 +732,16 @@ public abstract class Message if(arrayLen - offset - TRANSACTION_ID_LENGTH < length) { - throw new StunException( StunException.ILLEGAL_ARGUMENT, - "The given binary array does not seem to " - + "contain a whole StunMessage"); + throw + new StunException( + StunException.ILLEGAL_ARGUMENT, + "The given binary array does not seem to contain" + + " a whole StunMessage: given " + + ((int) arrayLen) + + " bytes of " + + message.getName() + + " but expecting " + + (offset + TRANSACTION_ID_LENGTH + length)); } byte tranID[] = new byte[TRANSACTION_ID_LENGTH]; @@ -846,7 +870,6 @@ public abstract class Message protected void validateAttributePresentity() throws IllegalStateException { - //the if(! rfc3489CompatibilityMode ) return; diff --git a/src/org/ice4j/message/MessageFactory.java b/src/org/ice4j/message/MessageFactory.java index 5ab5648..7bf87c9 100644 --- a/src/org/ice4j/message/MessageFactory.java +++ b/src/org/ice4j/message/MessageFactory.java @@ -18,9 +18,15 @@ import org.ice4j.attribute.*; * * @author Emil Ivov * @author Sebastien Vincent + * @author Lubomir Marinov */ public class MessageFactory { + + /** + * The Logger used by the MessageFactory class and its + * instances. + */ private static final Logger logger = Logger.getLogger(MessageFactory.class.getName()); @@ -434,6 +440,32 @@ public class MessageFactory request.addAttribute(messageIntegrityAttribute); } + /** + * Creates a new TURN Refresh Request without any optional + * attributes such as LIFETIME. + * + * @return a new TURN Refresh Request without any optional + * attributes such as LIFETIME + */ + public static Request createRefreshRequest() + { + Request refreshRequest = new Request(); + + try + { + refreshRequest.setMessageType(Message.REFRESH_REQUEST); + } + catch (IllegalArgumentException iaex) + { + /* + * We don't actually expect the exception to happen so we're + * ignoring it. + */ + logger.log(Level.FINE, "Failed to set message type.", iaex); + } + return refreshRequest; + } + /** * Create a refresh request. * @@ -498,6 +530,40 @@ public class MessageFactory return channelBindRequest; } + /** + * Creates a new TURN CreatePermission Request with a specific + * value for its XOR-PEER-ADDRESS attribute. + * + * @param peerAddress the value to assigned to the XOR-PEER-ADDRESS + * attribute + * @param transactionID the ID of the transaction which is to be used for + * the assignment of peerAddress to the XOR-PEER-ADDRESS attribute + * @return a new TURN CreatePermission Request with the specified + * value for its XOR-PEER-ADDRESS attribute + */ + public static Request createCreatePermissionRequest( + TransportAddress peerAddress, + byte[] transactionID) + { + Request createPermissionRequest = new Request(); + + try + { + createPermissionRequest.setMessageType( + Message.CREATEPERMISSION_REQUEST); + } + catch (IllegalArgumentException iaex) + { + // Expected to not happen because we are the creators. + logger.log(Level.FINE, "Failed to set message type.", iaex); + } + createPermissionRequest.addAttribute( + AttributeFactory.createXorPeerAddressAttribute( + peerAddress, + transactionID)); + return createPermissionRequest; + } + /** * Create a Send Indication. * diff --git a/src/org/ice4j/socket/DelegatingDatagramSocket.java b/src/org/ice4j/socket/DelegatingDatagramSocket.java new file mode 100644 index 0000000..30f3027 --- /dev/null +++ b/src/org/ice4j/socket/DelegatingDatagramSocket.java @@ -0,0 +1,712 @@ +/* + * 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.*; +import java.nio.channels.*; + +/** + * Implements a DatagramSocket which delegates its calls to a specific + * DatagramSocket. + * + * @author Lubomir Marinov + */ +public class DelegatingDatagramSocket + extends DatagramSocket +{ + + /** + * The DatagramSocket to which this + * DelegatingDatagramSocket delegates its calls. + */ + protected final DatagramSocket delegate; + + /** + * Initializes a new DelegatingDatagramSocket instance and binds it + * to any available port on the local host machine. The socket will be + * bound to the wildcard address, an IP address chosen by the kernel. + * + * @throws SocketException if the socket could not be opened, or the socket + * could not bind to the specified local port + * @see DatagramSocket#DatagramSocket() + */ + public DelegatingDatagramSocket() + throws SocketException + { + super(); + + this.delegate = null; + } + + /** + * Initializes a new DelegatingDatagramSocket instance which to + * implement the DatagramSocket functionality by delegating to a + * specific DatagramSocket. + * + * @param delegate the DatagramSocket to which the new instance is + * to delegate + * @throws SocketException if anything goes wrong while initializing the new + * DelegatingDatagramSocket instance + */ + public DelegatingDatagramSocket(DatagramSocket delegate) + throws SocketException + { + super(/* bindaddr */ (SocketAddress) null); + + this.delegate = delegate; + } + + /** + * Initializes a new DelegatingDatagramSocket instance and binds + * it to the specified port on the local host machine. The socket will be + * bound to the wildcard address, an IP address chosen by the kernel. + * + * @param port the port to bind the new socket to + * @throws SocketException if the socket could not be opened, or the socket + * could not bind to the specified local port + * @see DatagramSocket#DatagramSocket(int) + */ + public DelegatingDatagramSocket(int port) + throws SocketException + { + super(port); + + this.delegate = null; + } + + /** + * Initializes a new DelegatingDatagramSocket instance bound to the + * specified local address. The local port must be between 0 and 65535 + * inclusive. If the IP address is 0.0.0.0, the socket will be bound to the + * wildcard address, an IP address chosen by the kernel. + * + * @param port the local port to bind the new socket to + * @param laddr the local address to bind the new socket to + * @throws SocketException if the socket could not be opened, or the socket + * could not bind to the specified local port + * @see DatagramSocket#DatagramSocket(int, InetAddress) + */ + public DelegatingDatagramSocket(int port, InetAddress laddr) + throws SocketException + { + super(port, laddr); + + this.delegate = null; + } + + /** + * Creates a datagram socket, bound to the specified local socket address. + *

+ * If, if the address is null, creates an unbound socket. + *

+ * + * @param bindaddr local socket address to bind, or null for an + * unbound socket + * @throws SocketException if the socket could not be opened, or the socket + * could not bind to the specified local port + */ + public DelegatingDatagramSocket(SocketAddress bindaddr) + throws SocketException + { + super(bindaddr); + + this.delegate = null; + } + + /** + * Binds this DatagramSocket to a specific address and port. + *

+ * If the address is null, then the system will pick up an + * ephemeral port and a valid local address to bind the socket. + *

+ * + * @param addr the address and port to bind to + * @throws SocketException if any error happens during the bind, or if the + * socket is already bound + * @throws SecurityException if a security manager exists and its + * checkListen method doesn't allow the operation + * @throws IllegalArgumentException if addr is a + * SocketAddress subclass not supported by this socket + * @see DatagramSocket#bind(SocketAddress) + */ + @Override + public void bind(SocketAddress addr) + throws SocketException + { + if (delegate == null) + super.bind(addr); + else + delegate.bind(addr); + } + + /** + * Closes this datagram socket. + *

+ * Any thread currently blocked in {@link #receive(DatagramPacket)} upon + * this socket will throw a {@link SocketException}. + *

+ * + * @see DatagramSocket#close() + */ + @Override + public void close() + { + if (delegate == null) + super.close(); + else + delegate.close(); + } + + /** + * Connects the socket to a remote address for this socket. When a socket is + * connected to a remote address, packets may only be sent to or received + * from that address. By default a datagram socket is not connected. + *

+ * If the remote destination to which the socket is connected does not + * exist, or is otherwise unreachable, and if an ICMP destination + * unreachable packet has been received for that address, then a subsequent + * call to {@link #send(DatagramPacket)} or {@link #receive(DatagramPacket)} + * may throw a PortUnreachableException. Note, there is no + * guarantee that the exception will be thrown. + *

+ * + * @param address the remote address for the socket + * @param port the remote port for the socket + * @throws IllegalArgumentException if the address is null, or the + * port is out of range + * @throws SecurityException if the caller is not allowed to send datagrams + * to and receive datagrams from the address and port + * @see DatagramSocket#connect(InetAddress, int) + */ + @Override + public void connect(InetAddress address, int port) + { + if (delegate == null) + super.connect(address, port); + else + delegate.connect(address, port); + } + + /** + * Connects this socket to a remote socket address. + * + * @param addr the remote address + * @throws SocketException if the connect fails + * @throws IllegalArgumentException if addr is null or a + * SocketAddress subclass not supported by this socket + * @see DatagramSocket#connect(SocketAddress) + */ + @Override + public void connect(SocketAddress addr) + throws SocketException + { + if (delegate == null) + super.connect(addr); + else + delegate.connect(addr); + } + + /** + * Disconnects the socket. This does nothing if the socket is not connected. + * + * @see DatagramSocket#disconnect() + */ + @Override + public void disconnect() + { + if (delegate == null) + super.disconnect(); + else + delegate.disconnect(); + } + + /** + * Tests if SO_BROADCAST is enabled. + * + * @return a boolean indicating whether or not + * SO_BROADCAST is enabled + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @see DatagramSocket#getBroadcast() + */ + @Override + public boolean getBroadcast() + throws SocketException + { + return + (delegate == null) ? super.getBroadcast() : delegate.getBroadcast(); + } + + /** + * Returns the unique {@link DatagramChannel} object associated with this + * datagram socket, if any. + *

+ * A datagram socket will have a channel if, and only if, the channel itself + * was created via the {@link DatagramChannel#open()} method + *

+ * + * @return the datagram channel associated with this datagram socket, or + * null if this socket was not created for a channel + * @see DatagramSocket#getChannel() + */ + @Override + public DatagramChannel getChannel() + { + return (delegate == null) ? super.getChannel() : delegate.getChannel(); + } + + /** + * Returns the address to which this socket is connected. Returns + * null if the socket is not connected. + * + * @return the address to which this socket is connected + * @see DatagramSocket#getInetAddress() + */ + @Override + public InetAddress getInetAddress() + { + return + (delegate == null) + ? super.getInetAddress() + : delegate.getInetAddress(); + } + + /** + * Gets the local address to which the socket is bound. + *

+ * 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 DatagramSocket#getLocalAddress() + */ + @Override + public InetAddress getLocalAddress() + { + return + (delegate == null) + ? super.getLocalAddress() + : delegate.getLocalAddress(); + } + + /** + * Returns the port number on the local host to which this socket is bound. + * + * @return the port number on the local host to which this socket is bound + * @see DatagramSocket#getLocalPort() + */ + @Override + public int getLocalPort() + { + return + (delegate == null) ? super.getLocalPort() : delegate.getLocalPort(); + } + + /** + * Returns the address of the endpoint this socket is bound to, or + * null if it is not bound yet. + * + * @return a SocketAddress representing the local endpoint of this + * socket, or null if it is not bound yet + * @see DatagramSocket#getLocalSocketAddress() + */ + @Override + public SocketAddress getLocalSocketAddress() + { + return + (delegate == null) + ? super.getLocalSocketAddress() + : delegate.getLocalSocketAddress(); + } + + /** + * Returns the port for this socket. Returns -1 if the socket is + * not connected. + * + * @return the port to which this socket is connected + * @see DatagramSocket#getPort() + */ + @Override + public int getPort() + { + return (delegate == null) ? super.getPort() : delegate.getPort(); + } + + /** + * Gets the value of the SO_RCVBUF option for this + * DatagramSocket, that is the buffer size used by the platform for + * input on this DatagramSocket. + * + * @return the value of the SO_RCVBUF option for this + * DatagramSocket + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @see DatagramSocket#getReceiveBufferSize() + */ + @Override + public int getReceiveBufferSize() + throws SocketException + { + return + (delegate == null) + ? super.getReceiveBufferSize() + : delegate.getReceiveBufferSize(); + } + + /** + * Returns the address of the endpoint this socket is connected to, or + * null if it is unconnected. + * + * @return a SocketAddress representing the remote endpoint of this + * socket, or null if it is not connected yet + * @see DatagramSocket#getRemoteSocketAddress() + */ + @Override + public SocketAddress getRemoteSocketAddress() + { + return + (delegate == null) + ? super.getRemoteSocketAddress() + : delegate.getRemoteSocketAddress(); + } + + /** + * Tests if SO_REUSEADDR is enabled. + * + * @return a boolean indicating whether or not + * SO_REUSEADDR is enabled + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @see DatagramSocket#getReuseAddress() + */ + @Override + public boolean getReuseAddress() + throws SocketException + { + return + (delegate ==null) + ? super.getReuseAddress() + : delegate.getReuseAddress(); + } + + /** + * Gets the value of the SO_SNDBUF option for this + * DatagramSocket, that is the buffer size used by the platform for + * output on this DatagramSocket. + * + * @return the value of the SO_SNDBUF option for this + * DatagramSocket + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @see DatagramSocket#getSendBufferSize() + */ + @Override + public int getSendBufferSize() + throws SocketException + { + return + (delegate == null) + ? super.getSendBufferSize() + : delegate.getSendBufferSize(); + } + + /** + * Retrieves setting for SO_TIMEOUT. Zero returned implies that + * the option is disabled (i.e., timeout of infinity). + * + * @return the setting for SO_TIMEOUT + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @see DatagramSocket#getSoTimeout() + */ + @Override + public int getSoTimeout() + throws SocketException + { + return + (delegate == null) ? super.getSoTimeout() : delegate.getSoTimeout(); + } + + /** + * Gets the traffic class or type-of-service in the IP datagram header for + * packets sent from this DatagramSocket. + *

+ * As the underlying network implementation may ignore the traffic class or + * type-of-service set using {@link #setTrafficClass(int)} this method may + * return a different value than was previously set using the + * {@link #setTrafficClass(int)} method on this DatagramSocket. + *

+ * + * @return the traffic class or type-of-service already set + * @throws SocketException if there is an error obtaining the traffic class + * or type-of-service value + * @see DatagramSocket#getTrafficClass() + */ + @Override + public int getTrafficClass() + throws SocketException + { + return + (delegate == null) + ? super.getTrafficClass() + : delegate.getTrafficClass(); + } + + /** + * Returns the binding state of the socket. + * + * @return true if the socket successfully bound to an address; + * otherwise, false + * @see DatagramSocket#isBound() + */ + @Override + public boolean isBound() + { + return (delegate == null) ? super.isBound() : delegate.isBound(); + } + + /** + * Returns whether the socket is closed or not. + * + * @return true if the socket has been closed; otherwise, + * false + * @see DatagramSocket#isClosed() + */ + @Override + public boolean isClosed() + { + return (delegate == null) ? super.isClosed() : this.isClosed(); + } + + /** + * Returns the connection state of the socket. + * + * @return true if the socket successfully connected to a server; + * otherwise, false + * @see DatagramSocket#isConnected() + */ + @Override + public boolean isConnected() + { + return (delegate == null) ? super.isConnected() : this.isConnected(); + } + + /** + * 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. + *

+ * This method blocks until a datagram is received. The length + * field of the datagram packet object contains the length of the received + * message. If the message is longer than the packet's length, the message + * is truncated. + *

+ *

+ * If there is a security manager, a packet cannot be received if the + * security manager's checkAccept method does not allow it. + *

+ * + * @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 + { + if (delegate == null) + super.receive(p); + else + delegate.receive(p); + } + + /** + * 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. + *

+ * If there is a security manager, and the socket is not currently connected + * to a remote address, this method first performs some security checks. + * First, if p.getAddress().isMulticastAddress() is true, this + * method calls the security manager's checkMulticast method with + * p.getAddress() as its argument. If the evaluation of that + * expression is false, this method instead calls the security + * manager's checkConnect method with arguments + * p.getAddress().getHostAddress() and p.getPort(). Each + * call to a security manager method could result in a + * SecurityException if the operation is not allowed. + *

+ * + * @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 + { + if (delegate == null) + super.send(p); + else + delegate.send(p); + } + + /** + * Enables/disables SO_BROADCAST. + * + * @param on whether or not to have broadcast turned on + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @see DatagramSocket#setBroadcast(boolean) + */ + @Override + public void setBroadcast(boolean on) + throws SocketException + { + if (delegate == null) + super.setBroadcast(on); + else + delegate.setBroadcast(on); + } + + /** + * Sets the SO_RCVBUF option to the specified value for this + * DatagramSocket. The SO_RCVBUF option is used by the + * network implementation as a hint to size the underlying network I/O + * buffers. The SO_RCVBUF setting may also be used by the network + * implementation to determine the maximum size of the packet that can be + * received on this socket. + *

+ * Because SO_RCVBUF is a hint, applications that want to verify + * what size the buffers were set to should call + * {@link #getReceiveBufferSize()}. + *

+ * + * @param size the size to which to set the receive buffer size. The value + * must be greater than zero + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @throws IllegalArgumentException if the value is zero or is negative + * @see DatagramSocket#setReceiveBufferSize(int) + */ + @Override + public void setReceiveBufferSize(int size) + throws SocketException + { + if (delegate == null) + super.setReceiveBufferSize(size); + else + delegate.setReceiveBufferSize(size); + } + + /** + * Enables/disables the SO_REUSEADDR socket option. + * + * @param on whether to enable or disable the SO_REUSEADDR socket + * option + * @throws SocketException if an error occurs enabling or disabling the + * SO_RESUEADDR socket option, or the socket is closed + * @see DatagramSocket#setReuseAddress(boolean) + */ + @Override + public void setReuseAddress(boolean on) + throws SocketException + { + if (delegate == null) + super.setReuseAddress(on); + else + delegate.setReuseAddress(on); + } + + /** + * Sets the SO_SNDBUF option to the specified value for this + * DatagramSocket. The SO_SNDBUF option is used by the + * network implementation as a hint to size the underlying network I/O + * buffers. The SO_SNDBUF setting may also be used by the network + * implementation to determine the maximum size of the packet that can be + * sent on this socket. + *

+ * As SO_SNDBUF is a hint, applications that want to verify what + * size the buffer is should call {@link #getSendBufferSize()}. + *

+ *

+ * Increasing the buffer size may allow multiple outgoing packets to be + * queued by the network implementation when the send rate is high. + *

+ * + * @param size the size to which to set the send buffer size. The value must + * be greater than zero + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @throws IllegalArgumentException if the value is zero or is negative + * @see DatagramSocket#setSendBufferSize(int) + */ + @Override + public void setSendBufferSize(int size) + throws SocketException + { + if (delegate == null) + super.setSendBufferSize(size); + else + delegate.setSendBufferSize(size); + } + + /** + * Enables/disables SO_TIMEOUT with the specified timeout, in + * milliseconds. With this option set to a non-zero timeout, a call to + * {@link #receive(DatagramPacket)} for this DatagramSocket will + * block for only this amount of time. If the timeout expires, a + * SocketTimeoutException is raised, though the + * DatagramSocket is still valid. The option must be enabled prior + * to entering the blocking operation to have effect. The timeout must be + * greater than zero. A timeout of zero is interpreted as an infinite + * timeout. + * + * @param timeout the specified timeout in milliseconds + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @see DatagramSocket#setSoTimeout(int) + */ + @Override + public void setSoTimeout(int timeout) + throws SocketException + { + if (delegate == null) + super.setSoTimeout(timeout); + else + delegate.setSoTimeout(timeout); + } + + /** + * Sets traffic class or type-of-service octet in the IP datagram header for + * datagrams sent from this DatagramSocket. As the underlying + * network implementation may ignore this value applications should consider + * it a hint. + * + * @param tc an int value for the bitset + * @throws SocketException if there is an error setting the traffic class or + * type-of-service + * @see DatagramSocket#setTrafficClass(int) + */ + @Override + public void setTrafficClass(int tc) + throws SocketException + { + if (delegate == null) + super.setTrafficClass(tc); + else + delegate.setTrafficClass(tc); + } +} diff --git a/src/org/ice4j/socket/MultiplexedDatagramSocket.java b/src/org/ice4j/socket/MultiplexedDatagramSocket.java index 80fec39..f6d7902 100644 --- a/src/org/ice4j/socket/MultiplexedDatagramSocket.java +++ b/src/org/ice4j/socket/MultiplexedDatagramSocket.java @@ -9,7 +9,6 @@ package org.ice4j.socket; import java.io.*; import java.net.*; -import java.nio.channels.*; import java.util.*; /** @@ -25,7 +24,7 @@ import java.util.*; * @author Lubomir Marinov */ public class MultiplexedDatagramSocket - extends DatagramSocket + extends DelegatingDatagramSocket { /** @@ -76,7 +75,7 @@ public class MultiplexedDatagramSocket * yet. That is why MultiplexedDatagramSocket does not currently support * bind at construction time. */ - super((SocketAddress) null); + super(multiplexing); if (multiplexing == null) throw new NullPointerException("multiplexing"); @@ -85,29 +84,6 @@ public class MultiplexedDatagramSocket this.filter = filter; } - /** - * Binds this DatagramSocket to a specific address and port. - *

- * If the address is null, then the system will pick up an - * ephemeral port and a valid local address to bind the socket. - *

- * - * @param addr the address and port to bind to - * @throws SocketException if any error happens during the bind, or if the - * socket is already bound - * @throws SecurityException if a security manager exists and its - * checkListen method doesn't allow the operation - * @throws IllegalArgumentException if addr is a - * SocketAddress subclass not supported by this socket - * @see DatagramSocket#bind(SocketAddress) - */ - @Override - public void bind(SocketAddress addr) - throws SocketException - { - multiplexing.bind(addr); - } - /** * Closes this datagram socket. *

@@ -123,94 +99,6 @@ public class MultiplexedDatagramSocket multiplexing.close(this); } - /** - * Connects the socket to a remote address for this socket. When a socket is - * connected to a remote address, packets may only be sent to or received - * from that address. By default a datagram socket is not connected. - *

- * If the remote destination to which the socket is connected does not - * exist, or is otherwise unreachable, and if an ICMP destination - * unreachable packet has been received for that address, then a subsequent - * call to {@link #send(DatagramPacket)} or {@link #receive(DatagramPacket)} - * may throw a PortUnreachableException. Note, there is no - * guarantee that the exception will be thrown. - *

- * - * @param address the remote address for the socket - * @param port the remote port for the socket - * @throws IllegalArgumentException if the address is null, or the - * port is out of range - * @throws SecurityException if the caller is not allowed to send datagrams - * to and receive datagrams from the address and port - * @see DatagramSocket#connect(InetAddress, int) - */ - @Override - public void connect(InetAddress address, int port) - { - multiplexing.connect(address, port); - } - - /** - * Connects this socket to a remote socket address. - * - * @param addr the remote address - * @throws SocketException if the connect fails - * @throws IllegalArgumentException if addr is null or a - * SocketAddress subclass not supported by this socket - * @see DatagramSocket#connect(SocketAddress) - */ - @Override - public void connect(SocketAddress addr) - throws SocketException - { - multiplexing.connect(addr); - } - - /** - * Disconnects the socket. This does nothing if the socket is not connected. - * - * @see DatagramSocket#disconnect() - */ - @Override - public void disconnect() - { - multiplexing.disconnect(); - } - - /** - * Tests if SO_BROADCAST is enabled. - * - * @return a boolean indicating whether or not - * SO_BROADCAST is enabled - * @throws SocketException if there is an error in the underlying protocol, - * such as an UDP error - * @see DatagramSocket#getBroadcast() - */ - @Override - public boolean getBroadcast() - throws SocketException - { - return multiplexing.getBroadcast(); - } - - /** - * Returns the unique {@link DatagramChannel} object associated with this - * datagram socket, if any. - *

- * A datagram socket will have a channel if, and only if, the channel itself - * was created via the {@link DatagramChannel#open()} method - *

- * - * @return the datagram channel associated with this datagram socket, or - * null if this socket was not created for a channel - * @see DatagramSocket#getChannel() - */ - @Override - public DatagramChannel getChannel() - { - return multiplexing.getChannel(); - } - /** * Gets the DatagramPacketFilter which determines which * DatagramPackets read from the network are to be received through @@ -225,220 +113,6 @@ public class MultiplexedDatagramSocket return filter; } - /** - * Returns the address to which this socket is connected. Returns - * null if the socket is not connected. - * - * @return the address to which this socket is connected - * @see DatagramSocket#getInetAddress() - */ - @Override - public InetAddress getInetAddress() - { - return multiplexing.getInetAddress(); - } - - /** - * Gets the local address to which the socket is bound. - *

- * 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 DatagramSocket#getLocalAddress() - */ - @Override - public InetAddress getLocalAddress() - { - return multiplexing.getLocalAddress(); - } - - /** - * Returns the port number on the local host to which this socket is bound. - * - * @return the port number on the local host to which this socket is bound - * @see DatagramSocket#getLocalPort() - */ - @Override - public int getLocalPort() - { - return multiplexing.getLocalPort(); - } - - /** - * Returns the address of the endpoint this socket is bound to, or - * null if it is not bound yet. - * - * @return a SocketAddress representing the local endpoint of this - * socket, or null if it is not bound yet - * @see DatagramSocket#getLocalSocketAddress() - */ - @Override - public SocketAddress getLocalSocketAddress() - { - return multiplexing.getLocalSocketAddress(); - } - - /** - * Returns the port for this socket. Returns -1 if the socket is - * not connected. - * - * @return the port to which this socket is connected - * @see DatagramSocket#getPort() - */ - @Override - public int getPort() - { - return multiplexing.getPort(); - } - - /** - * Gets the value of the SO_RCVBUF option for this - * DatagramSocket, that is the buffer size used by the platform for - * input on this DatagramSocket. - * - * @return the value of the SO_RCVBUF option for this - * DatagramSocket - * @throws SocketException if there is an error in the underlying protocol, - * such as an UDP error - * @see DatagramSocket#getReceiveBufferSize() - */ - @Override - public int getReceiveBufferSize() - throws SocketException - { - return multiplexing.getReceiveBufferSize(); - } - - /** - * Returns the address of the endpoint this socket is connected to, or - * null if it is unconnected. - * - * @return a SocketAddress representing the remote endpoint of this - * socket, or null if it is not connected yet - * @see DatagramSocket#getRemoteSocketAddress() - */ - @Override - public SocketAddress getRemoteSocketAddress() - { - return multiplexing.getRemoteSocketAddress(); - } - - /** - * Tests if SO_REUSEADDR is enabled. - * - * @return a boolean indicating whether or not - * SO_REUSEADDR is enabled - * @throws SocketException if there is an error in the underlying protocol, - * such as an UDP error - * @see DatagramSocket#getReuseAddress() - */ - @Override - public boolean getReuseAddress() - throws SocketException - { - return multiplexing.getReuseAddress(); - } - - /** - * Gets the value of the SO_SNDBUF option for this - * DatagramSocket, that is the buffer size used by the platform for - * output on this DatagramSocket. - * - * @return the value of the SO_SNDBUF option for this - * DatagramSocket - * @throws SocketException if there is an error in the underlying protocol, - * such as an UDP error - * @see DatagramSocket#getSendBufferSize() - */ - @Override - public int getSendBufferSize() - throws SocketException - { - return multiplexing.getSendBufferSize(); - } - - /** - * Retrieves setting for SO_TIMEOUT. Zero returned implies that - * the option is disabled (i.e., timeout of infinity). - * - * @return the setting for SO_TIMEOUT - * @throws SocketException if there is an error in the underlying protocol, - * such as an UDP error - * @see DatagramSocket#getSoTimeout() - */ - @Override - public int getSoTimeout() - throws SocketException - { - return multiplexing.getSoTimeout(); - } - - /** - * Gets the traffic class or type-of-service in the IP datagram header for - * packets sent from this DatagramSocket. - *

- * As the underlying network implementation may ignore the traffic class or - * type-of-service set using {@link #setTrafficClass(int)} this method may - * return a different value than was previously set using the - * {@link #setTrafficClass(int)} method on this DatagramSocket. - *

- * - * @return the traffic class or type-of-service already set - * @throws SocketException if there is an error obtaining the traffic class - * or type-of-service value - * @see DatagramSocket#getTrafficClass() - */ - @Override - public int getTrafficClass() - throws SocketException - { - return multiplexing.getTrafficClass(); - } - - /** - * Returns the binding state of the socket. - * - * @return true if the socket successfully bound to an address; - * otherwise, false - * @see DatagramSocket#isBound() - */ - @Override - public boolean isBound() - { - return multiplexing.isBound(); - } - - /** - * Returns whether the socket is closed or not. - * - * @return true if the socket has been closed; otherwise, - * false - * @see DatagramSocket#isClosed() - */ - @Override - public boolean isClosed() - { - return multiplexing.isClosed(); - } - - /** - * Returns the connection state of the socket. - * - * @return true if the socket successfully connected to a server; - * otherwise, false - * @see DatagramSocket#isConnected() - */ - @Override - public boolean isConnected() - { - return multiplexing.isConnected(); - } - /** * Receives a datagram packet from this socket. When this method returns, * the DatagramPacket's buffer is filled with the data received. @@ -466,161 +140,4 @@ public class MultiplexedDatagramSocket { multiplexing.receive(this, p); } - - /** - * 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. - *

- * If there is a security manager, and the socket is not currently connected - * to a remote address, this method first performs some security checks. - * First, if p.getAddress().isMulticastAddress() is true, this - * method calls the security manager's checkMulticast method with - * p.getAddress() as its argument. If the evaluation of that - * expression is false, this method instead calls the security - * manager's checkConnect method with arguments - * p.getAddress().getHostAddress() and p.getPort(). Each - * call to a security manager method could result in a - * SecurityException if the operation is not allowed. - *

- * - * @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 - { - multiplexing.send(p); - } - - /** - * Enables/disables SO_BROADCAST. - * - * @param on whether or not to have broadcast turned on - * @throws SocketException if there is an error in the underlying protocol, - * such as an UDP error - * @see DatagramSocket#setBroadcast(boolean) - */ - @Override - public void setBroadcast(boolean on) - throws SocketException - { - multiplexing.setBroadcast(on); - } - - /** - * Sets the SO_RCVBUF option to the specified value for this - * DatagramSocket. The SO_RCVBUF option is used by the - * network implementation as a hint to size the underlying network I/O - * buffers. The SO_RCVBUF setting may also be used by the network - * implementation to determine the maximum size of the packet that can be - * received on this socket. - *

- * Because SO_RCVBUF is a hint, applications that want to verify - * what size the buffers were set to should call - * {@link #getReceiveBufferSize()}. - *

- * - * @param size the size to which to set the receive buffer size. The value - * must be greater than zero - * @throws SocketException if there is an error in the underlying protocol, - * such as an UDP error - * @throws IllegalArgumentException if the value is zero or is negative - * @see DatagramSocket#setReceiveBufferSize(int) - */ - @Override - public void setReceiveBufferSize(int size) - throws SocketException - { - multiplexing.setReceiveBufferSize(size); - } - - /** - * Enables/disables the SO_REUSEADDR socket option. - * - * @param on whether to enable or disable the SO_REUSEADDR socket - * option - * @throws SocketException if an error occurs enabling or disabling the - * SO_RESUEADDR socket option, or the socket is closed - * @see DatagramSocket#setReuseAddress(boolean) - */ - @Override - public void setReuseAddress(boolean on) - throws SocketException - { - multiplexing.setReuseAddress(on); - } - - /** - * Sets the SO_SNDBUF option to the specified value for this - * DatagramSocket. The SO_SNDBUF option is used by the - * network implementation as a hint to size the underlying network I/O - * buffers. The SO_SNDBUF setting may also be used by the network - * implementation to determine the maximum size of the packet that can be - * sent on this socket. - *

- * As SO_SNDBUF is a hint, applications that want to verify what - * size the buffer is should call {@link #getSendBufferSize()}. - *

- *

- * Increasing the buffer size may allow multiple outgoing packets to be - * queued by the network implementation when the send rate is high. - *

- * - * @param size the size to which to set the send buffer size. The value must - * be greater than zero - * @throws SocketException if there is an error in the underlying protocol, - * such as an UDP error - * @throws IllegalArgumentException if the value is zero or is negative - * @see DatagramSocket#setSendBufferSize(int) - */ - @Override - public void setSendBufferSize(int size) - throws SocketException - { - multiplexing.setSendBufferSize(size); - } - - /** - * Enables/disables SO_TIMEOUT with the specified timeout, in - * milliseconds. With this option set to a non-zero timeout, a call to - * {@link #receive(DatagramPacket)} for this DatagramSocket will - * block for only this amount of time. If the timeout expires, a - * SocketTimeoutException is raised, though the - * DatagramSocket is still valid. The option must be enabled prior - * to entering the blocking operation to have effect. The timeout must be - * greater than zero. A timeout of zero is interpreted as an infinite - * timeout. - * - * @param timeout the specified timeout in milliseconds - * @throws SocketException if there is an error in the underlying protocol, - * such as an UDP error - * @see DatagramSocket#setSoTimeout(int) - */ - @Override - public void setSoTimeout(int timeout) - throws SocketException - { - multiplexing.setSoTimeout(timeout); - } - - /** - * Sets traffic class or type-of-service octet in the IP datagram header for - * datagrams sent from this DatagramSocket. As the underlying - * network implementation may ignore this value applications should consider - * it a hint. - * - * @param tc an int value for the bitset - * @throws SocketException if there is an error setting the traffic class or - * type-of-service - * @see DatagramSocket#setTrafficClass(int) - */ - @Override - public void setTrafficClass(int tc) - throws SocketException - { - multiplexing.setTrafficClass(tc); - } } diff --git a/src/org/ice4j/socket/MultiplexingDatagramSocket.java b/src/org/ice4j/socket/MultiplexingDatagramSocket.java index 3ba1cb4..dd97e37 100644 --- a/src/org/ice4j/socket/MultiplexingDatagramSocket.java +++ b/src/org/ice4j/socket/MultiplexingDatagramSocket.java @@ -10,6 +10,7 @@ package org.ice4j.socket; import java.io.*; import java.net.*; import java.util.*; +import java.util.logging.*; /** * Represents a DatagramSocket which allows filtering @@ -24,6 +25,13 @@ public class MultiplexingDatagramSocket extends SafeCloseDatagramSocket { + /** + * The Logger used by the MultiplexingDatagramSocket class + * and its instances for logging output. + */ + private static final Logger logger + = Logger.getLogger(MultiplexingDatagramSocket.class.getName()); + /** * The constant which represents an empty array with * MultiplexedDatagramSocket element type. Explicitly defined in @@ -84,23 +92,18 @@ public class MultiplexingDatagramSocket /** * Initializes a new MultiplexingDatagramSocket instance which is - * to enable DatagramPacket filtering, bound to the specified local - * socket address. - *

- * If the specified local socket address is null, creates an - * unbound socket. - *

+ * to enable DatagramPacket filtering on a specific + * DatagramSocket. * - * @param bindaddr local socket address to bind, or null for an - * unbound socket - * @throws SocketException if the socket could not be opened, or the socket - * could not bind to the specified local port - * @see DatagramSocket#DatagramSocket(SocketAddress) + * @param delegate the DatagramSocket on which + * DatagramPacket filtering is to be enabled by the new instance + * @throws SocketException if anything goes wrong while initializing the new + * instance */ - public MultiplexingDatagramSocket(SocketAddress bindaddr) + public MultiplexingDatagramSocket(DatagramSocket delegate) throws SocketException { - super(bindaddr); + super(delegate); } /** @@ -139,6 +142,27 @@ public class MultiplexingDatagramSocket super(port, laddr); } + /** + * Initializes a new MultiplexingDatagramSocket instance which is + * to enable DatagramPacket filtering, bound to the specified local + * socket address. + *

+ * If the specified local socket address is null, creates an + * unbound socket. + *

+ * + * @param bindaddr local socket address to bind, or null for an + * unbound socket + * @throws SocketException if the socket could not be opened, or the socket + * could not bind to the specified local port + * @see DatagramSocket#DatagramSocket(SocketAddress) + */ + public MultiplexingDatagramSocket(SocketAddress bindaddr) + throws SocketException + { + super(bindaddr); + } + /** * Initializes a new DatagramPacket instance which is a clone of a * specific DatagramPacket i.e. the properties of the clone @@ -149,20 +173,17 @@ public class MultiplexingDatagramSocket * @return a new DatagramPacket instance which is a clone of the * specified DatagramPacket */ - static DatagramPacket clone(DatagramPacket p) + public static DatagramPacket clone(DatagramPacket p) { synchronized (p) { byte[] pData = p.getData(); - byte[] cData = (pData == null) ? pData : pData.clone(); + byte[] cData = (pData == null) ? null : pData.clone(); return new DatagramPacket( - cData, - p.getOffset(), - p.getLength(), - p.getAddress(), - p.getPort()); + cData, p.getOffset(), p.getLength(), + p.getAddress(), p.getPort()); } } @@ -189,12 +210,9 @@ public class MultiplexingDatagramSocket = new MultiplexedDatagramSocket[socketCount - 1]; System.arraycopy(sockets, 0, newSockets, 0, i); - System - .arraycopy( - sockets, - i + 1, - newSockets, - i, + System.arraycopy( + sockets, i + 1, + newSockets, i, newSockets.length - i); sockets = newSockets; } @@ -212,13 +230,44 @@ public class MultiplexingDatagramSocket * @param dest the DatagramPacket which is to have its properties * set to the value of the respective properties of src */ - static void copy(DatagramPacket src, DatagramPacket dest) + public static void copy(DatagramPacket src, DatagramPacket dest) { synchronized (dest) { dest.setAddress(src.getAddress()); - dest.setData(src.getData(), src.getOffset(), src.getLength()); dest.setPort(src.getPort()); + + byte[] srcData = src.getData(); + + if (srcData == null) + dest.setLength(0); + else + { + byte[] destData = dest.getData(); + + if (destData == null) + dest.setLength(0); + else + { + int destOffset = dest.getOffset(); + int destLength = destData.length - destOffset; + int srcLength = src.getLength(); + + if (destLength > srcLength) + destLength = srcLength; + else if (logger.isLoggable(Level.WARNING)) + { + logger.log( + Level.WARNING, + "Truncating received DatagramPacket data!"); + } + System.arraycopy( + srcData, src.getOffset(), + destData, destOffset, + destLength); + dest.setLength(destLength); + } + } } } diff --git a/src/org/ice4j/socket/RelayedCandidateDatagramSocket.java b/src/org/ice4j/socket/RelayedCandidateDatagramSocket.java index 2817fc8..05ddba0 100644 --- a/src/org/ice4j/socket/RelayedCandidateDatagramSocket.java +++ b/src/org/ice4j/socket/RelayedCandidateDatagramSocket.java @@ -9,9 +9,18 @@ package org.ice4j.socket; import java.io.*; import java.net.*; +import java.util.*; +import java.util.logging.*; + +import org.ice4j.*; +import org.ice4j.attribute.*; +import org.ice4j.ice.*; +import org.ice4j.ice.harvest.*; +import org.ice4j.message.*; +import org.ice4j.stack.*; /** - * Represents an application-purposed (as opposed to a ICE-specific) + * Represents an application-purposed (as opposed to an ICE-specific) * DatagramSocket for a RelayedCandidate harvested by a * TurnCandidateHarvest (and its associated * TurnCandidateHarvester, of course). @@ -22,18 +31,104 @@ import java.net.*; * @author Lubomir Marinov */ public class RelayedCandidateDatagramSocket - extends SafeCloseDatagramSocket + extends DatagramSocket + implements MessageEventHandler { + /** - * Initializes a new RelayedCandidateDatagramSocket instance. + * The Logger used by the RelayedCandidateDatagramSocket + * class and its instances for logging output. + */ + private static final Logger logger + = Logger.getLogger(RelayedCandidateDatagramSocket.class.getName()); + + /** + * The lifetime in milliseconds of a TURN permission created using a + * CreatePermission request. + */ + private static final long PERMISSION_LIFETIME = 300 /* seconds */ * 1000L; + + /** + * The time in milliseconds before a TURN permission expires that a + * RelayedCandidateDatagramSocket is to try to reinstall it. + */ + private static final long PERMISSION_LIFETIME_LEEWAY + = 60 /* seconds */ * 1000L; + + /** + * The list of per-peer Channels through which this + * RelayedCandidateDatagramSockets relays data send to it to + * peer TransportAddresses. + */ + private final List channels = new LinkedList(); + + /** + * The indicator which determines whether this instance has started + * executing or has executed its {@link #close()} method. + */ + private boolean closed = false; + + /** + * The DatagramPackets which are to be received through this + * DatagramSocket upon calls to its + * {@link #receive(DatagramPacket)} method. They have been received from the + * TURN server in the form of Data indications. + */ + private final List packetsToReceive + = new LinkedList(); + + /** + * The DatagramSockets which have been sent through this + * DatagramSocket using its {@link #send(DatagramPacket)} method + * and which are to be relayed through its associated TURN server in the + * form of Send indications. + */ + private final List packetsToSend + = new LinkedList(); + + /** + * The RelayedCandidate which uses this instance as the value of + * its socket property. + */ + private final RelayedCandidate relayedCandidate; + + /** + * The Thread which is to send the {@link #packetsToSend} to the + * associated TURN server. + */ + private Thread sendThread; + + /** + * The TurnCandidateHarvest which has harvested + * {@link #relayedCandidate}. + */ + private final TurnCandidateHarvest turnCandidateHarvest; + + /** + * Initializes a new RelayedCandidateDatagramSocket instance which + * is to be the socket of a specific RelayedCandidate + * harvested by a specific TurnCandidateHarvest. * + * @param relayedCandidate the RelayedCandidate which is to use the + * new instance as the value of its socket property + * @param turnCandidateHarvest the TurnCandidateHarvest which has + * harvested relayedCandidate * @throws SocketException if anything goes wrong while initializing the new * RelayedCandidateDatagramSocket instance */ - public RelayedCandidateDatagramSocket() + public RelayedCandidateDatagramSocket( + RelayedCandidate relayedCandidate, + TurnCandidateHarvest turnCandidateHarvest) throws SocketException { - super(null /* bindaddr */); + super(/* bindaddr */ (SocketAddress) null); + + this.relayedCandidate = relayedCandidate; + this.turnCandidateHarvest = turnCandidateHarvest; + + this.turnCandidateHarvest.harvester.stunStack.addIndicationListener( + this.turnCandidateHarvest.hostCandidate.getTransportAddress(), + this); } /** @@ -44,7 +139,249 @@ public class RelayedCandidateDatagramSocket @Override public void close() { - // TODO Auto-generated method stub + synchronized (this) + { + if (this.closed) + return; + else + this.closed = true; + } + synchronized (packetsToReceive) + { + packetsToReceive.notifyAll(); + } + synchronized (packetsToSend) + { + packetsToSend.notifyAll(); + } + turnCandidateHarvest.harvester.stunStack.removeIndicationListener( + turnCandidateHarvest.hostCandidate.getTransportAddress(), + this); + turnCandidateHarvest.close(this); + } + + /** + * Creates {@link #sendThread} which is to send {@link #packetsToSend} to + * the associated TURN server. + */ + private void createSendThread() + { + synchronized (packetsToSend) + { + sendThread + = new Thread() + { + @Override + public void run() + { + try + { + runInSendThread(); + } + finally + { + synchronized (packetsToSend) + { + if (sendThread + == Thread.currentThread()) + sendThread = null; + if ((sendThread == null) + && !closed + && !packetsToSend.isEmpty()) + createSendThread(); + } + } + } + }; + sendThread.start(); + } + } + + /** + * Gets the local address to which the socket is bound. + * RelayedCandidateDatagramSocket returns the address of + * its localSocketAddress. + *

+ * 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. + * RelayedCandidateDatagram 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 + * RelayedCandidateDatagramSocket 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 RelayedCandidate getRelayedCandidate() + { + return relayedCandidate; + } + + /** + * Notifies this MessageEventHandler that a specific STUN message + * has been received, parsed and is ready for delivery. + * RelayedCandidateDatagramSocket 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) + { + /* + * Is it meant for us? (It should be because + * RelayedCandidateDatagramSocket registers for STUN indications + * received at the associated local TransportAddress only.) + */ + if (!turnCandidateHarvest.hostCandidate.getTransportAddress().equals( + e.getLocalAddress())) + return; + // Is it from our TURN server? + if (!turnCandidateHarvest.harvester.stunServer.equals( + e.getRemoteAddress())) + return; + + Message message = e.getMessage(); + char messageType = message.getMessageType(); + + if (messageType != Message.DATA_INDICATION) + return; + + /* + * RFC 5766: When the client receives a Data indication, it checks that + * the Data indication contains both an XOR-PEER-ADDRESS and a DATA + * attribute, and discards the indication if it does not. + */ + XorPeerAddressAttribute peerAddressAttribute + = (XorPeerAddressAttribute) + message.getAttribute(Attribute.XOR_PEER_ADDRESS); + + if (peerAddressAttribute == null) + return; + + DataAttribute dataAttribute + = (DataAttribute) message.getAttribute(Attribute.DATA); + + if (dataAttribute == null) + return; + + TransportAddress peerAddress + = peerAddressAttribute.getAddress(message.getTransactionID()); + + 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); +System.err.println( + getClass().getSimpleName() + + ".handleMessageEvent: packetToReceive.length= " + + packetToReceive.getLength()); + packetsToReceive.notifyAll(); + } + } + } + + /** + * Notifies this RelayedCandidateDatagramSocket 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) + { + if (request.getMessageType() == Message.CREATEPERMISSION_REQUEST) + setChannelBound(request, false); + return false; + } + + /** + * Notifies this RelayedCandidateDatagramSocket 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) + { + if (request.getMessageType() == Message.CREATEPERMISSION_REQUEST) + setChannelBound(request, true); } /** @@ -62,7 +399,182 @@ public class RelayedCandidateDatagramSocket public void receive(DatagramPacket p) throws IOException { - // TODO Auto-generated method stub + 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( + RelayedCandidateDatagramSocket.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; + } + } + } + } + + /** + * 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.get(packetToSendIndex); + + /* + * Get a channel to the peer which is to receive the + * packetToSend. + */ + int channelCount = channels.size(); + TransportAddress peerAddress + = new TransportAddress( + packetToSend.getAddress(), + packetToSend.getPort(), + Transport.UDP); + Channel channel = null; + + for (int channelIndex = 0; + channelIndex < channelCount; + channelIndex++) + { + Channel aChannel = channels.get(channelIndex); + + if (aChannel.peerAddressEquals(peerAddress)) + { + channel = aChannel; + break; + } + } + if (channel == null) + { + channel = new Channel(peerAddress); + channels.add(channel); + } + + /* + * Either bind the channel or send the packetToSend through + * it. + */ + if (channel.isBound()) + { + packetsToSend.remove(packetToSendIndex); + try + { + channel.send(packetToSend, peerAddress); + } + catch (StunException sex) + { + if (logger.isLoggable(Level.INFO)) + { + logger.log( + Level.INFO, + "Failed to send through " + + RelayedCandidateDatagramSocket + .class.getSimpleName() + + " channel." , + sex); + } + } + break; + } + else if (!channel.isBinding()) + { + try + { + channel.bind(); + } + catch (StunException sex) + { + if (logger.isLoggable(Level.INFO)) + { + logger.log( + Level.INFO, + "Failed to bind " + + RelayedCandidateDatagramSocket + .class.getSimpleName() + + " channel." , + sex); + } + /* + * Well, it may not be the fault of the packetToSend + * but it happened while we were trying to send it + * and we don't have a way to report an error so + * just drop packetToSend in order to change + * something and not just go again trying the same + * thing. + */ + packetsToSend.remove(packetToSendIndex); + break; + } + } + } + + /* + * 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) + { + } + } + } + } } /** @@ -78,6 +590,248 @@ public class RelayedCandidateDatagramSocket public void send(DatagramPacket p) throws IOException { - // TODO Auto-generated method stub + synchronized (packetsToSend) + { + if (closed) + { + throw + new IOException( + RelayedCandidateDatagramSocket.class.getSimpleName() + + " has been closed."); + } + else + { + packetsToSend.add(MultiplexingDatagramSocket.clone(p)); + + if (sendThread == null) + createSendThread(); + else + packetsToSend.notifyAll(); + } + } + } + + /** + * Sets the bound property of a Channel the installation + * of which has been attempted by sending a specific Request. + * + * @param request the Request which has been attempted in order to + * install a Channel + * @param bound true if the bound property of the + * Channel is to be set to true; otherwise, false + */ + private void setChannelBound(Request request, boolean bound) + { + XorPeerAddressAttribute peerAddressAttribute + = (XorPeerAddressAttribute) + request.getAttribute(Attribute.XOR_PEER_ADDRESS); + byte[] transactionID = request.getTransactionID(); + TransportAddress peerAddress + = peerAddressAttribute.getAddress(transactionID); + + synchronized (packetsToSend) + { + int channelCount = channels.size(); + + for (int channelIndex = 0; + channelIndex < channelCount; + channelIndex++) + { + Channel channel = channels.get(channelIndex); + + if (channel.peerAddressEquals(peerAddress)) + { + channel.setBound(bound, transactionID); + packetsToSend.notifyAll(); + break; + } + } + } + } + + /** + * Represents a channel which relays data sent through this + * RelayedCandidateDatagramSocket to a specific + * TransportAddress via the TURN server associated with this + * RelayedCandidateDatagramSocket. + */ + private class Channel + { + /** + * The time stamp in milliseconds at which {@link #bindingTransactionID} + * has been used to bind/install this Channel. + */ + private long bindingTimeStamp = -1; + + /** + * The ID of the transaction with which a CreatePermission + * Request has been sent to bind/install this Channel. + */ + private byte[] bindingTransactionID; + + /** + * The indication which determines whether a confirmation has been + * received that this Channel has been bound. + */ + private boolean bound = false; + + /** + * The TransportAddress of the peer to which this + * Channel provides a permission of this + * RelayedCandidateDatagramSocket to send data to. + */ + private final TransportAddress peerAddress; + + /** + * Initializes a new Channel instance which is to provide this + * RelayedCandidateDatagramSocket with a permission to send + * to a specific peer TransportAddress. + * + * @param peerAddress the TransportAddress of the peer to which + * the new instance is to provide a permission of this + * RelayedCandidateDatagramSocket to send data to + */ + public Channel(TransportAddress peerAddress) + { + this.peerAddress = peerAddress; + } + + /** + * Binds/installs this channel so that it provides this + * RelayedCandidateDatagramSocket with a permission to send + * data to the TransportAddress associated with this instance. + * + * @throws StunException if anything goes wrong while binding/installing + * this channel + */ + public void bind() + throws StunException + { + byte[] transactionID + = TransactionID.createNewTransactionID().getBytes(); + Request createPermissionRequest + = MessageFactory.createCreatePermissionRequest( + peerAddress, + transactionID); + + createPermissionRequest.setTransactionID(transactionID); + turnCandidateHarvest.sendRequest( + RelayedCandidateDatagramSocket.this, + createPermissionRequest); + + bindingTransactionID = transactionID; + bindingTimeStamp = System.currentTimeMillis(); + } + + /** + * Gets the indicator which determines whether this instance has started + * binding/installing itself and has not received a confirmation that it + * has succeeded in doing so yet. + * + * @return true if this instance has started binding/installing + * itself and has not received a confirmation that it has succeeded in + * doing so yet; otherwise, false + */ + public boolean isBinding() + { + return (bindingTransactionID != null); + } + + /** + * Gets the indication which determines whether this instance is + * currently considered bound/installed. + * + * @return true if this instance is currently considered + * bound/installed; otherwise, false + */ + public boolean isBound() + { + if ((bindingTimeStamp == -1) + || (bindingTimeStamp + + PERMISSION_LIFETIME + - PERMISSION_LIFETIME_LEEWAY) + < System.currentTimeMillis()) + return false; + return (bindingTransactionID == null) && bound; + } + + /** + * Determines whether the peerAddress property of this instance + * is considered by this Channel to be equal to a specific + * TransportAddress. + * + * @param peerAddress the TransportAddress which is to be + * checked for equality (as defined by this Channel and not + * necessarily by the TransportAddress class) + * @return true if the specified TransportAddress is + * considered by this Channel to be equal to its + * peerAddress property; otherwise, false + */ + public boolean peerAddressEquals(TransportAddress peerAddress) + { + return + this.peerAddress.getAddress().equals(peerAddress.getAddress()); + } + + /** + * Sends a specific DatagramPacket through this + * Channel to a specific peer TransportAddress. + * + * @param p the DatagramPacket to be sent + * @param peerAddress the TransportAddress of the peer to which + * the DatagramPacket is to be sent + * @throws StunException if anything goes wrong while sending the + * specified DatagramPacket to the specified peer + * TransportAddress + */ + public void send(DatagramPacket p, TransportAddress peerAddress) + throws StunException + { + byte[] pData = p.getData(); + int pOffset = p.getOffset(); + int pLength = p.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(); + Indication sendIndication + = MessageFactory.createSendIndication( + peerAddress, + data, + transactionID); + + sendIndication.setTransactionID(transactionID); + turnCandidateHarvest.harvester.stunStack.sendIndication( + sendIndication, + turnCandidateHarvest.harvester.stunServer, + turnCandidateHarvest.hostCandidate.getTransportAddress()); + } + + /** + * Sets the indicator which determines whether this Channel is + * bound/installed. + * + * @param bound true if this Channel is to be marked + * as bound/installed; otherwise, false + * @param boundTransactionID an array of bytes which represents + * the ID of the transaction with which the confirmation about the + * binding/installing has arrived + */ + public void setBound(boolean bound, byte[] boundTransactionID) + { + if (bindingTransactionID != null) + { + bindingTransactionID = null; + this.bound = bound; + } + } } } diff --git a/src/org/ice4j/socket/SafeCloseDatagramSocket.java b/src/org/ice4j/socket/SafeCloseDatagramSocket.java index 628bf70..8a57893 100644 --- a/src/org/ice4j/socket/SafeCloseDatagramSocket.java +++ b/src/org/ice4j/socket/SafeCloseDatagramSocket.java @@ -21,7 +21,7 @@ import java.net.*; * @author Lubomir Marinov */ public class SafeCloseDatagramSocket - extends DatagramSocket + extends DelegatingDatagramSocket { /** @@ -52,20 +52,19 @@ public class SafeCloseDatagramSocket } /** - * Creates a datagram socket, bound to the specified local socket address. - *

- * If, if the address is null, creates an unbound socket. - *

+ * Initializes a new SafeCloseDatagramSocket instance which to + * implement the DatagramSocket functionality by delegating to a + * specific DatagramSocket. * - * @param bindaddr local socket address to bind, or null for an - * unbound socket - * @throws SocketException if the socket could not be opened, or the socket - * could not bind to the specified local port + * @param delegate the DatagramSocket to which the new instance is + * to delegate + * @throws SocketException if anything goes wrong while initializing the new + * SafeCloseDatagramSocket instance */ - public SafeCloseDatagramSocket(SocketAddress bindaddr) + public SafeCloseDatagramSocket(DatagramSocket delegate) throws SocketException { - super(bindaddr); + super(delegate); } /** @@ -102,6 +101,23 @@ public class SafeCloseDatagramSocket super(port, laddr); } + /** + * Creates a datagram socket, bound to the specified local socket address. + *

+ * If, if the address is null, creates an unbound socket. + *

+ * + * @param bindaddr local socket address to bind, or null for an + * unbound socket + * @throws SocketException if the socket could not be opened, or the socket + * could not bind to the specified local port + */ + public SafeCloseDatagramSocket(SocketAddress bindaddr) + throws SocketException + { + super(bindaddr); + } + /** * Closes this datagram socket. *

diff --git a/src/org/ice4j/socket/TurnDatagramPacketFilter.java b/src/org/ice4j/socket/TurnDatagramPacketFilter.java index fd52ea4..1703212 100644 --- a/src/org/ice4j/socket/TurnDatagramPacketFilter.java +++ b/src/org/ice4j/socket/TurnDatagramPacketFilter.java @@ -101,6 +101,7 @@ public class TurnDatagramPacketFilter { case Message.TURN_METHOD_ALLOCATE: case Message.TURN_METHOD_CHANNELBIND: + case Message.TURN_METHOD_CREATEPERMISSION: case Message.TURN_METHOD_DATA: case Message.TURN_METHOD_REFRESH: case Message.TURN_METHOD_SEND: diff --git a/src/org/ice4j/stack/Connector.java b/src/org/ice4j/stack/Connector.java index 0b5ae26..941ecde 100644 --- a/src/org/ice4j/stack/Connector.java +++ b/src/org/ice4j/stack/Connector.java @@ -48,7 +48,7 @@ class Connector /** * A flag that is set to false to exit the message processor. */ - private boolean isRunning; + private boolean running; /** * The instance to be notified if errors occur in the network listening @@ -79,13 +79,12 @@ class Connector socket.getLocalPort(), Transport.UDP); } - /** * Start the network listening thread. */ void start() { - this.isRunning = true; + this.running = true; Thread thread = new Thread(this, "IceConnector@"+hashCode()); thread.setDaemon(true); thread.start(); @@ -107,46 +106,86 @@ class Connector */ public void run() { - while (this.isRunning) + DatagramPacket packet = null; + + while (this.running) { try { - int bufsize = sock.getReceiveBufferSize(); - byte message[] = new byte[bufsize]; - DatagramPacket packet = new DatagramPacket(message, bufsize); - DatagramSocket localSock; synchronized (sockLock) { - if (!isRunning) + if (!running) return; localSock = this.sock; } + /* + * Make sure localSock's receiveBufferSize is taken into + * account including after it gets changed. + */ + int receiveBufferSize = localSock.getReceiveBufferSize(); + + if (packet == null) + { + packet + = new DatagramPacket( + new byte[receiveBufferSize], + receiveBufferSize); + } + else + { + byte[] packetData = packet.getData(); + + if ((packetData == null) + || (packetData.length < receiveBufferSize)) + { + packet.setData( + new byte[receiveBufferSize], + 0, + receiveBufferSize); + } + else + { + /* + * XXX Tell the packet it is large enough because the + * socket will not look at the length of the data array + * property and will just respect the length property. + */ + packet.setLength(receiveBufferSize); + } + } + localSock.receive(packet); //get lost if we are no longer running. - if(!isRunning) + if(!running) return; logger.finest("received datagram"); - RawMessage rawMessage = new RawMessage( message, - packet.getLength(), - new TransportAddress( packet.getAddress(), - packet.getPort(), Transport.UDP), - listenAddress); + RawMessage rawMessage + = new RawMessage( + packet.getData(), + packet.getLength(), + new TransportAddress( + packet.getAddress(), + packet.getPort(), + Transport.UDP), + listenAddress); messageQueue.add(rawMessage); } catch (SocketException ex) { - if (isRunning) + if (running) { - logger.log(Level.WARNING, - "A connector died:", ex); + logger.log( + Level.WARNING, + "Connector died: " + listenAddress, + ex); stop(); //Something wrong has happened @@ -159,7 +198,7 @@ class Connector else { //The exception was most probably caused by calling - //this.stop() .... + //this.stop(). } } catch (IOException ex) @@ -192,7 +231,7 @@ class Connector { synchronized(sockLock) { - this.isRunning = false; + this.running = false; this.sock = null; } } @@ -221,11 +260,9 @@ class Connector @Override public String toString() { - return "ice4j.Connector@" - + listenAddress - +" status: " - + (isRunning? "not":"") - +" running"; + return + "ice4j.Connector@" + listenAddress + + " status: " + (running ? "not" : "") +" running"; } /** diff --git a/src/org/ice4j/stack/EventDispatcher.java b/src/org/ice4j/stack/EventDispatcher.java index 5ee661f..4482c73 100644 --- a/src/org/ice4j/stack/EventDispatcher.java +++ b/src/org/ice4j/stack/EventDispatcher.java @@ -9,7 +9,7 @@ package org.ice4j.stack; import java.util.*; import org.ice4j.*; - +import org.ice4j.message.*; /** * This is a utility class used for dispatching incoming request events. We use @@ -18,44 +18,109 @@ import org.ice4j.*; * NetAccessPoint only). * * @author Emil Ivov + * @author Lubomir Marinov */ public class EventDispatcher { /** - * All property change listeners registered so far. + * The STUN request and indication listeners registered with this + * EventDispatcher. */ - private final Vector requestListeners - = new Vector(); + private final List> messageListeners + = new Vector>(); /** - * Hashtable for managing property change listeners registered for specific - * properties. Maps property names to PropertyChangeSupport objects. + * The Map of EventDispatchers which keep the + * registrations of STUN request and indication listeners registered for + * STUN requests and indications from specific local + * TransportAddresses. */ - private final Hashtable - requestListenersChildren - = new Hashtable(); + private final Map children + = new Hashtable(); /** - * Constructs an EventDispatcher object. + * Initializes a new EventDispatcher instance. */ public 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 + * @param indicationListener the MessageEventHandler which is to be + * registered for notifications about STUN indications received at the + * specified local TransportAddress + */ + public void addIndicationListener( + TransportAddress localAddr, + MessageEventHandler indicationListener) + { + addMessageListener( + localAddr, + new IndicationEventHandler(indicationListener)); + } + + /** + * Registers a specific MessageTypeEventHandler for notifications + * about received STUN messages. + * + * @param messageListener the MessageTypeEventHandler which is to + * be registered for notifications about received STUN messages + */ + private synchronized void addMessageListener( + MessageTypeEventHandler messageListener) + { + synchronized(messageListeners) + { + if(!messageListeners.contains(messageListener)) + messageListeners.add(messageListener); + } + } + + /** + * Registers a specific MessageTypeEventHandler for notifications + * about STUN messages received at a specific local + * TransportAddress. + * + * @param localAddr the local TransportAddress STUN messages + * received at which are to be reported to the specified + * messageListener + * @param messageListener the MessageTypeEventHandler which is to + * be registered for notifications about STUN messages received at the + * specified local TransportAddress + */ + private synchronized void addMessageListener( + TransportAddress localAddr, + MessageTypeEventHandler messageListener) + { + synchronized(children) + { + EventDispatcher child = children.get(localAddr); + + if (child == null) + { + child = new EventDispatcher(); + children.put(localAddr, child); + } + child.addMessageListener(messageListener); + } + } + /** * Add a RequestListener to the listener list. The listener is registered * for requests coming from no matter which NetAccessPoint. * * @param listener The ReuqestListener to be added */ - public synchronized void addRequestListener(RequestListener listener) + public void addRequestListener(RequestListener listener) { - synchronized(requestListeners) - { - if(!requestListeners.contains(listener)) - requestListeners.addElement(listener); - } + addMessageListener(new RequestListenerMessageEventHandler(listener)); } /** @@ -66,19 +131,53 @@ public class EventDispatcher * @param localAddr The NETAP descriptor that we're interested in. * @param listener The ConfigurationChangeListener to be added */ - - public synchronized void addRequestListener( TransportAddress localAddr, - RequestListener listener) + public void addRequestListener( TransportAddress localAddr, + RequestListener listener) { - synchronized(requestListenersChildren) + addMessageListener( + localAddr, + new RequestListenerMessageEventHandler(listener)); + } + + /** + * Unregisters a specific MessageTypeEventHandler from + * notifications about received STUN messages. + * + * @param messageListener the MessageTypeEventHandler to be + * unregistered for notifications about received STUN messages + */ + private synchronized void removeMessageListener( + MessageTypeEventHandler messageListener) + { + synchronized(messageListeners) { - EventDispatcher child = requestListenersChildren.get(localAddr); + messageListeners.remove(messageListener); + } + } + + /** + * Unregisters a specific MessageTypeEventHandler from + * notifications about STUN messages received at a specific local + * TransportAddress. + * + * @param localAddr the local TransportAddress STUN messages + * received at which to no longer be reported to the specified + * messageListener + * @param messageListener the MessageTypeEventHandler to be + * unregistered for notifications about STUN messages received at the + * specified local TransportAddress + */ + private synchronized void removeMessageListener( + TransportAddress localAddr, + MessageTypeEventHandler messageListener) + { + synchronized(children) + { + EventDispatcher child = children.get( localAddr ); + if (child == null) - { - child = new EventDispatcher(); - requestListenersChildren.put(localAddr, child); - } - child.addRequestListener(listener); + return; + child.removeMessageListener(messageListener); } } @@ -90,13 +189,9 @@ public class EventDispatcher * * @param listener The RequestListener to be removed */ - public synchronized void removeRequestListener( - RequestListener listener) + public void removeRequestListener(RequestListener listener) { - synchronized(requestListeners) - { - requestListeners.removeElement(listener); - } + removeMessageListener(new RequestListenerMessageEventHandler(listener)); } /** @@ -107,19 +202,12 @@ public class EventDispatcher * @param localAddr The NetAPDescriptor that was listened on. * @param listener The RequestListener to be removed */ - public synchronized void removeRequestListener(TransportAddress localAddr, - RequestListener listener) + public void removeRequestListener(TransportAddress localAddr, + RequestListener listener) { - synchronized(requestListenersChildren) - { - EventDispatcher child = requestListenersChildren.get( localAddr ); - - if (child == null) - { - return; - } - child.removeRequestListener(listener); - } + removeMessageListener( + localAddr, + new RequestListenerMessageEventHandler(listener)); } @@ -130,29 +218,31 @@ public class EventDispatcher */ public void fireMessageEvent(StunMessageEvent evt) { - TransportAddress localAddr = evt.getLocalAddress(); - List listenersCopy = null; + MessageTypeEventHandler[] messageListenersCopy; - synchronized(requestListeners) + synchronized(messageListeners) { - listenersCopy - = new ArrayList(requestListeners); + messageListenersCopy + = messageListeners.toArray( + new MessageTypeEventHandler[ + messageListeners.size()]); } - for (RequestListener target : listenersCopy) + char messageType = (char) (evt.getMessage().getMessageType() & 0x0110); + + for (MessageTypeEventHandler messageListener : messageListenersCopy) { - target.processRequest(evt); + if (messageType == messageListener.messageType) + messageListener.handleMessageEvent(evt); } - synchronized(requestListenersChildren) + synchronized(children) { - EventDispatcher child = requestListenersChildren.get(localAddr); + EventDispatcher child = children.get(localAddr); if (child != null) - { child.fireMessageEvent(evt); - } } } @@ -166,24 +256,23 @@ public class EventDispatcher */ public boolean hasRequestListeners(TransportAddress localAddr) { - synchronized(requestListeners) + synchronized(messageListeners) { - if(!requestListeners.isEmpty()) + if(!messageListeners.isEmpty()) { // there is a generic listener return true; } } - synchronized(requestListenersChildren) + synchronized(children) { - if (!requestListenersChildren.isEmpty()) + if (!children.isEmpty()) { - EventDispatcher child = requestListenersChildren.get(localAddr); - if (child != null && child.requestListeners != null) - { - return !child.requestListeners.isEmpty(); - } + EventDispatcher child = children.get(localAddr); + + if (child != null) + return !child.messageListeners.isEmpty(); } } @@ -195,8 +284,143 @@ public class EventDispatcher */ public void removeAllListeners() { - if(requestListeners != null) - requestListeners.removeAllElements(); - requestListenersChildren.clear(); + messageListeners.clear(); + children.clear(); + } + + /** + * Implements MessageEventHandler for a + * MessageEventHandler which handles STUN indications. + * + * @author Lubomir Marinov + */ + private static class IndicationEventHandler + extends MessageTypeEventHandler + { + + /** + * Initializes a new IndicationEventHandler which is to + * implement MessageEventHandler for a specific + * MessageEventHandler which handles STUN indications. + * + * @param requestListener the RequestListener for which the new + * instance is to implement MessageEventHandler + */ + public IndicationEventHandler(MessageEventHandler indicationListener) + { + super(Message.STUN_INDICATION, indicationListener); + } + + /** + * Notifies this MessageEventHandler that a STUN message has + * been received, parsed and is ready for delivery. + * + * @param e a StunMessageEvent which encapsulates the STUN + * message to be handled + * @see MessageEventHandler#handleMessageEvent(StunMessageEvent) + */ + public void handleMessageEvent(StunMessageEvent e) + { + delegate.handleMessageEvent(e); + } + } + + /** + * Represents the base for providers of MessageEventHandler + * implementations to specific Objects. + * + * @author Lubomir Marinov + */ + private static abstract class MessageTypeEventHandler + implements MessageEventHandler + { + + /** + * The Object for which this instance implements + * MessageEventHandler. + */ + public final T delegate; + + /** + * The type of the STUN messages that this MessageEventHandler + * is interested in. + */ + public final char messageType; + + /** + * Initializes a new MessageTypeEventHandler which is to + * forward STUN messages with a specific type to a specific handler. + * + * @param messageType the type of the STUN messages that the new + * instance is to forward to the specified handler delegate + * @param delegate the handler to which the new instance is to forward + * STUN messages with the specified messageType + */ + public MessageTypeEventHandler(char messageType, T delegate) + { + if (delegate == null) + throw new NullPointerException("delegate"); + + this.messageType = messageType; + this.delegate = delegate; + } + + @Override + public boolean equals(Object obj) + { + if (this == obj) + return true; + if (!getClass().isInstance(obj)) + return false; + + MessageTypeEventHandler mteh = (MessageTypeEventHandler) obj; + + return + (messageType == mteh.messageType) + && delegate.equals(mteh.delegate); + } + + @Override + public int hashCode() + { + return (messageType | delegate.hashCode()); + } + } + + /** + * Implements MessageEventHandler for RequestListener. + * + * @author Lubomir Marinov + */ + private static class RequestListenerMessageEventHandler + extends MessageTypeEventHandler + { + + /** + * Initializes a new RequestListenerMessageEventHandler which + * is to implement MessageEventHandler for a specific + * RequestListener. + * + * @param requestListener the RequestListener for which the new + * instance is to implement MessageEventHandler + */ + public RequestListenerMessageEventHandler( + RequestListener requestListener) + { + super(Message.STUN_REQUEST, requestListener); + } + + /** + * Notifies this MessageEventHandler that a STUN message has + * been received, parsed and is ready for delivery. + * + * @param e a StunMessageEvent which encapsulates the STUN + * message to be handled + * @see MessageEventHandler#handleMessageEvent(StunMessageEvent) + */ + public void handleMessageEvent(StunMessageEvent e) + { + delegate.processRequest(e); + } } } diff --git a/src/org/ice4j/stack/RawMessage.java b/src/org/ice4j/stack/RawMessage.java index 6694630..c8bd7cd 100644 --- a/src/org/ice4j/stack/RawMessage.java +++ b/src/org/ice4j/stack/RawMessage.java @@ -55,12 +55,16 @@ public class RawMessage TransportAddress remoteAddress, TransportAddress localAddress) { - //... don't do a null check - let it throw an NP exception - - this.messageBytes = new byte[messageBytes.length]; + /* + * Let NullPointerException go out. + * + * The length of the array messgeBytes may be enormous while + * messageLength may be tiny so it does not make sense to clone + * messageBytes. + */ + this.messageBytes = new byte[messageLength]; + System.arraycopy(messageBytes, 0, this.messageBytes, 0, messageLength); this.messageLength = messageLength; - System.arraycopy(messageBytes, 0, this.messageBytes, - 0, messageBytes.length); this.localAddress = localAddress; this.remoteAddress = remoteAddress; } diff --git a/src/org/ice4j/stack/StunStack.java b/src/org/ice4j/stack/StunStack.java index 6f6b2d2..20f9c5a 100644 --- a/src/org/ice4j/stack/StunStack.java +++ b/src/org/ice4j/stack/StunStack.java @@ -24,6 +24,7 @@ import org.ice4j.security.*; * configure the stack. * * @author Emil Ivov + * @author Lubomir Marinov */ public class StunStack implements MessageEventHandler @@ -280,6 +281,57 @@ public class StunStack return netAccessManager; } + /** + * Sends a specific STUN Indication to a specific destination + * TransportAddress through a socket registered with this + * StunStack using a specific TransportAddress. + * + * @param indication the STUN Indication to be sent to the + * specified destination TransportAddress through the socket with + * the specified TransportAddress + * @param sendTo the TransportAddress of the destination to which + * the specified indication is to be sent + * @param sendThrough the TransportAddress of the socket registered + * with this StunStack through which the specified + * indication is to be sent + * @throws StunException if anything goes wrong while sending the specified + * indication to the destination sendTo through the socket + * identified by sendThrough + */ + public void sendIndication( + Indication indication, + TransportAddress sendTo, + TransportAddress sendThrough) + throws StunException + { + if (indication.getTransactionID() == null) + { + indication.setTransactionID( + TransactionID.createNewTransactionID().getBytes()); + } + + try + { + getNetAccessManager().sendMessage(indication, sendThrough, sendTo); + } + catch (IllegalArgumentException iaex) + { + throw + new StunException( + StunException.ILLEGAL_ARGUMENT, + "Failed to send STUN indication: " + indication, + iaex); + } + catch (IOException ioex) + { + throw + new StunException( + StunException.NETWORK_ERROR, + "Failed to send STUN indication: " + indication, + ioex); + } + } + /** * Sends the specified request through the specified access point, and * registers the specified ResponseCollector for later notification. @@ -427,6 +479,24 @@ public class StunStack } } + /** + * Adds a new MessageEventHandler which is to be notified about + * STUN indications received at a specific local TransportAddress. + * + * @param localAddr the TransportAddress of the local socket for + * which received STUN indications are to be reported to the specified + * MessageEventHandler + * @param indicationListener the MessageEventHandler which is to be + * registered for notifications about STUN indications received at the + * specified local TransportAddress + */ + public void addIndicationListener( + TransportAddress localAddr, + MessageEventHandler indicationListener) + { + eventDispatcher.addIndicationListener(localAddr, indicationListener); + } + /** * Sets the listener that should be notified when a new Request is received. * @param requestListener the listener interested in incoming requests. @@ -436,6 +506,24 @@ public class StunStack this.eventDispatcher.addRequestListener( requestListener ); } + /** + * Removes an existing MessageEventHandler to no longer be notified + * about STUN indications received at a specific local + * TransportAddress. + * + * @param localAddr the TransportAddress of the local socket for + * which received STUN indications are to no longer be reported to the + * specified MessageEventHandler + * @param indicationListener the MessageEventHandler which is to be + * unregistered for notifications about STUN indications received at the + * specified local TransportAddress + */ + public void removeIndicationListener( + TransportAddress localAddr, + MessageEventHandler indicationListener) + { + } + /** * Removes the specified listener from the local listener list. (If any * instances of this listener have been registered for a particular @@ -607,6 +695,11 @@ public class StunStack logger.fine("all tids in stock were" + clientTransactions); } } + // indication + else if (msg instanceof Indication) + { + eventDispatcher.fireMessageEvent(event); + } } /** diff --git a/test/test/Ice.java b/test/test/Ice.java index 9785fc4..bfac7a6 100644 --- a/test/test/Ice.java +++ b/test/test/Ice.java @@ -13,16 +13,27 @@ import java.util.*; import org.ice4j.*; import org.ice4j.ice.*; import org.ice4j.ice.harvest.*; +import org.ice4j.security.*; /** * Simple ice4j testing scenario. The sample application would create and start - * both agents and make one of them and make one of them run checks against the - * other. + * both agents and make one of them run checks against the other. * * @author Emil Ivov + * @author Lubomir Marinov */ public class Ice { + + /** + * The indicator which determines whether the Ice application (i.e. + * the run-sample Ant target) is to start connectivity establishment of the + * remote peer (in addition to the connectivity establishment of the local + * agent which is always started, of course). + */ + private static final boolean START_CONNECTIVITY_ESTABLISHMENT_OF_REMOTE_PEER + = true; + /** * Start time for debugging purposes. */ @@ -55,6 +66,9 @@ public class Ice localAgent.setRemoteUfrag(remotePeer.getLocalUfrag()); localAgent.setRemotePassword(remotePeer.getLocalPassword()); + if (START_CONNECTIVITY_ESTABLISHMENT_OF_REMOTE_PEER) + transferRemoteCandidates(remotePeer, localAgent); + remotePeer.setRemoteUfrag(localAgent.getLocalUfrag()); remotePeer.setRemotePassword(localAgent.getLocalPassword()); @@ -64,6 +78,9 @@ public class Ice localAgent.startConnectivityEstablishment(); + if (START_CONNECTIVITY_ESTABLISHMENT_OF_REMOTE_PEER) + remotePeer.startConnectivityEstablishment(); + System.out.println("Local audio clist:\n" + localAgent.getStream("audio").getCheckList()); @@ -95,9 +112,11 @@ public class Ice { long processingEndTime = System.currentTimeMillis(); - System.out.println("Agent entered the " + evt.getNewValue() - + " state."); - if(evt.getNewValue() == IceProcessingState.COMPLETED) + Object iceProcessingState = evt.getNewValue(); + + System.out.println( + "Agent entered the " + iceProcessingState + " state."); + if(iceProcessingState == IceProcessingState.COMPLETED) { System.out.println("Total ICE processing time: " + (processingEndTime - startTime) + "ms"); @@ -129,8 +148,8 @@ public class Ice System.out.println(stream.getCheckList()); } } - else if(evt.getNewValue() == IceProcessingState.TERMINATED - || evt.getNewValue() == IceProcessingState.FAILED) + else if(iceProcessingState == IceProcessingState.TERMINATED + || iceProcessingState == IceProcessingState.FAILED) { System.exit(0); } @@ -159,9 +178,7 @@ public class Ice if(remoteStream != null) transferRemoteCandidates(localStream, remoteStream); else - { localAgent.removeStream(localStream); - } } } @@ -187,9 +204,7 @@ public class Ice if(remoteComponent != null) transferRemoteCandidates(localComponent, remoteComponent); else - { localStream.removeComponent(localComponent); - } } } @@ -237,6 +252,7 @@ public class Ice { Agent agent = new Agent(); + // STUN StunCandidateHarvester stunHarv = new StunCandidateHarvester( new TransportAddress("sip-communicator.net", 3478, Transport.UDP)); StunCandidateHarvester stun6Harv = new StunCandidateHarvester( @@ -246,8 +262,25 @@ public class Ice agent.addCandidateHarvester(stunHarv); agent.addCandidateHarvester(stun6Harv); + // TURN + String[] hostnames + = new String[] + { + "130.79.90.150", + "2001:660:4701:1001:230:5ff:fe1a:805f" + }; + int port = 3478; + LongTermCredential longTermCredential + = new LongTermCredential("guest", "anonymouspower!!"); + + for (String hostname : hostnames) + agent.addCandidateHarvester( + new TurnCandidateHarvester( + new TransportAddress(hostname, port, Transport.UDP), + longTermCredential)); + createStream(rtpPort, "audio", agent); - //createStream(rtpPort + 2, "video", agent); +// createStream(rtpPort + 2, "video", agent); return agent; } @@ -287,15 +320,13 @@ public class Ice + (endTime - startTime) +" ms"); startTime = endTime; //rtcpComp - //agent.createComponent( - // stream, Transport.UDP, rtpPort + 1, rtpPort + 1, rtpPort + 101); +// agent.createComponent( +// stream, Transport.UDP, rtpPort + 1, rtpPort + 1, rtpPort + 101); - endTime = System.currentTimeMillis(); - System.out.println("RTCP Component created in " - + (endTime - startTime) +" ms"); +// endTime = System.currentTimeMillis(); +// System.out.println("RTCP Component created in " +// + (endTime - startTime) +" ms"); return stream; } - - }