From c4278af39ccd9eac73a0123cc6f696b1fef96459 Mon Sep 17 00:00:00 2001 From: emcho Date: Mon, 24 Jun 2013 21:06:31 +0000 Subject: [PATCH] Improves logging. Starts work on SDP utilities for use with SIP and WebRTC. Starts work on trickle ICE. --- src/org/ice4j/TransportAddress.java | 10 +- src/org/ice4j/ice/Agent.java | 104 +++-- src/org/ice4j/ice/Candidate.java | 26 +- src/org/ice4j/ice/CandidatePrioritizer.java | 91 ++++ src/org/ice4j/ice/Component.java | 99 ++--- src/org/ice4j/ice/TrickleCallback.java | 12 + src/org/ice4j/ice/UPNPCandidate.java | 3 +- .../ice4j/ice/harvest/CandidateHarvester.java | 8 +- .../ice/harvest/CandidateHarvesterSet.java | 243 ++--------- .../harvest/CandidateHarvesterSetElement.java | 142 +++++++ .../harvest/CandidateHarvesterSetTask.java | 109 +++++ .../ice4j/ice/harvest/HarvestingTimeStat.java | 4 +- .../ice/harvest/HostCandidateHarvester.java | 22 +- .../ice/harvest/StunCandidateHarvester.java | 25 +- src/org/ice4j/ice/harvest/UPNPHarvester.java | 2 +- src/org/ice4j/ice/sdp/CandidateAttribute.java | 153 +++++++ src/org/ice4j/ice/sdp/IceSdpUtils.java | 247 +++++++++++ .../ice4j/socket/RtcpDemuxPacketFilter.java | 40 ++ test/test/Ice.java | 26 +- test/test/IceDistributed.java | 4 + test/test/SdpUtils.java | 392 ------------------ 21 files changed, 1019 insertions(+), 743 deletions(-) create mode 100644 src/org/ice4j/ice/CandidatePrioritizer.java create mode 100644 src/org/ice4j/ice/TrickleCallback.java create mode 100644 src/org/ice4j/ice/harvest/CandidateHarvesterSetElement.java create mode 100644 src/org/ice4j/ice/harvest/CandidateHarvesterSetTask.java create mode 100644 src/org/ice4j/ice/sdp/CandidateAttribute.java create mode 100644 src/org/ice4j/ice/sdp/IceSdpUtils.java create mode 100644 src/org/ice4j/socket/RtcpDemuxPacketFilter.java delete mode 100644 test/test/SdpUtils.java diff --git a/src/org/ice4j/TransportAddress.java b/src/org/ice4j/TransportAddress.java index 230315d..38b846c 100644 --- a/src/org/ice4j/TransportAddress.java +++ b/src/org/ice4j/TransportAddress.java @@ -136,7 +136,15 @@ public class TransportAddress */ public String toString() { - return super.toString() + "/" + getTransport(); + StringBuilder bldr = new StringBuilder(getHostAddress()); + + if(isIPv6()) + bldr.insert(0, "[").append("]"); + + bldr.append(":").append(getPort()); + bldr.append("/").append(getTransport()); + + return bldr.toString(); } /** diff --git a/src/org/ice4j/ice/Agent.java b/src/org/ice4j/ice/Agent.java index d61ea17..8f0d91f 100644 --- a/src/org/ice4j/ice/Agent.java +++ b/src/org/ice4j/ice/Agent.java @@ -1,6 +1,6 @@ /* * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * Maintained by the SIP Communicator community (http://sip-communicator.org). + * Maintained by the Jitsi community (https://jitsi.org). * * Distributable under LGPL license. * See terms of license at gnu.org. @@ -218,11 +218,17 @@ public class Agent */ private int generation = 0; + /** + * Determines whether this agent should perform trickling. + */ + private boolean trickle = true; + /** * Indicates that ICE will be shutdown. */ private boolean shutdown = false; + /** * Creates an empty Agent with no streams, and no address. */ @@ -283,7 +289,7 @@ public class Agent */ public IceMediaStream createMediaStream(String mediaStreamName) { - logger.info("Create media stream for " + mediaStreamName); + logger.fine("Create media stream for " + mediaStreamName); IceMediaStream mediaStream = new IceMediaStream(Agent.this, mediaStreamName); @@ -302,7 +308,7 @@ public class Agent /** * Creates a new {@link Component} for the specified stream and - * allocates all local candidates that should belong to it. + * allocates potentially all local candidates that should belong to it. * * @param stream the {@link IceMediaStream} that the new {@link Component} * should belong to. @@ -344,8 +350,6 @@ public class Agent Component component = stream.createComponent(transport); - logger.info("Create component " + component.toShortString()); - gatherCandidates(component, preferredPort, minPort, maxPort); for(Candidate candidate : component.getLocalCandidates()) @@ -436,7 +440,7 @@ public class Agent logger.info("Gather candidates for component " + component.toShortString()); - this.startHarvesting(); + this.startHarvestTiming(); hostCandidateHarvester.harvest( component, @@ -452,33 +456,42 @@ public class Agent logger.fine("host candidate count: " + component.getLocalCandidateCount()); - //apply other harvesters here - harvesters.harvest(component); + //in case we are not trickling, apply other harvesters here + if(!isTrickling()) + harvesters.harvest(component); - this.stopHarvesting(); + this.stopHarvestTiming(); logger.info( - "End candidate harvest for all harvesters within " - + this.getTotalHarvestingTime() + " ms" - + ", component: " + component.getComponentID()); + "Harvest for " + component.toShortString() + " completed in " + + this.getTotalHarvestingTime() + " ms."); logger.fine("host+harvested candidate count: " + component.getLocalCandidateCount()); - computeFoundations(component); - - //make sure we compute priorities only after we have all candidates - component.prioritizeCandidates(); + //Emil: because of trickle we now compute foundations or priorities + // directly when adding candidates. This shouldn't change anything but + // there's no need to do it here again. + //computeFoundations(component); + //component.prioritizeCandidates(); //eliminate redundant candidates component.eliminateRedundantCandidates(); - logger.fine("host+harvested candidate count (after elimination): " + - component.getLocalCandidateCount()); - //select the candidate to put in the media line. component.selectDefaultCandidate(); } + /** + * Starts an asynchronous harvest across all components and reports newly + * discovered candidates to trickleCallback. + * + * @param trickleCallback + */ + public void startCandidateTrickle(TrickleCallback trickleCallback) + { + + } + /** * Initializes all stream check lists and begins the checks. */ @@ -886,6 +899,17 @@ public class Agent return ret; } + /** + * Returns the {@link FoundationsRegistry} this agent is using to assign + * candidate foundations. We use the FoundationsRegistry to keep + * track of the foundations we assign within a session (i.e. the entire life + * time of an Agent) + */ + public final FoundationsRegistry getFoundationsRegistry() + { + return foundationsRegistry; + } + /** * Returns the IceMediaStream with the specified name or * null if no such stream has been registered with this @@ -1280,8 +1304,7 @@ public class Agent * {@link org.ice4j.message.Request} contained the USE-CANDIDATE ICE * attribute. */ - protected void incomingCheckReceived( - TransportAddress remoteAddress, + protected void incomingCheckReceived(TransportAddress remoteAddress, TransportAddress localAddress, long priority, String remoteUFrag, @@ -2231,6 +2254,37 @@ public class Agent return null; } + /** + * Indicates whether this agent is currently set to trickle candidates + * rather than gathering them synchronously while components are being + * added. When trickling is turned on, the agent will only gather host + * addresses for newly added components. When trickling is off, all + * harvesting for a specific component will be executed when that component + * is being added. + * + * @return false if this agent is configured to perform all + * harvesting when components are being added and false otherwise. + */ + public boolean isTrickling() + { + return trickle; + } + + /** + * Determines whether this agent will trickle candidates rather than + * gather them synchronously while components are being added. When + * trickling is turned on, the agent will only gather host addresses for + * newly added components. When trickling is off, all harvesting for a + * specific component will be executed when that component is being added. + * + * @param trickle false if this agent is configured to perform all + * harvesting when components are being added and false otherwise. + */ + public void setTrickling(boolean trickle) + { + this.trickle = trickle; + } + /** * Returns the harvesting time (in ms) for the harvester given in parameter. @@ -2311,17 +2365,17 @@ public class Agent /** * Starts the harvesting timer. Called when the harvest begins. */ - public void startHarvesting() + public void startHarvestTiming() { - this.harvestingTimeStat.startHarvesting(); + this.harvestingTimeStat.startHarvestTiming(); } /** * Stops the harvesting timer. Called when the harvest ends. */ - public void stopHarvesting() + public void stopHarvestTiming() { - this.harvestingTimeStat.stopHarvesting(); + this.harvestingTimeStat.stopHarvestTiming(); } /** diff --git a/src/org/ice4j/ice/Candidate.java b/src/org/ice4j/ice/Candidate.java index 001f8bd..894d03c 100644 --- a/src/org/ice4j/ice/Candidate.java +++ b/src/org/ice4j/ice/Candidate.java @@ -28,6 +28,7 @@ import org.ice4j.*; */ public abstract class Candidate > + implements Comparable { /** * The transport address represented by this candidate. @@ -754,16 +755,16 @@ public abstract class Candidate return 30; if( getType() == CandidateType.SERVER_REFLEXIVE_CANDIDATE) - return 20; + return 10; if( getType() == CandidateType.HOST_CANDIDATE) { //prefer IPv4 as default since many servers would still freak out //when seeing IPv6 address. if(getTransportAddress().isIPv6()) - return 10; + return 20; else - return 15; + return 25; } //WTF? @@ -940,4 +941,21 @@ public abstract class Candidate return this.relatedCandidate; } -} + + /** + * Compares this Candidate with the specified one based on their + * priority and returns a negative integer, zero, or a positive integer if + * this Candidate has a lower, equal, or greater priority than the + * second. + * + * @param candidate the second Candidate to compare. + * + * @return a negative integer, zero, or a positive integer as the first + * Candidate has a lower, equal, or greater priority than the + * second. + */ + public int compareTo(T candidate) + { + return CandidatePrioritizer.compareCandidates(this, candidate); + } +} \ No newline at end of file diff --git a/src/org/ice4j/ice/CandidatePrioritizer.java b/src/org/ice4j/ice/CandidatePrioritizer.java new file mode 100644 index 0000000..38ce035 --- /dev/null +++ b/src/org/ice4j/ice/CandidatePrioritizer.java @@ -0,0 +1,91 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the SIP Communicator community (http://sip-communicator.org). + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.ice; + +import java.util.*; + +/** + * Compares candidates based on their priority. + * + * @author Emil Ivov + */ +class CandidatePrioritizer + implements Comparator> +{ + /** + * Compares the two Candidates based on their priority and + * returns a negative integer, zero, or a positive integer as the first + * Candidate has a lower, equal, or greater priority than the + * second. + * + * @param c1 the first Candidate to compare. + * @param c2 the second Candidate to compare. + * + * @return a negative integer, zero, or a positive integer as the first + * Candidate has a lower, equal, + * or greater priority than the + * second. + */ + public static int compareCandidates(Candidate c1, Candidate c2) + { + if (c1.getPriority() < c2.getPriority()) + return 1; + else if (c1.getPriority() == c2.getPriority()) + return 0; + else //if(c1.getPriority() > c2.getPriority()) + return -1; + } + + /** + * Compares the two Candidates based on their priority and + * returns a negative integer, zero, or a positive integer as the first + * Candidate has a lower, equal, or greater priority than the + * second. + * + * @param c1 the first Candidate to compare. + * @param c2 the second Candidate to compare. + * + * @return a negative integer, zero, or a positive integer as the first + * Candidate has a lower, equal, + * or greater priority than the + * second. + */ + public int compare(Candidate c1, Candidate c2) + { + return CandidatePrioritizer.compareCandidates(c1, c2); + } + + /** + * Indicates whether some other object is "equal to" this + * Comparator. This method must obey the general contract of + * Object.equals(Object). Additionally, this method can return + * true only if the specified Object is also a + * comparator and it imposes the same ordering as this comparator. Thus, + * comp1.equals(comp2) implies that + * sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2)) for + * every object reference o1 and o2.

+ *

+ * Note that it is always safe not to override + * Object.equals(Object). However, overriding this method may, + * in some cases, improve performance by allowing programs to determine + * that two distinct Comparators impose the same order. + * + * @param obj the reference object with which to compare. + * + * @return true only if the specified object is also + * a comparator and it imposes the same ordering as this + * comparator. + * + * @see Object#equals(Object) + * @see Object#hashCode() + */ + public boolean equals(Object obj) + { + return (obj instanceof CandidatePrioritizer); + } +} \ No newline at end of file diff --git a/src/org/ice4j/ice/Component.java b/src/org/ice4j/ice/Component.java index 57d5ce5..7749068 100644 --- a/src/org/ice4j/ice/Component.java +++ b/src/org/ice4j/ice/Component.java @@ -142,9 +142,27 @@ public class Component */ public void addLocalCandidate(LocalCandidate candidate) { + Agent agent = getParentStream().getParentAgent(); + + //assign foundation. + agent.getFoundationsRegistry().assignFoundation(candidate); + + //compute priority + CompatibilityMode compatibilityMode = getParentStream().getParentAgent() + .getCompatibilityMode(); + if(compatibilityMode == CompatibilityMode.GTALK) + { + candidate.computeGTalkPriority(); + } + else + { + candidate.computePriority(); + } + synchronized(localCandidates) { localCandidates.add(candidate); + Collections.sort(localCandidates); } } @@ -419,19 +437,6 @@ public class Component } } - /** - * Adds a list of local Candidates to this media-stream component. - * - * @param candidates a List of candidates to be added - */ - public void addLocalCandidates(List candidates) - { - synchronized(localCandidates) - { - localCandidates.addAll(candidates); - } - } - /** * Adds a List of remote Candidates as reported by a remote agent. * @@ -566,7 +571,7 @@ public class Component StringBuffer buff = new StringBuffer(parentStream.getName()); buff.append("."); - buff.append(componentID); + buff.append(getName()); return buff.toString(); } @@ -574,15 +579,20 @@ public class Component /** * Computes the priorities of all Candidates and then sorts them * accordingly. + * + * @Deprecated candidates are now being prioritized upon addition and + * calling this method is no longer necessary. */ protected void prioritizeCandidates() { synchronized(localCandidates) { - CompatibilityMode compat = getParentStream().getParentAgent(). - getCompatibilityMode(); + CompatibilityMode compat = getParentStream().getParentAgent() + .getCompatibilityMode(); + LocalCandidate[] candidates = new LocalCandidate[localCandidates.size()]; + localCandidates.toArray(candidates); //first compute the actual priorities @@ -608,63 +618,6 @@ public class Component } } - /** - * Compares candidates based on their priority. - */ - private static class CandidatePrioritizer - implements Comparator> - { - /** - * Compares the two Candidates based on their priority and - * returns a negative integer, zero, or a positive integer as the first - * Candidate has a lower, equal, or greater priority than the - * second. - * - * @param c1 the first Candidate to compare. - * @param c2 the second Candidate to compare. - * - * @return a negative integer, zero, or a positive integer as the first - * Candidate has a lower, equal, or greater priority than the - * second. - */ - public int compare(Candidate c1, Candidate c2) - { - if(c1.getPriority() < c2.getPriority()) - return 1; - else if(c1.getPriority() == c2.getPriority()) - return 0; - else //if(c1.getPriority() > c2.getPriority()) - return -1; - } - - /** - * Indicates whether some other object is "equal to" this - * Comparator. This method must obey the general contract of - * Object.equals(Object). Additionally, this method can return - * true only if the specified Object is also a - * comparator and it imposes the same ordering as this comparator. Thus, - * comp1.equals(comp2) implies that - * sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2)) for - * every object reference o1 and o2.

- * - * Note that it is always safe not to override - * Object.equals(Object). However, overriding this method may, - * in some cases, improve performance by allowing programs to determine - * that two distinct Comparators impose the same order. - * - * @param obj the reference object with which to compare. - * @return true only if the specified object is also - * a comparator and it imposes the same ordering as this - * comparator. - * @see java.lang.Object#equals(java.lang.Object) - * @see java.lang.Object#hashCode() - */ - public boolean equals(Object obj) - { - return (obj instanceof CandidatePrioritizer); - } - } - /** * Eliminates redundant candidates, removing them from the specified * component. A candidate is redundant if its transport address diff --git a/src/org/ice4j/ice/TrickleCallback.java b/src/org/ice4j/ice/TrickleCallback.java new file mode 100644 index 0000000..3fd43c5 --- /dev/null +++ b/src/org/ice4j/ice/TrickleCallback.java @@ -0,0 +1,12 @@ +package org.ice4j.ice; + +/** + * Created with IntelliJ IDEA. + * User: emcho + * Date: 24.06.13 + * Time: 22:56 + * To change this template use File | Settings | File Templates. + */ +public class TrickleCallback +{ +} diff --git a/src/org/ice4j/ice/UPNPCandidate.java b/src/org/ice4j/ice/UPNPCandidate.java index 10f49d7..80e8aed 100644 --- a/src/org/ice4j/ice/UPNPCandidate.java +++ b/src/org/ice4j/ice/UPNPCandidate.java @@ -40,8 +40,7 @@ public class UPNPCandidate LocalCandidate base, Component parentComponent, GatewayDevice device) { - super( - transportAddress, + super( transportAddress, parentComponent, CandidateType.SERVER_REFLEXIVE_CANDIDATE, CandidateExtendedType.UPNP_CANDIDATE, diff --git a/src/org/ice4j/ice/harvest/CandidateHarvester.java b/src/org/ice4j/ice/harvest/CandidateHarvester.java index 04c3d47..2bc0df6 100644 --- a/src/org/ice4j/ice/harvest/CandidateHarvester.java +++ b/src/org/ice4j/ice/harvest/CandidateHarvester.java @@ -47,17 +47,17 @@ public abstract class CandidateHarvester /** * Starts the harvesting timer. Called when the harvest begins. */ - public void startHarvesting() + public void startHarvestTiming() { - this.harvestingTimeStat.startHarvesting(); + this.harvestingTimeStat.startHarvestTiming(); } /** * Stops the harvesting timer. Called when the harvest ends. */ - public void stopHarvesting() + public void stopHarvestTiming() { - this.harvestingTimeStat.stopHarvesting(); + this.harvestingTimeStat.stopHarvestTiming(); } /** diff --git a/src/org/ice4j/ice/harvest/CandidateHarvesterSet.java b/src/org/ice4j/ice/harvest/CandidateHarvesterSet.java index 20ae4ba..8cc17ba 100644 --- a/src/org/ice4j/ice/harvest/CandidateHarvesterSet.java +++ b/src/org/ice4j/ice/harvest/CandidateHarvesterSet.java @@ -91,6 +91,7 @@ public class CandidateHarvesterSet } } + /** * Gathers candidate addresses for a specific Component using * specific CandidateHarvesters. @@ -107,89 +108,29 @@ public class CandidateHarvesterSet final Component component, ExecutorService executorService) { - /** - * Represents a task to be executed by the specified executorService and - * to call {@link CandidateHarvester#harvestComponent} on the specified - * harvesters. - */ - class CandidateHarvesterSetTask - implements Runnable - { - /** - * The CandidateHarvester on which - * {@link CandidateHarvester#harvest(Component)} is to be or is - * being called. - */ - private CandidateHarvesterSetElement harvester; - /** - * Initializes a new CandidateHarvesterSetTask which is to - * call {@link CandidateHarvester#harvest(Component)} on a specific - * harvester and then as many harvesters as possible. - * - * @param harvester the CandidateHarvester on which the - * new instance is to call - * CandidateHarvester#harvest(Component) first - */ - public CandidateHarvesterSetTask( - CandidateHarvesterSetElement harvester) - { - this.harvester = harvester; - } - - /** - * Gets the CandidateHarvester on which - * {@link CandidateHarvester#harvest(Component)} is being called. - * - * @return the CandidateHarvester on which - * CandidateHarvester#harvest(Component) is being called - */ - public CandidateHarvesterSetElement getHarvester() - { - return harvester; - } - - public void run() - { - while (true) - { - if (harvester.isEnabled()) - { - try - { - harvester.harvest(component); - } - catch (Throwable t) - { - logger.info( - "disabling harvester due to exception: " + - t.getLocalizedMessage()); - harvester.setEnabled(false); - - if (t instanceof ThreadDeath) - throw (ThreadDeath) t; - } - } - - /* - * CandidateHarvester#harvest(Component) has been called on - * the harvester and its success or failure has been noted. - * Now forget the harvester because any failure to continue - * execution is surely not its fault. - */ - harvester = null; - - synchronized (harvesters) - { - if (harvesters.hasNext()) - harvester = harvesters.next(); - else - break; - } - } - } - } + harvest(harvesters, + Arrays.asList(new Component[]{component}), + executorService); + } + /** + * Gathers candidate addresses for a specific Component using + * specific CandidateHarvesters. + * + * @param harvesters the CandidateHarvesters to gather candidate + * addresses for the specified Component + * @param components the Components to gather candidate addresses + * for. + * @param executorService the ExecutorService to schedule the + * execution of the gathering of candidate addresses performed by the + * specified harvesters + */ + private void harvest( + final Iterator harvesters, + final List components, + ExecutorService executorService) + { /* * Start asynchronously executing the * CandidateHarvester#harvest(Component) method of the harvesters. @@ -212,14 +153,25 @@ public class CandidateHarvesterSet else break; } + if (!harvester.isEnabled()) continue; - // Asynchronously start gathering candidates using the harvester. - CandidateHarvesterSetTask task - = new CandidateHarvesterSetTask(harvester); + List componentsCopy; - tasks.put(task, executorService.submit(task)); + synchronized (components) + { + componentsCopy = new ArrayList(components); + } + + for(Component component : componentsCopy) + { + // Asynchronously start gathering candidates using the harvester. + CandidateHarvesterSetTask task = new CandidateHarvesterSetTask( + harvester, component, harvesters); + + tasks.put(task, executorService.submit(task)); + } } /* @@ -253,6 +205,9 @@ public class CandidateHarvesterSet } catch (ExecutionException ee) { + CandidateHarvesterSetElement harvester + = task.getKey().getHarvester(); + /* * A problem appeared during the execution of the task. * CandidateHarvesterSetTask clears its harvester property @@ -260,12 +215,10 @@ public class CandidateHarvesterSet * appeared while working with a harvester. */ logger.info( - "disabling harvester due to ExecutionException: " + + "disabling harvester "+ harvester.getHarvester() + + " due to ExecutionException: " + ee.getLocalizedMessage()); - CandidateHarvesterSetElement harvester - = task.getKey().getHarvester(); - if (harvester != null) harvester.setEnabled(false); break; @@ -319,7 +272,7 @@ public class CandidateHarvesterSet public CandidateHarvester next() throws NoSuchElementException { - return elementIter.next().harvester; + return elementIter.next().getHarvester(); } /** @@ -362,114 +315,4 @@ public class CandidateHarvesterSet return elements.size(); } } - - /** - * Represents a CandidateHarvester as an element in a - * CandidateHarvesterSet. - */ - private static class CandidateHarvesterSetElement - { - /** - * The indicator which determines whether - * {@link CandidateHarvester#harvest(Component)} is to be called on - * {@link #harvester}. - */ - private boolean enabled = true; - - /** - * The CandidateHarvester which is an element in a - * CandidateHarvesterSet. - */ - private final CandidateHarvester harvester; - - /** - * Initializes a new CandidateHarvesterSetElement instance - * which is to represent a specific CandidateHarvester as an - * element in a CandidateHarvesterSet. - * - * @param harvester the CandidateHarvester which is to be - * represented as an element in a CandidateHarvesterSet by the - * new instance - */ - public CandidateHarvesterSetElement(CandidateHarvester harvester) - { - this.harvester = harvester; - } - - /** - * Calls {@link CandidateHarvester#harvest(Component)} on the associated - * CandidateHarvester if enabled. - * - * @param component the Component to gather candidates for - */ - public void harvest(Component component) - { - if (isEnabled()) - { - harvester.startHarvesting(); - Collection candidates - = harvester.harvest(component); - harvester.stopHarvesting(); - - logger.info( - "End candidate harvest within " - + harvester.getHarvestingTime() - + " ms, for " - + harvester.getClass().getName() - + ", component: " + component.getComponentID()); - - /* - * If the CandidateHarvester has not gathered any candidates, it - * is considered failed and will not be used again in order to - * not risk it slowing down the overall harvesting. - */ - if ((candidates == null) || candidates.isEmpty()) - setEnabled(false); - } - } - - /** - * Determines whether the associated CandidateHarvester is - * considered to be the same as a specific CandidateHarvester. - * - * @param harvester the CandidateHarvester to be compared to - * the associated CandidateHarvester - * @return true if the associated CandidateHarvester - * is considered to be the same as the specified harvester; - * otherwise, false - */ - public boolean harvesterEquals(CandidateHarvester harvester) - { - return this.harvester.equals(harvester); - } - - /** - * Gets the indicator which determines whether - * {@link CandidateHarvester#harvest(Component)} is to be called on the - * associated CandidateHarvester. - * - * @return true if - * CandidateHarvester#harvest(Component) is to be called on the - * associated CandidateHarvester; otherwise, false - */ - public boolean isEnabled() - { - return enabled; - } - - /** - * Sets the indicator which determines whether - * {@link CandidateHarvester#harvest(Component)} is to be called on the - * associated CandidateHarvester. - * - * @param enabled true if - * CandidateHarvester#harvest(Component) is to be called on the - * associated CandidateHarvester; otherwise, false - */ - public void setEnabled(boolean enabled) - { - logger.info("disabling harvester: " + harvester); - this.enabled = enabled; - } - } } diff --git a/src/org/ice4j/ice/harvest/CandidateHarvesterSetElement.java b/src/org/ice4j/ice/harvest/CandidateHarvesterSetElement.java new file mode 100644 index 0000000..559720d --- /dev/null +++ b/src/org/ice4j/ice/harvest/CandidateHarvesterSetElement.java @@ -0,0 +1,142 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the SIP Communicator community (http://sip-communicator.org). + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.ice.harvest; + +import org.ice4j.ice.*; + +import java.util.*; +import java.util.logging.*; + +/** + * Represents a CandidateHarvester as an element in a + * CandidateHarvesterSet. + * + * @author Lyubomir Marinov + * @author Emil Ivov + */ +class CandidateHarvesterSetElement +{ + /** + * The Logger used by the CandidateHarvesterSetElement + * class and its instances for logging output. + */ + private static final Logger logger + = Logger.getLogger(CandidateHarvesterSetElement.class.getName()); + + /** + * The indicator which determines whether + * {@link CandidateHarvester#harvest(org.ice4j.ice.Component)} is to be + * called on {@link #harvester}. + */ + private boolean enabled = true; + + /** + * The CandidateHarvester which is an element in a + * CandidateHarvesterSet. + */ + private final CandidateHarvester harvester; + + /** + * Initializes a new CandidateHarvesterSetElement instance + * which is to represent a specific CandidateHarvester as an + * element in a CandidateHarvesterSet. + * + * @param harvester the CandidateHarvester which is to be + * represented as an element in a CandidateHarvesterSet by the + * new instance + */ + public CandidateHarvesterSetElement(CandidateHarvester harvester) + { + this.harvester = harvester; + } + + /** + * Calls {@link CandidateHarvester#harvest(org.ice4j.ice.Component)} on the + * associated CandidateHarvester if enabled. + * + * @param component the Component to gather candidates for + */ + public void harvest(Component component) + { + if (isEnabled()) + { + harvester.startHarvestTiming(); + Collection candidates + = harvester.harvest(component); + harvester.stopHarvestTiming(); + + logger.info( + "Completed " + component.getParentStream().getName() + + "." + component.getName() + + " harvest with " + harvester.toString() + " in " + + harvester.getHarvestingTime() + + " ms. Candidates found: " + candidates.size()); + /* + * If the CandidateHarvester has not gathered any candidates, it + * is considered failed and will not be used again in order to + * not risk it slowing down the overall harvesting. + */ + if ((candidates == null) || candidates.isEmpty()) + setEnabled(false); + } + } + + /** + * Determines whether the associated CandidateHarvester is + * considered to be the same as a specific CandidateHarvester. + * + * @param harvester the CandidateHarvester to be compared to + * the associated CandidateHarvester + * @return true if the associated CandidateHarvester + * is considered to be the same as the specified harvester; + * otherwise, false + */ + public boolean harvesterEquals(CandidateHarvester harvester) + { + return this.harvester.equals(harvester); + } + + /** + * Gets the indicator which determines whether + * {@link CandidateHarvester#harvest(Component)} is to be called on the + * associated CandidateHarvester. + * + * @return true if + * CandidateHarvester#harvest(Component) is to be called on the + * associated CandidateHarvester; otherwise, false + */ + public boolean isEnabled() + { + return enabled; + } + + /** + * Sets the indicator which determines whether + * {@link CandidateHarvester#harvest(Component)} is to be called on the + * associated CandidateHarvester. + * + * @param enabled true if + * CandidateHarvester#harvest(Component) is to be called on the + * associated CandidateHarvester; otherwise, false + */ + public void setEnabled(boolean enabled) + { + logger.info("Disabling: " + harvester); + this.enabled = enabled; + } + + /** + * Returns the CandidateHarvester encapsulated by this element. + * + * @return the CandidateHarvester encapsulated by this element. + */ + public CandidateHarvester getHarvester() + { + return harvester; + } +} \ No newline at end of file diff --git a/src/org/ice4j/ice/harvest/CandidateHarvesterSetTask.java b/src/org/ice4j/ice/harvest/CandidateHarvesterSetTask.java new file mode 100644 index 0000000..966ff40 --- /dev/null +++ b/src/org/ice4j/ice/harvest/CandidateHarvesterSetTask.java @@ -0,0 +1,109 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the SIP Communicator community (http://sip-communicator.org). + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.ice.harvest; + +import org.ice4j.ice.*; + +import java.util.logging.*; + +/** + * Represents a task to be executed by the specified executorService and + * to call {@link CandidateHarvester#harvest(Component)} on the specified + * harvesters. + * + * @author Lyubomir Marinov + * @author Emil Ivov + */ +class CandidateHarvesterSetTask + implements Runnable +{ + /** + * The Logger used by the CandidateHarvesterSetTask + * class and its instances for logging output. + */ + private static final Logger logger + = Logger.getLogger(CandidateHarvesterSetTask.class.getName()); + + /** + * The CandidateHarvester on which + * {@link CandidateHarvester#harvest(org.ice4j.ice.Component)} is to be or + * is being called. + */ + private CandidateHarvesterSetElement harvester; + + /** + * The {@link Component} whose addresses we will be harvesting in this task. + */ + private Component component; + + /** + * Initializes a new CandidateHarvesterSetTask which is to + * call {@link CandidateHarvester#harvest(org.ice4j.ice.Component)} on a + * specific harvester and then as many harvesters as possible. + * + * @param harvester the CandidateHarvester on which the + * new instance is to call + * CandidateHarvester#harvest(Component) first + */ + + java.util.Iterator harvesters; + public CandidateHarvesterSetTask( + CandidateHarvesterSetElement harvester, + Component component, + java.util.Iterator harvesters) + { + this.harvester = harvester; + this.component = component; + this.harvesters = harvesters; + } + + /** + * Gets the CandidateHarvester on which + * {@link CandidateHarvester#harvest(org.ice4j.ice.Component)} is being + * called. + * + * @return the CandidateHarvester on which + * CandidateHarvester#harvest(Component) is being called + */ + public CandidateHarvesterSetElement getHarvester() + { + return harvester; + } + + /** + * Runs the actual harvesting for this component + */ + public void run() + { + if (harvester.isEnabled()) + { + try + { + harvester.harvest(component); + } + catch (Throwable t) + { + logger.info( + "disabling harvester due to exception: " + + t.getLocalizedMessage()); + harvester.setEnabled(false); + + if (t instanceof ThreadDeath) + throw (ThreadDeath) t; + } + } + + /* + * CandidateHarvester#harvest(Component) has been called on + * the harvester and its success or failure has been noted. + * Now forget the harvester because any failure to continue + * execution is surely not its fault. + */ + harvester = null; + } +} diff --git a/src/org/ice4j/ice/harvest/HarvestingTimeStat.java b/src/org/ice4j/ice/harvest/HarvestingTimeStat.java index 0f21a23..626ef25 100644 --- a/src/org/ice4j/ice/harvest/HarvestingTimeStat.java +++ b/src/org/ice4j/ice/harvest/HarvestingTimeStat.java @@ -34,7 +34,7 @@ public class HarvestingTimeStat /** * Starts the harvesting timer. Called when the harvest begins. */ - public void startHarvesting() + public void startHarvestTiming() { ++nbHarvesting; // Remember the start date of this harvester. @@ -44,7 +44,7 @@ public class HarvestingTimeStat /** * Stops the harvesting timer. Called when the harvest ends. */ - public void stopHarvesting() + public void stopHarvestTiming() { // Remember the last harvesting time. this.lastHarvestingTime = this.getHarvestingTime(); diff --git a/src/org/ice4j/ice/harvest/HostCandidateHarvester.java b/src/org/ice4j/ice/harvest/HostCandidateHarvester.java index 2281024..eb3e8f6 100644 --- a/src/org/ice4j/ice/harvest/HostCandidateHarvester.java +++ b/src/org/ice4j/ice/harvest/HostCandidateHarvester.java @@ -69,7 +69,7 @@ public class HostCandidateHarvester throws IllegalArgumentException, IOException { - this.startHarvesting(); + this.startHarvestTiming(); Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); @@ -177,13 +177,11 @@ public class HostCandidateHarvester + " maxPort=" + maxPort); } - this.stopHarvesting(); + this.stopHarvestTiming(); logger.info( - "End candidate harvest within " - + this.getHarvestingTime() - + " ms, for " - + this.getClass().getName() - + ", component: " + component.getComponentID()); + "Completed " + component.toShortString() + " harvest with " + + getClass().getSimpleName() + " in " + getHarvestingTime() + + " ms. Candidates found: " + component.getLocalCandidateCount()); } /** @@ -334,7 +332,7 @@ public class HostCandidateHarvester + " address " + laddr + " and port " + port + " (" + se.getMessage() +")"); - logger.log(Level.INFO, "", se); + logger.log(Level.FINEST, "", se); } port ++; @@ -410,17 +408,17 @@ public class HostCandidateHarvester /** * Starts the harvesting timer. Called when the harvest begins. */ - public void startHarvesting() + public void startHarvestTiming() { - this.harvestingTimeStat.startHarvesting(); + this.harvestingTimeStat.startHarvestTiming(); } /** * Stops the harvesting timer. Called when the harvest ends. */ - public void stopHarvesting() + public void stopHarvestTiming() { - this.harvestingTimeStat.stopHarvesting(); + this.harvestingTimeStat.stopHarvestTiming(); } /** diff --git a/src/org/ice4j/ice/harvest/StunCandidateHarvester.java b/src/org/ice4j/ice/harvest/StunCandidateHarvester.java index 14722ba..816db78 100644 --- a/src/org/ice4j/ice/harvest/StunCandidateHarvester.java +++ b/src/org/ice4j/ice/harvest/StunCandidateHarvester.java @@ -226,9 +226,8 @@ public class StunCandidateHarvester */ public Collection harvest(Component component) { - logger.fine("invoked harvest / stream.component: " + toString() + " / " - + component.getParentStream().getName() + " / " + - component.getComponentID()); + logger.fine("starting " + component.toShortString() + + " harvest for: " + toString() ); stunStack = component.getParentStream().getParentAgent().getStunStack(); for (Candidate cand : component.getLocalCandidates()) @@ -257,29 +256,17 @@ public class StunCandidateHarvester if (completedHarvestCandidates != null) { - logger.fine("harvest / stream.component: " + toString() + - " / " + component.getParentStream().getName() + " / " + - component.getComponentID() + - ": completedHarvestCandidates element count: " + - completedHarvests.size()); - if(completedHarvestCandidates.length != 0) { candidates.addAll( Arrays.asList(completedHarvestCandidates)); } } - else - logger.fine("harvest / stream.component: " + toString() + - " / " + component.getParentStream().getName() + " / " + - component.getComponentID() + - ": completedHarvestCandidates == null"); } } - logger.info("harvest / stream.component: " + toString() + " / " - + component.getParentStream().getName() + " / " + - component.getComponentID() + - "found " + candidates.size() + " candidates."); + logger.finest( + "Completed " + component.toShortString() + " harvest: " + toString() + + ". Found " + candidates.size() + " candidates."); return candidates; } @@ -390,7 +377,7 @@ public class StunCandidateHarvester String proto = (this instanceof TurnCandidateHarvester) ? "TURN" : "STUN"; - return proto + " harvester for srvr: " + this.stunServer; + return proto + " harvester(srvr: " + this.stunServer + ")"; } /** diff --git a/src/org/ice4j/ice/harvest/UPNPHarvester.java b/src/org/ice4j/ice/harvest/UPNPHarvester.java index 41c05a3..a0c5380 100644 --- a/src/org/ice4j/ice/harvest/UPNPHarvester.java +++ b/src/org/ice4j/ice/harvest/UPNPHarvester.java @@ -143,7 +143,7 @@ public class UPNPHarvester port, localAddress.getHostAddress(), "UDP", - "Ice4J: " + port)) + "ice4j.org: " + port)) { List cands = createUPNPCandidate(socket, localAddress, externalIPAddress, externalPort, diff --git a/src/org/ice4j/ice/sdp/CandidateAttribute.java b/src/org/ice4j/ice/sdp/CandidateAttribute.java new file mode 100644 index 0000000..35943de --- /dev/null +++ b/src/org/ice4j/ice/sdp/CandidateAttribute.java @@ -0,0 +1,153 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the Jitsi community (https://jitsi.org). + * + * Distributable under LGPL license. See terms of license at gnu.org. + */ +package org.ice4j.ice.sdp; + +import gov.nist.core.*; +import gov.nist.javax.sdp.fields.*; +import org.ice4j.*; +import org.ice4j.ice.*; + +import javax.sdp.*; + +public class CandidateAttribute extends AttributeField +{ + /** + * The SDP name of candidate attributes. + */ + public static final String NAME = "candidate"; + + /** + * This class's serial version uid. + */ + private static final long serialVersionUID = 1L; + + /** + * The Candidate that we will be encapsulating. + */ + private final Candidate candidate; + + /** + * Creates an attribute instance + * + * @param candidate the Candidate + */ + public CandidateAttribute(Candidate candidate) + { + this.candidate = candidate; + } + + /** + * Returns the name of this attribute + * + * @return a String identity. + */ + public String getName() + { + return NAME; + } + + /** + * Does nothing . + * + * @param name ignored. + */ + public void setName(String name) + { + } + + /** + * Always returns true as this attribute always has a value. + * + * @return true if the attribute has a value. + */ + public boolean hasValue() + { + return true; + } + + ; + + /** + * Returns the value of this attribute. + * + * @return the value + */ + public String getValue() + { + StringBuffer buff = new StringBuffer(); + + buff.append(candidate.getFoundation()); + buff.append(" ").append( + candidate.getParentComponent().getComponentID()); + buff.append(" ").append(candidate.getTransport()); + buff.append(" ").append(candidate.getPriority()); + buff.append(" ").append( + candidate.getTransportAddress().getHostAddress()); + buff.append(" ").append( + candidate.getTransportAddress().getPort()); + buff.append(" typ ").append( + candidate.getType()); + + TransportAddress relAddr = candidate.getRelatedAddress(); + + if (relAddr != null) + { + buff.append(" raddr ").append(relAddr.getHostAddress()); + buff.append(" rport ").append(relAddr.getPort()); + } + + return buff.toString(); + } + + /** + * Parses the value of this attribute. + * + * @param value the - attribute value + * + * @throws javax.sdp.SdpException if there's a problem with the value + * String. + */ + public void setValue(String value) throws + SdpException + { + + } + + /** + * Returns the type character for the field. + * + * @return the type character for the field. + */ + public char getTypeChar() + { + return 'a'; + } + + /** + * Returns a reference to this attribute. + * + * @return a reference to this attribute. + */ + public CandidateAttribute clone() + { + return null; + } + + /** + * Returns the string encoded version of this object + * + * @return the string encoded version of this object + */ + public String encode() + { + StringBuffer sbuff = new StringBuffer(ATTRIBUTE_FIELD); + sbuff.append(getName()).append(Separators.COLON); + sbuff.append(getValue()); + return sbuff.append(Separators.NEWLINE).toString(); + } + +} \ No newline at end of file diff --git a/src/org/ice4j/ice/sdp/IceSdpUtils.java b/src/org/ice4j/ice/sdp/IceSdpUtils.java new file mode 100644 index 0000000..66ed19c --- /dev/null +++ b/src/org/ice4j/ice/sdp/IceSdpUtils.java @@ -0,0 +1,247 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the Jitsi community (https://jitsi.org). + * + * Distributable under LGPL license. See terms of license at gnu.org. + */ +package org.ice4j.ice.sdp; + +import gov.nist.javax.sdp.fields.*; +import org.ice4j.*; +import org.ice4j.ice.*; + +import javax.sdp.*; +import java.util.*; +import java.util.logging.*; + +/** + * A number of utility methods that WebRTC or SIP applications may find useful + * in case they are also fine with using jain-sdp + * + * @author Emil Ivov + */ +public class IceSdpUtils +{ + /** + * The name of the SDP attribute that contains an ICE user fragment. + */ + public static final String ICE_UFRAG = "ice-ufrag"; + + /** + * The name of the SDP attribute that contains an ICE password. + */ + public static final String ICE_PWD = "ice-pwd"; + + /** + * The name of the SDP attribute that contains an ICE options. + */ + public static final String ICE_OPTIONS = "ice-options"; + + /** + * The name of the ICE SDP option that indicates support for trickle. + */ + public static final String ICE_OPTION_TRICKLE = "trickle"; + + /** + * A reference to the currently valid SDP factory instance. + */ + private static final SdpFactory sdpFactory = SdpFactory.getInstance(); + + /** + * The Logger used by the IceSdpUtils + * class and its instances for logging output. + */ + private static final Logger logger + = Logger.getLogger(IceSdpUtils.class.getName()); + + /** + * Sets the specified ICE user fragment and password as attributes of the + * specified session description. + * + * @param sDes the session description where we'd like to set a user + * fragment and a password. + * @param uFrag the ICE user name fragment that we'd like to set on the + * session description + * @param pwd the ICE password that we'd like to set on the session + * description + * + * @throws NullPointerException if the either of the parameters is null + */ + @SuppressWarnings("unchecked") // SDP legacy + public static void setIceCredentials(SessionDescription sDes, + String uFrag, + String pwd) + throws NullPointerException + { + if (sDes == null || uFrag == null || pwd == null) + { + throw new NullPointerException( + "sDes, uFrag and pwd, cannot be null"); + } + + try + { + Vector sessionAttributes = sDes.getAttributes(true); + + //ice u-frag and password + sessionAttributes.add(sdpFactory.createAttribute(ICE_UFRAG, uFrag)); + sessionAttributes.add(sdpFactory.createAttribute(ICE_PWD, pwd)); + + sDes.setAttributes(sessionAttributes); + } + catch (Exception cause) + { + // this is very unlikely to happen but we should still log. + // Just in case. + logger.log(Level.INFO, + "Failed to set ICE credentials for some weird reason", + cause); + } + } + + /** + * Reflects the candidates from the various components in + * iceMediaStream into the specified m-line. Also sets default + * candidates into m= lines and c= lines. This method uses media level + * c= lines. They override session level making them pointless. This + * shouldn't be causing problems, but for good taste, make sure you don't + * include session level ones and avoid duplication. + * + * @param mediaDescription the media descriptions that we'd like to add + * candidates to. + * @param iceMediaStream the media stream where we should extract candidates + * from. + */ + public static void initMediaDescription(MediaDescription mediaDescription, + IceMediaStream iceMediaStream) + { + for(Component component : iceMediaStream.getComponents()) + { + //first add the candidates + for(Candidate candidate : component.getLocalCandidates()) + { + mediaDescription.addAttribute( + new CandidateAttribute(candidate)); + } + + //set the default candidate + try + { + TransportAddress defaultAddress + = component.getDefaultCandidate().getTransportAddress(); + + mediaDescription.getMedia().setMediaPort( + defaultAddress.getPort()); + + String addressFamily = defaultAddress.isIPv6() + ? Connection.IP6 + : Connection.IP4; + + mediaDescription.setConnection(sdpFactory.createConnection( + "IN", defaultAddress.getHostAddress(), addressFamily)); + } + catch (SdpException exc) + { + //this shouldn't happen but let's rethrow an SDP exception just + //in case. + throw new IllegalArgumentException( + "Something went wrong when setting default candidates", + exc); + } + } + } + + /** + * Sets ice credentials, ICE options, media lines and candidates from agent, + * on the specified session description. + * + * @param sDes the {@link SessionDescription} that we'd like to setup as per + * the specified agent. + * @param agent the {@link Agent} that we need to use when initializing + * the session description. + */ + @SuppressWarnings("unchecked") // jain-sdp legacy + public static void initSessionDescription(SessionDescription sDes, + Agent agent) + { + //now add ICE options + StringBuilder allOptionsBuilder = new StringBuilder(); + + //if(agent.supportsTrickle()) + allOptionsBuilder.append(ICE_OPTION_TRICKLE).append(" "); + + String allOptions = allOptionsBuilder.toString().trim(); + + try + { + if (allOptions.length() > 0) + { + //get the attributes so that we could easily modify them + Vector sessionAttributes = sDes.getAttributes(true); + + sessionAttributes.add( + sdpFactory.createAttribute(ICE_OPTIONS, allOptions)); + } + + //take care of the origin: first extract one of the default + // addresses so that we could set the origin. + TransportAddress defaultAddress = agent.getStreams().get(0) + .getComponent(Component.RTP).getDefaultCandidate() + .getTransportAddress(); + + String addressFamily = defaultAddress.isIPv6() + ? Connection.IP6 + : Connection.IP4; + + //origin + Origin o = sDes.getOrigin(); + + if( o == null || "user".equals(o.getUsername())) + { + //looks like there wasn't any origin set: jain-sdp creates a + //default origin that has "user" as the user name so we use this + //to detect it. it's quite hacky but couldn't fine another way. + o = sdpFactory.createOrigin("ice4j.org", 0, 0, "IN", + addressFamily, defaultAddress.getHostAddress()); + } + else + { + //if an origin existed, we just make sure it has the right + // address now and are care ful not to touch anything else. + o.setAddress(defaultAddress.getHostAddress()); + o.setAddressType(addressFamily); + } + + sDes.setOrigin(o); + + //m lines + List streams = agent.getStreams(); + Vector mDescs = new Vector( + agent.getStreamCount()); + for(IceMediaStream stream : streams) + { + MediaDescription mLine = sdpFactory.createMediaDescription( + stream.getName(), 0, //default port comes later + 1, SdpConstants.RTP_AVP, new int[]{0}); + + IceSdpUtils.initMediaDescription(mLine, stream); + + mDescs.add(mLine); + } + + sDes.setMediaDescriptions(mDescs); + } + catch (SdpException exc) + { + //this shouldn't happen but let's rethrow an SDP exception just + //in case. + throw new IllegalArgumentException( + "Something went wrong when setting ICE options", + exc); + } + + //first set credentials + setIceCredentials( + sDes, agent.getLocalUfrag(), agent.getLocalPassword()); + } +} diff --git a/src/org/ice4j/socket/RtcpDemuxPacketFilter.java b/src/org/ice4j/socket/RtcpDemuxPacketFilter.java new file mode 100644 index 0000000..805bd28 --- /dev/null +++ b/src/org/ice4j/socket/RtcpDemuxPacketFilter.java @@ -0,0 +1,40 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the SIP Communicator community (http://sip-communicator.org). + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.socket; + +import java.net.*; + +/** + * Implements a DatagramPacketFilter which only accepts + * DatagramPackets which represent RTCP messages according to the rules + * described in RFC5761. + *

+ * This filter would only be able to demultiplex between RTP and RTCP packets. + * Other protocols such as STUN/TURN, DTLS or ZRTP are not taken into account + * and may produce false positives if left to this filter. They should hence + * be handled by lower layers/demuxers. + * + * @author Emil Ivov + */ +public class RtcpDemuxPacketFilter + implements DatagramPacketFilter +{ + /** + * Determines whether a specific DatagramPacket is an RTCP. + * DatagramPacket in a selection based on this filter. + * + * @param p the DatagramPacket whose protocol we'd like to + * determine. + * @return true if p is an RTCP and this filter accepts it + * and false otherwise. + */ + public boolean accept(DatagramPacket p) + { + return false; + } +} diff --git a/test/test/Ice.java b/test/test/Ice.java index 09bb83a..4d45a7e 100644 --- a/test/test/Ice.java +++ b/test/test/Ice.java @@ -264,25 +264,25 @@ public class Ice protected static Agent createAgent(int rtpPort) throws Throwable { + long startTime = System.currentTimeMillis(); Agent agent = new Agent(); // STUN StunCandidateHarvester stunHarv = new StunCandidateHarvester( - new TransportAddress("sip-communicator.net", 3478, Transport.UDP)); + new TransportAddress("stun.jitsi.net", 3478, Transport.UDP)); StunCandidateHarvester stun6Harv = new StunCandidateHarvester( - new TransportAddress("ipv6.sip-communicator.net", + new TransportAddress("stun6.jitsi.net", 3478, Transport.UDP)); agent.addCandidateHarvester(stunHarv); agent.addCandidateHarvester(stun6Harv); // TURN - String[] hostnames - = new String[] - { - "130.79.90.150", - "2001:660:4701:1001:230:5ff:fe1a:805f" - }; + String[] hostnames = new String[] + { + "stun.jitsi.net", + "stun6.jitsi.net" + }; int port = 3478; LongTermCredential longTermCredential = new LongTermCredential("guest", "anonymouspower!!"); @@ -293,10 +293,20 @@ public class Ice new TransportAddress(hostname, port, Transport.UDP), longTermCredential)); + //UPnP: adding an UPnP harvester because they are generally slow + //which makes it more convenient to test things like trickle. + agent.addCandidateHarvester( new UPNPHarvester() ); + //STREAMS createStream(rtpPort, "audio", agent); createStream(rtpPort + 2, "video", agent); + + long endTime = System.currentTimeMillis(); + long total = endTime - startTime; + + System.out.println("Total harvesting time: " + total + "ms."); + return agent; } diff --git a/test/test/IceDistributed.java b/test/test/IceDistributed.java index 40982b4..415cf8b 100644 --- a/test/test/IceDistributed.java +++ b/test/test/IceDistributed.java @@ -44,9 +44,13 @@ public class IceDistributed localAgent.setControlling(false); String localSDP = SdpUtils.createSDPDescription(localAgent); + //wait a bit so that the logger can stop dumping stuff: + Thread.sleep(500); + System.out.println("=================== feed the following" +" to the remote agent ==================="); + System.out.println(localSDP); System.out.println("======================================" diff --git a/test/test/SdpUtils.java b/test/test/SdpUtils.java deleted file mode 100644 index 31eacf6..0000000 --- a/test/test/SdpUtils.java +++ /dev/null @@ -1,392 +0,0 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * Maintained by the SIP Communicator community (http://sip-communicator.org). - * - * Distributable under LGPL license. See terms of license at gnu.org. - */ -package test; - -import gov.nist.core.*; -import gov.nist.javax.sdp.fields.*; - -import java.util.*; -import java.util.StringTokenizer; - -import javax.sdp.*; - -import org.ice4j.*; -import org.ice4j.ice.*; -import org.ice4j.ice.Agent; - -/** - * Utilities for manipulating SDP. The utilities This method do not try - * to act smart and make a lot of assumptions (e.g. at least one media stream - * with at least one component) that may not always be true in real life and - * lead to exceptions. Therefore, make sure you reread the code if reusing it - * in an application. It should be fine for the purposes of our ice4j examples - * though. - * - * @author Emil Ivov - */ -public class SdpUtils -{ - /** - * Creates a session description containing the streams from the specified - * agent using dummy codecs. - * - * @param agent the {@link Agent} we'd like to generate. - * - * @return a {@link SessionDescription} representing agent's - * streams. - * - * @throws Throwable on rainy days - */ - public static String createSDPDescription(Agent agent) throws Throwable - { - SdpFactory factory = SdpFactory.getInstance(); - SessionDescription sdess = factory.createSessionDescription(); - Vector sessionAttributes = new Vector(); - - TransportAddress defaultAddress = agent.getStreams().get(0) - .getComponent(Component.RTP).getDefaultCandidate() - .getTransportAddress(); - - String addrType = defaultAddress.isIPv6() - ? Connection.IP6 - : Connection.IP4; - - //origin (use ip from the first component of the first stream) - Origin o = factory.createOrigin("ice4j.org", 0, 0, "IN", addrType, - defaultAddress.getHostAddress()); - sdess.setOrigin(o); - - //connection (again use ip from first stream's component) - Connection c = factory.createConnection("IN", addrType, - defaultAddress.getHostAddress() ); - sdess.setConnection(c); - - //ice u-frag and password - sessionAttributes.add(factory.createAttribute("ice-pwd", - agent.getLocalPassword())); - sessionAttributes.add(factory.createAttribute("ice-ufrag", - agent.getLocalUfrag())); - - //m lines - List streams = agent.getStreams(); - Vector mDescs = new Vector( - agent.getStreamCount()); - for(IceMediaStream stream : streams) - { - TransportAddress streamDefaultAddr = stream.getComponent( - Component.RTP).getDefaultCandidate().getTransportAddress(); - MediaDescription mdesc = factory.createMediaDescription( - stream.getName(), streamDefaultAddr.getPort(), - 1, SdpConstants.RTP_AVP, new int[]{0}); - - Vector candidates = new Vector(); - for(Component component : stream.getComponents()) - { - for(Candidate cand : component.getLocalCandidates()) - { - candidates.add(new CandidateAttribute(cand)); - } - } - - mdesc.setAttributes(candidates); - - mDescs.add(mdesc); - } - - sdess.setAttributes(sessionAttributes); - sdess.setMediaDescriptions(mDescs); - return sdess.toString(); - } - - /** - * Configures localAgent the the remote peer streams, components, - * and candidates specified in sdp - * - * @param localAgent the {@link Agent} that we'd like to configure. - * - * @param sdp the SDP string that the remote peer sent. - * - * @throws Exception for all sorts of reasons. - */ - @SuppressWarnings("unchecked") // jain-sdp legacy code. - public static void parseSDP(Agent localAgent, String sdp) - throws Exception - { - SdpFactory factory = SdpFactory.getInstance(); - SessionDescription sdess = factory.createSessionDescription(sdp); - - for(IceMediaStream stream : localAgent.getStreams()) - { - stream.setRemotePassword(sdess.getAttribute("ice-pwd")); - stream.setRemoteUfrag(sdess.getAttribute("ice-ufrag")); - } - - Connection globalConn = sdess.getConnection(); - String globalConnAddr = null; - if(globalConn != null) - globalConnAddr = globalConn.getAddress(); - - Vector mdescs = sdess.getMediaDescriptions(true); - - for (MediaDescription desc : mdescs) - { - String streamName = desc.getMedia().getMediaType(); - - IceMediaStream stream = localAgent.getStream(streamName); - - if(stream == null) - continue; - - Vector attributes = desc.getAttributes(true); - for( Attribute attribute : attributes) - { - if(!attribute.getName().equals(CandidateAttribute.NAME)) - continue; - - parseCandidate(attribute, stream); - } - - //set default candidates - Connection streamConn = desc.getConnection(); - String streamConnAddr = null; - if(streamConn != null) - streamConnAddr = streamConn.getAddress(); - else - streamConnAddr = globalConnAddr; - - int port = desc.getMedia().getMediaPort(); - - TransportAddress defaultRtpAddress = - new TransportAddress(streamConnAddr, port, Transport.UDP); - - int rtcpPort = port + 1; - String rtcpAttributeValue = desc.getAttribute("rtcp"); - - if (rtcpAttributeValue != null) - rtcpPort = Integer.parseInt(rtcpAttributeValue); - - TransportAddress defaultRtcpAddress = - new TransportAddress(streamConnAddr, rtcpPort, Transport.UDP); - - Component rtpComponent = stream.getComponent(Component.RTP); - Component rtcpComponent = stream.getComponent(Component.RTCP); - - Candidate defaultRtpCandidate - = rtpComponent.findRemoteCandidate(defaultRtpAddress); - rtpComponent.setDefaultRemoteCandidate(defaultRtpCandidate); - - if(rtcpComponent != null) - { - Candidate defaultRtcpCandidate - = rtcpComponent.findRemoteCandidate(defaultRtcpAddress); - rtcpComponent.setDefaultRemoteCandidate(defaultRtcpCandidate); - } - } - } - - /** - * Parses the attribute. - * - * @param attribute the attribute that we need to parse. - * @param stream the {@link IceMediaStream} that the candidate is supposed - * to belong to. - * - * @return a newly created {@link RemoteCandidate} matching the - * content of the specified attribute or null if the - * candidate belonged to a component we don't have. - */ - private static RemoteCandidate parseCandidate(Attribute attribute, - IceMediaStream stream) - { - String value = null; - - try{ - value = attribute.getValue(); - }catch (Throwable t){}//can't happen - - StringTokenizer tokenizer = new StringTokenizer(value); - - //XXX add exception handling. - String foundation = tokenizer.nextToken(); - int componentID = Integer.parseInt( tokenizer.nextToken() ); - Transport transport = Transport.parse(tokenizer.nextToken()); - long priority = Long.parseLong(tokenizer.nextToken()); - String address = tokenizer.nextToken(); - int port = Integer.parseInt(tokenizer.nextToken()); - - TransportAddress transAddr - = new TransportAddress(address, port, transport); - - tokenizer.nextToken(); //skip the "typ" String - CandidateType type = CandidateType.parse(tokenizer.nextToken()); - - Component component = stream.getComponent(componentID); - - if(component == null) - return null; - - // check if there's a related address property - - RemoteCandidate relatedCandidate = null; - if (tokenizer.countTokens() >= 4) - { - tokenizer.nextToken(); // skip the raddr element - String relatedAddr = tokenizer.nextToken(); - tokenizer.nextToken(); // skip the rport element - int relatedPort = Integer.parseInt(tokenizer.nextToken()); - - TransportAddress raddr = new TransportAddress( - relatedAddr, relatedPort, Transport.UDP); - - relatedCandidate = component.findRemoteCandidate(raddr); - } - - RemoteCandidate cand = new RemoteCandidate(transAddr, component, type, - foundation, priority, relatedCandidate); - - component.addRemoteCandidate(cand); - - return cand; - } - - - - /** - * An implementation of the candidate SDP attribute. - */ - private static class CandidateAttribute extends AttributeField - { - /** - * The SDP name of candidate attributes. - */ - public static final String NAME = "candidate"; - - /** - * This class's serial version uid. - */ - private static final long serialVersionUID = 1L; - - /** - * The Candidate that we will be encapsulating. - */ - private final Candidate candidate; - - /** - * Creates an attribute instance - * - * @param candidate the Candidate - */ - public CandidateAttribute(Candidate candidate) - { - this.candidate = candidate; - } - /** - * Returns the name of this attribute - * - * @return a String identity. - */ - public String getName() - { - return NAME; - } - - /** - * Does nothing . - * - * @param name ignored. - */ - public void setName(String name){} - - /** - * Always returns true as this attribute always has a value. - * - * @return true if the attribute has a value. - */ - public boolean hasValue() - { - return true; - }; - - /** - * Returns the value of this attribute. - * - * @return the value - */ - public String getValue() - { - StringBuffer buff= new StringBuffer(); - - buff.append(candidate.getFoundation()); - buff.append(" ").append( - candidate.getParentComponent().getComponentID()); - buff.append(" ").append(candidate.getTransport()); - buff.append(" ").append(candidate.getPriority()); - buff.append(" ").append( - candidate.getTransportAddress().getHostAddress()); - buff.append(" ").append( - candidate.getTransportAddress().getPort()); - buff.append(" typ ").append( - candidate.getType()); - - TransportAddress relAddr = candidate.getRelatedAddress(); - - if(relAddr != null) - { - buff.append(" raddr ").append(relAddr.getHostAddress()); - buff.append(" rport ").append(relAddr.getPort()); - } - - return buff.toString(); - } - - /** - * Parses the value of this attribute. - * - * @param value the - attribute value - * - * @throws SdpException if there's a problem with the value - * String. - */ - public void setValue(String value) throws SdpException - { - - } - - /** - * Returns the type character for the field. - * - * @return the type character for the field. - */ - public char getTypeChar() - { - return 'a'; - } - - /** - * Returns a reference to this attribute. - * - * @return a reference to this attribute. - */ - public CandidateAttribute clone() - { - return this; - } - - /** - * Returns the string encoded version of this object - * - * @return the string encoded version of this object - */ - public String encode() - { - StringBuffer sbuff = new StringBuffer(ATTRIBUTE_FIELD); - sbuff.append(getName()).append(Separators.COLON); - sbuff.append(getValue()); - return sbuff.append(Separators.NEWLINE).toString(); - } - } -}