-
Notifications
You must be signed in to change notification settings - Fork 228
/
RelayedCandidateDatagramSocket.java
1560 lines (1425 loc) · 56.6 KB
/
RelayedCandidateDatagramSocket.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.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 an ICE-specific)
* <tt>DatagramSocket</tt> for a <tt>RelayedCandidate</tt> harvested by a
* <tt>TurnCandidateHarvest</tt> (and its associated
* <tt>TurnCandidateHarvester</tt>, of course).
* <tt>RelayedCandidateDatagramSocket</tt> is associated with a successful
* Allocation on a TURN server and implements sends and receives through it
* using TURN messages to and from that TURN server.
*
* @author Lyubomir Marinov
*/
public class RelayedCandidateDatagramSocket
extends DatagramSocket
implements MessageEventHandler
{
/**
* The <tt>Logger</tt> used by the <tt>RelayedCandidateDatagramSocket</tt>
* class and its instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(RelayedCandidateDatagramSocket.class.getName());
/**
* The constant which represents a channel number value signaling that no
* channel number has been explicitly specified.
*/
private static final char CHANNEL_NUMBER_NOT_SPECIFIED = 0;
/**
* The length in bytes of the Channel Number field of a TURN ChannelData
* message.
*/
private static final int CHANNELDATA_CHANNELNUMBER_LENGTH = 2;
/**
* The length in bytes of the Length field of a TURN ChannelData message.
*/
private static final int CHANNELDATA_LENGTH_LENGTH = 2;
/**
* The maximum channel number which is valid for TURN ChannelBind
* <tt>Request</tt>.
*/
private static final char MAX_CHANNEL_NUMBER = 0x7FFF;
/**
* The minimum channel number which is valid for TURN ChannelBind
* <tt>Request</tt>s.
*/
private static final char MIN_CHANNEL_NUMBER = 0x4000;
/**
* 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
* <tt>RelayedCandidateDatagramSocket</tt> is to try to reinstall it.
*/
private static final long PERMISSION_LIFETIME_LEEWAY
= 60 /* seconds */ * 1000L;
/**
* The <tt>DatagramSocket</tt> through which this
* <tt>RelayedCandidateDatagramSocket</tt> actually sends and receives the
* data it has been asked to {@link #send(DatagramPacket)} and
* {@link #receive(DatagramPacket)}. Since data can be exchanged with a TURN
* server using STUN messages (i.e. Send and Data indications),
* <tt>RelayedCandidateDatagramSocket</tt> may send and receive data using
* the associated <tt>StunStack</tt> and not <tt>channelDataSocket</tt>.
* However, using <tt>channelDataSocket</tt> is supposed to be more
* efficient than using <tt>StunStack</tt>.
*/
private final DatagramSocket channelDataSocket;
/**
* The list of per-peer <tt>Channel</tt>s through which this
* <tt>RelayedCandidateDatagramSocket</tt>s relays data send to it to
* peer <tt>TransportAddress</tt>es.
*/
private final List<Channel> 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 <tt>DatagramPacketFilter</tt> which is able to determine whether a
* specific <tt>DatagramPacket</tt> sent through a
* <tt>RelayedCandidateDatagramSocket</tt> is part of the ICE connectivity
* checks. The recognizing is necessary because RFC 5245 says that "it is
* RECOMMENDED that the agent defer creation of a TURN channel until ICE
* completes."
*/
private static final DatagramPacketFilter connectivityCheckRecognizer
= new StunDatagramPacketFilter();
/**
* The next free channel number to be returned by
* {@link #getNextChannelNumber()} and marked as non-free.
*/
private char nextChannelNumber = MIN_CHANNEL_NUMBER;
/**
* The <tt>DatagramPacket</tt>s which are to be received through this
* <tt>DatagramSocket</tt> 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<DatagramPacket> packetsToReceive = new LinkedList<>();
/**
* The <tt>DatagramSocket</tt>s which have been sent through this
* <tt>DatagramSocket</tt> 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<DatagramPacket> packetsToSend = new LinkedList<>();
/**
* The <tt>Thread</tt> which receives <tt>DatagramPacket</tt>s from
* {@link #channelDataSocket} and queues them in {@link #packetsToReceive}.
*/
private Thread receiveChannelDataThread;
/**
* The <tt>RelayedCandidate</tt> which uses this instance as the value of
* its <tt>socket</tt> property.
*/
private final RelayedCandidate relayedCandidate;
/**
* The <tt>Thread</tt> which is to send the {@link #packetsToSend} to the
* associated TURN server.
*/
private Thread sendThread;
/**
* The <tt>TurnCandidateHarvest</tt> which has harvested
* {@link #relayedCandidate}.
*/
private final TurnCandidateHarvest turnCandidateHarvest;
/**
* Initializes a new <tt>RelayedCandidateDatagramSocket</tt> instance which
* is to be the <tt>socket</tt> of a specific <tt>RelayedCandidate</tt>
* harvested by a specific <tt>TurnCandidateHarvest</tt>.
*
* @param relayedCandidate the <tt>RelayedCandidate</tt> which is to use the
* new instance as the value of its <tt>socket</tt> property
* @param turnCandidateHarvest the <tt>TurnCandidateHarvest</tt> which has
* harvested <tt>relayedCandidate</tt>
* @throws SocketException if anything goes wrong while initializing the new
* <tt>RelayedCandidateDatagramSocket</tt> instance
*/
public RelayedCandidateDatagramSocket(
RelayedCandidate relayedCandidate,
TurnCandidateHarvest turnCandidateHarvest)
throws SocketException
{
super(/* bindaddr */ (SocketAddress) null);
this.relayedCandidate = relayedCandidate;
this.turnCandidateHarvest = turnCandidateHarvest;
this.turnCandidateHarvest
.harvester
.getStunStack()
.addIndicationListener(
this.turnCandidateHarvest.hostCandidate
.getTransportAddress(),
this);
DatagramSocket hostSocket
= this.turnCandidateHarvest.hostCandidate
.getCandidateIceSocketWrapper().getUDPSocket();
if (hostSocket instanceof MultiplexingDatagramSocket)
{
channelDataSocket
= ((MultiplexingDatagramSocket) hostSocket).getSocket(
new TurnDatagramPacketFilter(
this.turnCandidateHarvest.harvester.stunServer)
{
@Override
public boolean accept(DatagramPacket p)
{
return channelDataSocketAccept(p);
}
@Override
protected boolean acceptMethod(char method)
{
return channelDataSocketAcceptMethod(method);
}
});
}
else
channelDataSocket = null;
}
/**
* Determines whether a specific <tt>DatagramPacket</tt> is accepted by
* {@link #channelDataSocket} (i.e. whether <tt>channelDataSocket</tt>
* understands <tt>p</tt> and <tt>p</tt> is meant to be received by
* <tt>channelDataSocket</tt>).
*
* @param p the <tt>DatagramPacket</tt> which is to be checked whether it is
* accepted by <tt>channelDataSocket</tt>
* @return <tt>true</tt> if <tt>channelDataSocket</tt> accepts <tt>p</tt>
* (i.e. <tt>channelDataSocket</tt> understands <tt>p</tt> and <tt>p</tt> is
* meant to be received by <tt>channelDataSocket</tt>); otherwise,
* <tt>false</tt>
*/
private boolean channelDataSocketAccept(DatagramPacket p)
{
// Is it from our TURN server?
if (turnCandidateHarvest.harvester.stunServer.equals(
p.getSocketAddress()))
{
int pLength = p.getLength();
if (pLength
>= (CHANNELDATA_CHANNELNUMBER_LENGTH
+ CHANNELDATA_LENGTH_LENGTH))
{
byte[] pData = p.getData();
int pOffset = p.getOffset();
/*
* The first two bits should be 0b01 because of the current
* channel number range 0x4000 - 0x7FFE. But 0b10 and 0b11 which
* are currently reserved and may be used in the future to
* extend the range of channel numbers.
*/
if ((pData[pOffset] & 0xC0) != 0)
{
/*
* Technically, we cannot create a DatagramPacket from a
* ChannelData message with a Channel Number we do not know
* about. But determining that we know the value of the
* Channel Number field may be too much of an unnecessary
* performance penalty and it may be unnecessary because the
* message comes from our TURN server and it looks like a
* ChannelData message already.
*/
pOffset += CHANNELDATA_CHANNELNUMBER_LENGTH;
pLength -= CHANNELDATA_CHANNELNUMBER_LENGTH;
int length
= ((pData[pOffset++] << 8)
| (pData[pOffset++] & 0xFF));
int padding = ((length % 4) > 0) ? 4 - (length % 4) : 0;
/*
* The Length field specifies the length in bytes of the
* Application Data field. The Length field does not include
* the padding that is sometimes present in the data of the
* DatagramPacket.
*/
return length == pLength - padding - CHANNELDATA_LENGTH_LENGTH
|| length == pLength - CHANNELDATA_LENGTH_LENGTH;
}
}
}
return false;
}
/**
* Determines whether {@link #channelDataSocket} accepts
* <tt>DatagramPacket</tt>s which represent STUN messages with a specific
* method.
*
* @param method the method of the STUN messages represented in
* <tt>DatagramPacket</tt>s which is accepted by <tt>channelDataSocket</tt>
* @return <tt>true</tt> if <tt>channelDataSocket</tt> accepts
* <tt>DatagramPacket</tt>s which represent STUN messages with the specified
* <tt>method</tt>; otherwise, <tt>false</tt>
*/
private boolean channelDataSocketAcceptMethod(char method)
{
/*
* Accept only ChannelData messages for now. ChannelData messages are
* not STUN messages so they do not have a method associated with them.
*/
return false;
}
/**
* Closes this datagram socket.
*
* @see DatagramSocket#close()
*/
@Override
public void close()
{
synchronized (this)
{
if (this.closed)
return;
else
this.closed = true;
}
synchronized (packetsToReceive)
{
packetsToReceive.notifyAll();
}
synchronized (packetsToSend)
{
packetsToSend.notifyAll();
}
turnCandidateHarvest.harvester.getStunStack().removeIndicationListener(
turnCandidateHarvest.hostCandidate.getTransportAddress(),
this);
turnCandidateHarvest.close(this);
super.close();
}
/**
* Creates {@link #receiveChannelDataThread} which is to receive
* <tt>DatagramPacket</tt>s from {@link #channelDataSocket} and queue them
* in {@link #packetsToReceive}.
*/
private void createReceiveChannelDataThread()
{
receiveChannelDataThread
= new Thread()
{
@Override
public void run()
{
boolean done = false;
try
{
runInReceiveChannelDataThread();
done = true;
}
catch (SocketException sex)
{
done = true;
}
finally
{
/*
* If receiveChannelDataThread is dying and this
* RelayedCandidateDatagramSocket is not closed, then
* spawn a new receiveChannelDataThread.
*/
synchronized (packetsToReceive)
{
if (receiveChannelDataThread
== Thread.currentThread())
receiveChannelDataThread = null;
if ((receiveChannelDataThread == null)
&& !closed
&& !done)
createReceiveChannelDataThread();
}
}
}
};
receiveChannelDataThread.start();
}
/**
* Creates {@link #sendThread} which is to send {@link #packetsToSend} to
* the associated TURN server.
*/
private void createSendThread()
{
sendThread
= new Thread()
{
@Override
public void run()
{
try
{
runInSendThread();
}
finally
{
/*
* If sendThread is dying and there are packetsToSend,
* then spawn a new sendThread.
*/
synchronized (packetsToSend)
{
if (sendThread == Thread.currentThread())
sendThread = null;
if ((sendThread == null)
&& !closed
&& !packetsToSend.isEmpty())
createSendThread();
}
}
}
};
sendThread.start();
}
/**
* Gets the local address to which the socket is bound.
* <tt>RelayedCandidateDatagramSocket</tt> returns the <tt>address</tt> of
* its <tt>localSocketAddress</tt>.
* <p>
* If there is a security manager, its <tt>checkConnect</tt> method is first
* called with the host address and <tt>-1</tt> as its arguments to see if
* the operation is allowed.
* </p>
*
* @return the local address to which the socket is bound, or an
* <tt>InetAddress</tt> representing any local address if either the socket
* is not bound, or the security manager <tt>checkConnect</tt> 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.
* <tt>RelayedCandidateDatagramSocket</tt> returns the <tt>port</tt> of its
* <tt>localSocketAddress</tt>.
*
* @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
* <tt>null</tt> if it is not bound yet. Since
* <tt>RelayedCandidateDatagramSocket</tt> represents an
* application-purposed <tt>DatagramSocket</tt> relaying data to and from a
* TURN server, the <tt>localSocketAddress</tt> is the
* <tt>transportAddress</tt> of the respective <tt>RelayedCandidate</tt>.
*
* @return a <tt>SocketAddress</tt> representing the local endpoint of this
* socket, or <tt>null</tt> if it is not bound yet
* @see DatagramSocket#getLocalSocketAddress()
*/
@Override
public InetSocketAddress getLocalSocketAddress()
{
return getRelayedCandidate().getTransportAddress();
}
/**
* Gets the next free channel number to be allocated to a <tt>Channel</tt>
* and marked as non-free.
*
* @return the next free channel number to be allocated to a
* <tt>Channel</tt> and marked as non-free.
*/
private char getNextChannelNumber()
{
char nextChannelNumber;
if (this.nextChannelNumber > MAX_CHANNEL_NUMBER)
nextChannelNumber = CHANNEL_NUMBER_NOT_SPECIFIED;
else
{
nextChannelNumber = this.nextChannelNumber;
this.nextChannelNumber++;
}
return nextChannelNumber;
}
/**
* Gets the <tt>RelayedCandidate</tt> which uses this instance as the value
* of its <tt>socket</tt> property.
*
* @return the <tt>RelayedCandidate</tt> which uses this instance as the
* value of its <tt>socket</tt> property
*/
public final RelayedCandidate getRelayedCandidate()
{
return relayedCandidate;
}
/**
* Notifies this <tt>MessageEventHandler</tt> that a specific STUN message
* has been received, parsed and is ready for delivery.
* <tt>RelayedCandidateDatagramSocket</tt> handles STUN indications sent
* from the associated TURN server and received at the associated local
* <tt>TransportAddress</tt>.
*
* @param e a <tt>StunMessageEvent</tt> 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 (Throwable t)
{
/*
* The signature of the DatagramPacket constructor was changed
* in JDK 8 to not declare that it may throw a SocketException.
*/
if (t instanceof SocketException)
{
packetToReceive = null;
}
else if (t instanceof Error)
{
throw (Error) t;
}
else if (t instanceof RuntimeException)
{
throw (RuntimeException) t;
}
else
{
/*
* Unfortunately, we cannot re-throw it. Anyway, it was
* unlikely to occur on JDK 7.
*/
if (t instanceof InterruptedException)
{
Thread.currentThread().interrupt();
}
packetToReceive = null;
}
}
if (packetToReceive != null)
{
synchronized (packetsToReceive)
{
packetsToReceive.add(packetToReceive);
packetsToReceive.notifyAll();
}
}
}
/**
* Notifies this <tt>RelayedCandidateDatagramSocket</tt> that a specific
* <tt>Request</tt> it has sent has either failed or received a STUN error
* <tt>Response</tt>.
*
* @param response the <tt>Response</tt> which responds to <tt>request</tt>
* @param request the <tt>Request</tt> sent by this instance to which
* <tt>response</tt> responds
* @return <tt>true</tt> if the failure or error condition has been handled
* and the caller should assume this instance has recovered from it;
* otherwise, <tt>false</tt>
*/
public boolean processErrorOrFailure(Response response, Request request)
{
switch (request.getMessageType())
{
case Message.CHANNELBIND_REQUEST:
setChannelNumberIsConfirmed(request, false);
break;
case Message.CREATEPERMISSION_REQUEST:
setChannelBound(request, false);
break;
default:
break;
}
return false;
}
/**
* Notifies this <tt>RelayedCandidateDatagramSocket</tt> that a specific
* <tt>Request</tt> it has sent has received a STUN success
* <tt>Response</tt>.
*
* @param response the <tt>Response</tt> which responds to <tt>request</tt>
* @param request the <tt>Request</tt> sent by this instance to which
* <tt>response</tt> responds
*/
public void processSuccess(Response response, Request request)
{
switch (request.getMessageType())
{
case Message.CHANNELBIND_REQUEST:
setChannelNumberIsConfirmed(request, true);
break;
case Message.CREATEPERMISSION_REQUEST:
setChannelBound(request, true);
break;
default:
break;
}
}
/**
* Receives a datagram packet from this socket. When this method returns,
* the <tt>DatagramPacket</tt>'s buffer is filled with the data received.
* The datagram packet also contains the sender's IP address, and the port
* number on the sender's machine.
*
* @param p the <tt>DatagramPacket</tt> into which to place the incoming
* data
* @throws IOException if an I/O error occurs
* @see DatagramSocket#receive(DatagramPacket)
*/
@Override
public void receive(DatagramPacket p)
throws IOException
{
synchronized (packetsToReceive)
{
do
{
/*
* 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)
{
}
}
else
{
DatagramPacket packetToReceive = packetsToReceive.remove(0);
MultiplexingXXXSocketSupport.copy(packetToReceive, p);
packetsToReceive.notifyAll();
break;
}
}
while (true);
}
}
/**
* Runs in {@link #receiveChannelDataThread} to receive
* <tt>DatagramPacket</tt>s from {@link #channelDataSocket} and queue them
* in {@link #packetsToReceive}.
*
* @throws SocketException if anything goes wrong while receiving
* <tt>DatagramPacket</tt>s from {@link #channelDataSocket} and
* {@link #receiveChannelDataThread} is to no longer exist
*/
private void runInReceiveChannelDataThread()
throws SocketException
{
DatagramPacket p = null;
while (!closed)
{
// read one datagram a time
int receiveBufferSize = 1500;
if (p == null)
{
p
= new DatagramPacket(
new byte[receiveBufferSize],
receiveBufferSize);
}
else
{
byte[] pData = p.getData();
if ((pData == null) || (pData.length < receiveBufferSize))
p.setData(new byte[receiveBufferSize]);
else
p.setLength(receiveBufferSize);
}
try
{
channelDataSocket.receive(p);
}
catch (Throwable t)
{
if (t instanceof ThreadDeath)
{
// Death is the end of life no matter what.
throw (ThreadDeath) t;
}
else if (t instanceof SocketException)
{
/*
* If the channelDataSocket has gone unusable, put an end to
* receiving from it.
*/
throw (SocketException) t;
}
else
{
if (logger.isLoggable(Level.WARNING))
{
logger.log(
Level.WARNING,
"Ignoring error while receiving from"
+ " ChannelData socket",
t);
}
continue;
}
}
/*
* We've been waiting in #receive so make sure we're still to
* continue just in case.
*/
if (closed)
break;
int channelDataLength = p.getLength();
if (channelDataLength
< (CHANNELDATA_CHANNELNUMBER_LENGTH
+ CHANNELDATA_LENGTH_LENGTH))
continue;
byte[] channelData = p.getData();
int channelDataOffset = p.getOffset();
char channelNumber
= (char)
((channelData[channelDataOffset++] << 8)
| (channelData[channelDataOffset++] & 0xFF));
channelDataLength -= CHANNELDATA_CHANNELNUMBER_LENGTH;
char length
= (char)
((channelData[channelDataOffset++] << 8)
| (channelData[channelDataOffset++] & 0xFF));
channelDataLength -= CHANNELDATA_LENGTH_LENGTH;
if (length > channelDataLength)
continue;
TransportAddress peerAddress = null;
synchronized (packetsToSend)
{
int channelCount = channels.size();
for (int channelIndex = 0;
channelIndex < channelCount;
channelIndex++)
{
Channel channel = channels.get(channelIndex);
if (channel.channelNumberEquals(channelNumber))
{
peerAddress = channel.peerAddress;
break;
}
}
}
if (peerAddress == null)
continue;
byte[] data = new byte[length];
System.arraycopy(channelData, channelDataOffset, data, 0, length);
DatagramPacket packetToReceive
= new DatagramPacket(data, 0, length, peerAddress);
synchronized (packetsToReceive)
{
packetsToReceive.add(packetToReceive);
packetsToReceive.notifyAll();
}
}
}
/**
* 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);
}
/*
* RFC 5245 says that "it is RECOMMENDED that the agent
* defer creation of a TURN channel until ICE completes."
* RelayedCandidateDatagramSocket is not explicitly told
* from the outside that ICE has completed so it tries to
* determine it by assuming that connectivity checks send
* only STUN messages and ICE has completed by the time a
* non-STUN message is to be sent.
*/
boolean forceBind = false;
if ((channelDataSocket != null)
&& !channel.getChannelDataIsPreferred()
&& !connectivityCheckRecognizer.accept(
packetToSend))
{
channel.setChannelDataIsPreferred(true);
forceBind = true;
}
/*
* Either bind the channel or send the packetToSend through
* it.
*/
if (!forceBind && 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 (forceBind || !channel.isBinding())
{
try
{
channel.bind();
}
catch (StunException sex)
{
if (logger.isLoggable(Level.INFO))
{
logger.log(