summaryrefslogtreecommitdiff
path: root/java/src/IceInternal/UdpTransceiver.java
blob: 15f1683cf4e9674e2e957efea702669970be8921 (plain)
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
// **********************************************************************
//
// Copyright (c) 2003-2014 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

package IceInternal;

final class UdpTransceiver implements Transceiver
{
    public java.nio.channels.SelectableChannel fd()
    {
        assert(_fd != null);
        return _fd;
    }

    public int initialize(Buffer readBuffer, Buffer writeBuffer, Ice.BooleanHolder moreData)
    {
        //
        // Nothing to do.
        //
        return SocketOperation.None;
    }

    public int closing(boolean initiator, Ice.LocalException ex)
    {
        //
        // Nothing to do.
        //
        return SocketOperation.None;
    }

    public void close()
    {
        assert(_fd != null);

        if(_state >= StateConnected && _instance.traceLevel() >= 1)
        {
            String s = "closing " + _instance.protocol() + " connection\n" + toString();
            _instance.logger().trace(_instance.traceCategory(), s);
        }

        try
        {
            _fd.close();
        }
        catch(java.io.IOException ex)
        {
        }
        _fd = null;
    }

    @SuppressWarnings("deprecation")
    public int write(Buffer buf)
    {
        //
        // We don't want write or send to be called on android main thread as this will cause
        // NetworkOnMainThreadException to be thrown. If that is the android main thread
        // we return false and this method will be later called from the thread pool
        //
        if(Util.isAndroidMainThread(Thread.currentThread()))
        {
            return SocketOperation.Write;
        }

        assert(buf.b.position() == 0);
        assert(_fd != null && _state >= StateConnected);

        // The caller is supposed to check the send size before by calling checkSendSize
        assert(java.lang.Math.min(_maxPacketSize, _sndSize - _udpOverhead) >= buf.size());

        int ret = 0;
        while(true)
        {
            try
            {
                if(_state == StateConnected)
                {
                    ret = _fd.write(buf.b);
                }
                else
                {
                    if(_peerAddr == null)
                    {
                        throw new Ice.SocketException(); // No peer has sent a datagram yet.
                    }
                    ret = _fd.send(buf.b, _peerAddr);
                }
                break;
            }
            catch(java.nio.channels.AsynchronousCloseException ex)
            {
                throw new Ice.ConnectionLostException(ex);
            }
            catch(java.net.PortUnreachableException ex)
            {
                throw new Ice.ConnectionLostException(ex);
            }
            catch(java.io.InterruptedIOException ex)
            {
                continue;
            }
            catch(java.io.IOException ex)
            {
                throw new Ice.SocketException(ex);
            }
        }

        if(ret == 0)
        {
            return SocketOperation.Write;
        }

        if(_instance.traceLevel() >= 3)
        {
            String s = "sent " + ret + " bytes via " + _instance.protocol() + "\n" + toString();
            _instance.logger().trace(_instance.traceCategory(), s);
        }

        assert(ret == buf.b.limit());
        return SocketOperation.None;
    }

    @SuppressWarnings("deprecation")
    public int read(Buffer buf, Ice.BooleanHolder moreData)
    {
        assert(buf.b.position() == 0);

        final int packetSize = java.lang.Math.min(_maxPacketSize, _rcvSize - _udpOverhead);
        buf.resize(packetSize, true);
        buf.b.position(0);

        int ret = 0;
        while(true)
        {
            try
            {
                java.net.SocketAddress peerAddr = _fd.receive(buf.b);
                if(peerAddr == null || buf.b.position() == 0)
                {
                    return SocketOperation.Read;
                }

                _peerAddr = (java.net.InetSocketAddress)peerAddr;
                ret = buf.b.position();
                break;
            }
            catch(java.nio.channels.AsynchronousCloseException ex)
            {
                throw new Ice.ConnectionLostException(ex);
            }
            catch(java.net.PortUnreachableException ex)
            {
                throw new Ice.ConnectionLostException(ex);
            }
            catch(java.io.InterruptedIOException ex)
            {
                continue;
            }
            catch(java.io.IOException ex)
            {
                throw new Ice.ConnectionLostException(ex);
            }
        }

        if(_state == StateNeedConnect)
        {
            //
            // If we must connect, we connect to the first peer that sends us a packet.
            //
            Network.doConnect(_fd, _peerAddr);
            _state = StateConnected;

            if(_instance.traceLevel() >= 1)
            {
                String s = "connected " + _instance.protocol() + " socket\n" + toString();
                _instance.logger().trace(_instance.traceCategory(), s);
            }
        }

        if(_instance.traceLevel() >= 3)
        {
            String s = "received " + ret + " bytes via " + _instance.protocol() + "\n" + toString();
            _instance.logger().trace(_instance.traceCategory(), s);
        }

        buf.resize(ret, true);
        buf.b.position(ret);

        return SocketOperation.None;
    }

