/
SinglePortUdpHarvester.java
413 lines (366 loc) · 13.4 KB
/
SinglePortUdpHarvester.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ice4j.ice.harvest;
import org.ice4j.*;
import org.ice4j.ice.*;
import org.ice4j.socket.*;
import org.ice4j.stack.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.*;
/**
* A harvester implementation which binds to a single <tt>DatagramSocket</tt>
* and provides local candidates of type "host". It runs a thread
* ({@link #thread}) which perpetually reads from the socket.
*
* When {@link #harvest(org.ice4j.ice.Component)} is called, this harvester
* creates and adds to the component a
* {@link org.ice4j.ice.harvest.SinglePortUdpHarvester.MyCandidate} instance,
* and associates the component's local username fragment (ufrag) with this
* candidate.
*
* When a STUN Binding Request with a given ufrag is received, if the ufrag
* matches one of the registered candidates, then a new socket is created, which
* is to receive further packets from the remote address, and the socket is
* added to the candidate.
*
* @author Boris Grozev
*/
public class SinglePortUdpHarvester
extends AbstractUdpListener
implements CandidateHarvester
{
/**
* Our class logger.
*/
private static final Logger logger
= Logger.getLogger(SinglePortUdpHarvester.class.getName());
/**
* Creates a new <tt>SinglePortUdpHarvester</tt> instance for each allowed
* IP address found on each allowed network interface, with the given port.
*
* @param port the UDP port number to use.
* @return the list of created <tt>SinglePortUdpHarvester</tt>s.
*/
public static List<SinglePortUdpHarvester> createHarvesters(int port)
{
List<SinglePortUdpHarvester> harvesters = new LinkedList<>();
for (TransportAddress address
: AbstractUdpListener.getAllowedAddresses(port))
{
try
{
harvesters.add(
new SinglePortUdpHarvester(address));
}
catch (IOException ioe)
{
logger.info("Failed to create SinglePortUdpHarvester for "
+ "address " + address + ": " + ioe);
}
}
return harvesters;
}
/**
* The map which keeps all currently active <tt>Candidate</tt>s created by
* this harvester. The keys are the local username fragments (ufrags) of
* the components for which the candidates are harvested.
*/
private final Map<String, MyCandidate> candidates
= new ConcurrentHashMap<>();
/**
* Manages statistics about harvesting time.
*/
private HarvestStatistics harvestStatistics = new HarvestStatistics();
/**
* Initializes a new <tt>SinglePortUdpHarvester</tt> instance which is to
* bind on the specified local address.
* @param localAddress the address to bind to. If the port is 0 an ephemeral port is chosen by the OS and the
* SinglePortUdpHarvester.localAddress will reflect the allocated port number.
* @throws IOException if initialization fails.
*/
public SinglePortUdpHarvester(TransportAddress localAddress)
throws IOException
{
super(localAddress);
logger.info("Initialized SinglePortUdpHarvester with address "
+ this.localAddress);
}
/**
* {@inheritDoc}
*/
public HarvestStatistics getHarvestStatistics()
{
return harvestStatistics;
}
/**
* {@inheritDoc}
*
* Looks for an ICE candidate registered with this harvester, which has a
* local ufrag of {@code ufrag}, and if one is found it accepts the new
* socket and adds it to the candidate.
*/
protected void maybeAcceptNewSession(Buffer buf,
InetSocketAddress remoteAddress,
String ufrag)
{
MyCandidate candidate = candidates.get(ufrag);
if (candidate == null)
{
// A STUN Binding Request with an unknown USERNAME. Drop it.
return;
}
// This is a STUN Binding Request destined for this
// specific Candidate/Component/Agent.
try
{
// 1. Create a socket for this remote address
// 2. Set-up de-multiplexing for future datagrams
// with this address to this socket.
MySocket newSocket = addSocket(remoteAddress, ufrag);
// 3. Let the candidate and its STUN stack no about the
// new socket.
candidate.addSocket(newSocket, remoteAddress);
// 4. Add the original datagram to the new socket.
newSocket.addBuffer(buf);
}
catch (SocketException se)
{
logger.info("Could not create a socket: " + se);
}
catch (IOException ioe)
{
logger.info("Failed to handle new socket: " + ioe);
}
}
/**
* {@inheritDoc}
*/
@Override
public Collection<LocalCandidate> harvest(Component component)
{
IceMediaStream stream = component.getParentStream();
Agent agent = stream.getParentAgent();
String ufrag = agent.getLocalUfrag();
if (stream.getComponentCount() != 1 || agent.getStreamCount() != 1)
{
/*
* SinglePortUdpHarvester only works with streams with a
* single component, and agents with a single stream. This is
* because we use the local "ufrag" from an incoming STUN packet
* to setup de-multiplexing based on remote transport address.
*/
logger.info(
"More than one Component for an Agent, cannot harvest.");
return new LinkedList<>();
}
MyCandidate candidate = new MyCandidate(component, ufrag);
candidates.put(ufrag, candidate);
component.addLocalCandidate(candidate);
return new ArrayList<LocalCandidate>(Arrays.asList(candidate));
}
/**
* {@inheritDoc}
*/
@Override
public boolean isHostHarvester()
{
return true;
}
/**
* Implements a <tt>Candidate</tt> for the purposes of this
* <tt>SinglePortUdpHarvester</tt>.
*/
private class MyCandidate
extends HostCandidate
{
/**
* The local username fragment associated with this candidate.
*/
private final String ufrag;
/**
* The flag which indicates that this <tt>MyCandidate</tt> has been
* freed.
*/
private boolean freed = false;
/**
* The collection of <tt>IceSocketWrapper</tt>s that can potentially
* be used by the ice4j user to read/write from/to this candidate.
* The keys are the remote addresses for each socket.
* <p>
* There are wrappers over <tt>MultiplexedDatagramSocket</tt>s over
* a corresponding socket in {@link #sockets}.
*/
private final Map<SocketAddress, IceSocketWrapper> candidateSockets
= new HashMap<>();
/**
* The collection of <tt>DatagramSocket</tt>s added to this candidate.
* The keys are the remote addresses for each socket.
* <p>
* These are the "raw" sockets, before any wrappers are added for
* the STUN stack or the user of ice4j.
*/
private final Map<SocketAddress, DatagramSocket> sockets
= new HashMap<>();
/**
* Initializes a new <tt>MyCandidate</tt> instance with the given
* <tt>Component</tt> and the given local username fragment.
*
* @param component the <tt>Component</tt> for which this candidate will
* serve.
* @param ufrag the local ICE username fragment for this candidate (and
* its <tt>Component</tt> and <tt>Agent</tt>).
*/
private MyCandidate(Component component, String ufrag)
{
super(localAddress, component);
this.ufrag = ufrag;
}
/**
* {@inheritDoc}
* <p>
* Closes all sockets in use by this <tt>LocalCandidate</tt>.
*/
@Override
public void free()
{
synchronized (this)
{
if (freed)
return;
freed = true;
}
candidates.remove(ufrag);
synchronized (sockets)
{
StunStack stunStack = getStunStack();
for (Map.Entry<SocketAddress, DatagramSocket> e
: sockets.entrySet())
{
DatagramSocket socket = e.getValue();
if (stunStack != null)
{
TransportAddress localAddress
= new TransportAddress(socket.getLocalAddress(),
socket.getLocalPort(),
Transport.UDP);
TransportAddress remoteAddress
= new TransportAddress(
(InetSocketAddress) e.getKey(),
Transport.UDP);
stunStack.removeSocket(localAddress, remoteAddress);
}
socket.close();
}
sockets.clear();
}
synchronized (candidateSockets)
{
for (IceSocketWrapper wrapper : candidateSockets.values())
{
wrapper.close();
}
candidateSockets.clear();
}
super.free();
}
/**
* Adds a new <tt>Socket</tt> to this candidate, which is associated
* with a particular remote address.
*
* @param socket the socket to add.
* @param remoteAddress the remote address for the socket.
*/
private synchronized void addSocket(DatagramSocket socket,
InetSocketAddress remoteAddress)
throws IOException
{
if (freed)
{
throw new IOException("Candidate freed");
}
Component component = getParentComponent();
if (component == null)
{
throw new IOException("No parent component");
}
IceProcessingState state
= component.getParentStream().getParentAgent().getState();
if (state == IceProcessingState.FAILED)
{
throw new IOException(
"Cannot add socket to an Agent in state FAILED.");
}
else if (state != null && state.isOver()
&& logger.isLoggable(Level.FINE))
{
logger.fine(
"Adding a socket to a completed Agent, state=" + state);
}
MultiplexingDatagramSocket multiplexing
= new MultiplexingDatagramSocket(socket);
// Socket to add to the candidate
IceSocketWrapper candidateSocket
= new IceUdpSocketWrapper(multiplexing);
// STUN-only filtered socket to add to the StunStack
IceSocketWrapper stunSocket
= new IceUdpSocketWrapper(
multiplexing.getSocket(new StunDatagramPacketFilter()));
component.getParentStream().getParentAgent().getStunStack()
.addSocket(
stunSocket,
new TransportAddress(remoteAddress, Transport.UDP));
MergingDatagramSocket componentSocket
= component.getComponentSocket();
if (componentSocket != null)
{
componentSocket.add(multiplexing);
}
synchronized (candidateSockets)
{
IceSocketWrapper oldSocket
= candidateSockets.put(remoteAddress, candidateSocket);
if (oldSocket != null)
{
logger.warning("Replacing the socket for remote address "
+ remoteAddress);
oldSocket.close();
}
}
// XXX is this necessary?
synchronized (sockets)
{
sockets.put(remoteAddress, socket);
}
}
/**
* {@inheritDoc}
*/
@Override
protected IceSocketWrapper getCandidateIceSocketWrapper(
SocketAddress remoteAddress)
{
synchronized (candidateSockets)
{
return candidateSockets.get(remoteAddress);
}
}
}
}