    public String protocol()
    {
        return _instance.protocol();
    }

    public String toString()
    {
        if(_fd == null)
        {
            return "<closed>";
        }

        String s;
        if(_state == StateNotConnected)
        {
            java.net.DatagramSocket socket = ((java.nio.channels.DatagramChannel)_fd).socket();
            s = "local address = " + Network.addrToString((java.net.InetSocketAddress)socket.getLocalSocketAddress());
            if(_peerAddr != null)
            {
                s += "\nremote address = " + Network.addrToString(_peerAddr);
            }
        }
        else
        {
            s = Network.fdToString(_fd);
        }

        if(_mcastAddr != null)
        {
            s += "\nmulticast address = " + Network.addrToString(_mcastAddr);
        }
        return s;
    }

    public Ice.ConnectionInfo getInfo()
    {
        Ice.UDPConnectionInfo info = new Ice.UDPConnectionInfo();
        if(_fd != null)
        {
            java.net.DatagramSocket socket = _fd.socket();
            info.localAddress = socket.getLocalAddress().getHostAddress();
            info.localPort = socket.getLocalPort();
            if(_state == StateNotConnected)
            {
                if(_peerAddr != null)
                {
                    info.remoteAddress = _peerAddr.getAddress().getHostAddress();
                    info.remotePort = _peerAddr.getPort();
                }
            }
            else
            {
                if(socket.getInetAddress() != null)
                {
                    info.remoteAddress = socket.getInetAddress().getHostAddress();
                    info.remotePort = socket.getPort();
                }
            }
        }
        if(_mcastAddr != null)
        {
            info.mcastAddress = _mcastAddr.getAddress().getHostAddress();
            info.mcastPort = _mcastAddr.getPort();
        }
        return info;
    }

    public void checkSendSize(Buffer buf, int messageSizeMax)
    {
        if(buf.size() > messageSizeMax)
        {
            Ex.throwMemoryLimitException(buf.size(), messageSizeMax);
        }

        //
        // The maximum packetSize is either the maximum allowable UDP packet size, or
        // the UDP send buffer size (which ever is smaller).
        //
        final int packetSize = java.lang.Math.min(_maxPacketSize, _sndSize - _udpOverhead);
        if(packetSize < buf.size())
        {
            throw new Ice.DatagramLimitException();
        }
    }

    public final int effectivePort()
    {
        return _addr.getPort();
    }

    //
    // Only for use by UdpEndpoint
    //
    @SuppressWarnings("deprecation")
    UdpTransceiver(ProtocolInstance instance, java.net.InetSocketAddress addr, String mcastInterface, int mcastTtl)
    {
        _instance = instance;
        _state = StateNeedConnect;
        _addr = addr;

        try
        {
            _fd = Network.createUdpSocket(_addr);
            setBufSize(instance.properties());
            Network.setBlock(_fd, false);
            //
            // NOTE: setting the multicast interface before performing the
            // connect is important for some OS such as OS X.
            //
            if(_addr.getAddress().isMulticastAddress())
            {
                configureMulticast(null, mcastInterface, mcastTtl);
            }
            Network.doConnect(_fd, _addr);
            _state = StateConnected; // We're connected now

            if(_instance.traceLevel() >= 1)
            {
                String s = "starting to send " + _instance.protocol() + " packets\n" + toString();
                _instance.logger().trace(_instance.traceCategory(), s);
            }
        }
        catch(Ice.LocalException ex)
        {
            _fd = null;
            throw ex;
        }
    }

    //
    // Only for use by UdpEndpoint
    //
    @SuppressWarnings("deprecation")
    UdpTransceiver(ProtocolInstance instance, String host, int port, String mcastInterface, boolean connect)
    {
        _instance = instance;
        _state = connect ? StateNeedConnect : StateNotConnected;

        try
        {
            _addr = Network.getAddressForServer(host, port, instance.protocolSupport(), instance.preferIPv6());
            _fd = Network.createUdpSocket(_addr);
            setBufSize(instance.properties());
            Network.setBlock(_fd, false);
            if(_instance.traceLevel() >= 2)
            {
                String s = "attempting to bind to " + _instance.protocol() + " socket " + Network.addrToString(_addr);
                _instance.logger().trace(_instance.traceCategory(), s);
            }
            if(_addr.getAddress().isMulticastAddress())
            {
                Network.setReuseAddress(_fd, true);
                _mcastAddr = _addr;
                if(System.getProperty("os.name").startsWith("Windows") ||
                   System.getProperty("java.vm.name").startsWith("OpenJDK"))
                {
                    //
                    // Windows does not allow binding to the mcast address itself
                    // so we bind to INADDR_ANY (0.0.0.0) instead. As a result,
                    // bi-directional connection won't work because the source
                    // address won't be the multicast address and the client will
                    // therefore reject the datagram.
                    //
                    int protocol =
                        _mcastAddr.getAddress().getAddress().length == 4 ? Network.EnableIPv4 : Network.EnableIPv6;
                    _addr = Network.getAddressForServer("", port, protocol, instance.preferIPv6());
                }
                _addr = Network.doBind(_fd, _addr);
                configureMulticast(_mcastAddr, mcastInterface, -1);

                if(port == 0)
                {
                    _mcastAddr = new java.net.InetSocketAddress(_mcastAddr.getAddress(), _addr.getPort());
                }
            }
            else
            {
                if(!System.getProperty("os.name").startsWith("Windows"))
                {
                    //
                    // Enable SO_REUSEADDR on Unix platforms to allow
                    // re-using the socket even if it's in the TIME_WAIT
                    // state. On Windows, this doesn't appear to be
                    // necessary and enabling SO_REUSEADDR would actually
                    // not be a good thing since it allows a second
                    // process to bind to an address even it's already
                    // bound by another process.
                    //
                    // TODO: using SO_EXCLUSIVEADDRUSE on Windows would
                    // probably be better but it's only supported by recent
                    // Windows versions (XP SP2, Windows Server 2003).
                    //
                    Network.setReuseAddress(_fd, true);
                }
                _addr = Network.doBind(_fd, _addr);
            }

            if(_instance.traceLevel() >= 1)
            {
                StringBuffer s = new StringBuffer("starting to receive " + _instance.protocol() + " packets\n");
                s.append(toString());

                java.util.List<String> interfaces =
                    Network.getHostsForEndpointExpand(_addr.getAddress().getHostAddress(), instance.protocolSupport(),
                                                      true);
                if(!interfaces.isEmpty())
                {
                    s.append("\nlocal interfaces: ");
                    s.append(IceUtilInternal.StringUtil.joinString(interfaces, ", "));
                }
                _instance.logger().trace(_instance.traceCategory(), s.toString());
            }
        }
        catch(Ice.LocalException ex)
        {
            _fd = null;
            throw ex;
        }
    }

    private synchronized void setBufSize(Ice.Properties properties)
    {
        assert(_fd != null);

        for(int i = 0; i < 2; ++i)
        {
            String direction;
            String prop;
            int dfltSize;
            if(i == 0)
            {
                direction = "receive";
                prop = "Ice.UDP.RcvSize";
                dfltSize = Network.getRecvBufferSize(_fd);
                _rcvSize = dfltSize;
            }
            else
            {
                direction = "send";
                prop = "Ice.UDP.SndSize";
                dfltSize = Network.getSendBufferSize(_fd);
                _sndSize = dfltSize;
            }

            //
            // Get property for buffer size and check for sanity.
            //
            int sizeRequested = properties.getPropertyAsIntWithDefault(prop, dfltSize);
            if(sizeRequested < (_udpOverhead + IceInternal.Protocol.headerSize))
            {
                _instance.logger().warning("Invalid " + prop + " value of " + sizeRequested + " adjusted to " +
                    dfltSize);
                sizeRequested = dfltSize;
            }

            if(sizeRequested != dfltSize)
            {
                //
                // Try to set the buffer size. The kernel will silently adjust
                // the size to an acceptable value. Then read the size back to
                // get the size that was actually set.
                //
                int sizeSet;
                if(i == 0)
                {
                    Network.setRecvBufferSize(_fd, sizeRequested);
                    _rcvSize = Network.getRecvBufferSize(_fd);
                    sizeSet = _rcvSize;
                }
                else
                {
                    Network.setSendBufferSize(_fd, sizeRequested);
                    _sndSize = Network.getSendBufferSize(_fd);
                    sizeSet = _sndSize;
                }

                //
                // Warn if the size that was set is less than the requested size.
                //
                if(sizeSet < sizeRequested)
                {
                    _instance.logger().warning("UDP " + direction + " buffer size: requested size of "
                                    + sizeRequested + " adjusted to " + sizeSet);
                }
            }
        }
    }

    private void configureMulticast(java.net.InetSocketAddress group, String interfaceAddr, int ttl)
    {
        try
        {
            java.net.NetworkInterface intf = null;

            if(interfaceAddr.length() != 0)
            {
                intf = java.net.NetworkInterface.getByName(interfaceAddr);
                if(intf == null)
                {
                    try
                    {
                        intf = java.net.NetworkInterface.getByInetAddress(
                            java.net.InetAddress.getByName(interfaceAddr));
                    }
                    catch(Exception ex)
                    {
                    }
                }
            }

            if(group != null)
            {
                //
                // Join multicast group.
                //
                boolean join = false;
                if(intf != null)
                {
                    _fd.join(group.getAddress(), intf);
                    join = true;
                }
                else
                {
                    //
                    // If the user doesn't specify an interface, we join to the multicast group with every
                    // interface that supports multicast and has a configured address with the same protocol
                    // as the group address protocol.
                    //
                    int protocol = group.getAddress().getAddress().length == 4 ? Network.EnableIPv4 :
                                                                                 Network.EnableIPv6;

                    java.util.List<java.net.NetworkInterface> interfaces =
                                java.util.Collections.list(java.net.NetworkInterface.getNetworkInterfaces());
                    for(java.net.NetworkInterface iface : interfaces)
                    {
                        if(!iface.supportsMulticast())
                        {
                            continue;
                        }

                        boolean hasProtocolAddress = false;
                        java.util.List<java.net.InetAddress> addresses =
                            java.util.Collections.list(iface.getInetAddresses());
                        for(java.net.InetAddress address : addresses)
                        {
                            if(address.getAddress().length == 4 && protocol == Network.EnableIPv4 ||
                               address.getAddress().length != 4 && protocol == Network.EnableIPv6)
                            {
                                hasProtocolAddress = true;
                                break;
                            }
                        }

                        if(hasProtocolAddress)
                        {
                            _fd.join(group.getAddress(), iface);
                            join = true;
                        }
                    }

                    if(!join)
                    {
                        throw new Ice.SocketException(new IllegalArgumentException(
                                                    "There aren't any interfaces that support multicast, " +
                                                    "or the interfaces that support it\n" +
                                                    "are not configured for the group protocol. " +
                                                    "Cannot join the mulitcast group."));
                    }
                }
            }
            else if(intf != null)
            {
                //
                // Otherwise, set the multicast interface if specified.
                //
                _fd.setOption(java.net.StandardSocketOptions.IP_MULTICAST_IF, intf);
            }

            if(ttl != -1)
            {
                _fd.setOption(java.net.StandardSocketOptions.IP_MULTICAST_TTL, ttl);
            }
        }
        catch(Exception ex)
        {
            throw new Ice.SocketException(ex);
        }
    }

    protected synchronized void finalize()
        throws Throwable
    {
        try
        {
            IceUtilInternal.Assert.FinalizerAssert(_fd == null);
        }
        catch(java.lang.Exception ex)
        {
        }
        finally
        {
            super.finalize();
        }
    }

    private ProtocolInstance _instance;

    private int _state;
    private int _rcvSize;
    private int _sndSize;
    private java.nio.channels.DatagramChannel _fd;
    private java.net.InetSocketAddress _addr;
    private java.net.InetSocketAddress _mcastAddr = null;
    private java.net.InetSocketAddress _peerAddr = null;

    //
    // The maximum IP datagram size is 65535. Subtract 20 bytes for the IP header and 8 bytes for the UDP header
    // to get the maximum payload.
    //
    private final static int _udpOverhead = 20 + 8;
    private final static int _maxPacketSize = 65535 - _udpOverhead;

    private static final int StateNeedConnect = 0;
    private static final int StateConnected = 1;
    private static final int StateNotConnected = 2;
}