summaryrefslogtreecommitdiff
path: root/java/src/IceInternal/Network.java
blob: fb1e0c6961ed53fc2ab03980d4a32d0c7a84e5fe (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
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
// **********************************************************************
//
// Copyright (c) 2003-2006 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;

public final class Network
{
    public static boolean
    connectionLost(java.io.IOException ex)
    {
        //
        // TODO: The JDK raises a generic IOException for certain
        // cases of connection loss. Unfortunately, our only choice is
        // to search the exception message for distinguishing phrases.
        //

        String msg = ex.getMessage().toLowerCase();

        if(msg != null)
        {
            final String[] msgs =
            {
                "connection reset by peer", // ECONNRESET
                "cannot send after socket shutdown", // ESHUTDOWN (Win32)
                "cannot send after transport endpoint shutdown", // ESHUTDOWN (Linux)
                "software caused connection abort", // ECONNABORTED
                "an existing connection was forcibly closed", // unknown
	        "connection closed by remote host", // unknown
	        "an established connection was aborted by the software in your host machine", // unknown (Win32)
	        "broken pipe", // EPIPE
		"there is no process to read data written to a pipe", // EPIPE? (AIX JDK 1.4.2)
		"socket is closed" // unknown (AIX JDK 1.4.2)
            };

            for(int i = 0; i < msgs.length; i++)
            {
                if(msg.indexOf(msgs[i]) != -1)
                {
                    return true;
                }
            }
        }

        return false;
    }

    public static boolean
    connectionRefused(java.net.ConnectException ex)
    {
        //
        // The JDK raises a generic ConnectException when the server
        // actively refuses a connection. Unfortunately, our only
        // choice is to search the exception message for
        // distinguishing phrases.
        //

        String msg = ex.getMessage().toLowerCase();

        if(msg != null)
        {
            final String[] msgs =
            {
                "connection refused", // ECONNREFUSED
		"remote host refused an attempted connect operation" // ECONNREFUSED (AIX JDK 1.4.2)
            };

            for(int i = 0; i < msgs.length; i++)
            {
                if(msg.indexOf(msgs[i]) != -1)
                {
                    return true;
                }
            }
        }

        return false;
    }

    public static boolean
    notConnected(java.net.SocketException ex)
    {
	String msg = ex.getMessage().toLowerCase();
	if(msg.indexOf("transport endpoint is not connected") != -1)
	{
	    return true;
	}
	//
	// BUGFIX: We check for EINVAL because shutdown() under Mac OS
	// X returns EINVAL if the server side is gone.
	//
	else if(msg.indexOf("invalid argument") != -1)
	{
	    return true;
	}
	return false;
    }

    public static java.nio.channels.SocketChannel
    createTcpSocket()
    {
        try
        {
            java.nio.channels.SocketChannel fd = java.nio.channels.SocketChannel.open();
            java.net.Socket socket = fd.socket();
            socket.setTcpNoDelay(true);
            socket.setKeepAlive(true);
            return fd;
        }
        catch(java.io.IOException ex)
        {
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
    }

    public static java.nio.channels.ServerSocketChannel
    createTcpServerSocket()
    {
        try
        {
            java.nio.channels.ServerSocketChannel fd = java.nio.channels.ServerSocketChannel.open();
            //
            // It's not possible to set TCP_NODELAY or KEEP_ALIVE
            // on a server socket in Java
            //
            //java.net.Socket socket = fd.socket();
            //socket.setTcpNoDelay(true);
            //socket.setKeepAlive(true);
            return fd;
        }
        catch(java.io.IOException ex)
        {
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
    }

    public static java.nio.channels.DatagramChannel
    createUdpSocket()
    {
        try
        {
            return java.nio.channels.DatagramChannel.open();
        }
        catch(java.io.IOException ex)
        {
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
    }

    private static void
    closeSocketNoThrow(java.nio.channels.SelectableChannel fd)
    {
        try
	{
	    fd.close();
	}
	catch(java.io.IOException ex)
	{
	    // Ignore
	}
    }

    public static void
    closeSocket(java.nio.channels.SelectableChannel fd)
    {
	try
	{
	    fd.close();
	}
	catch(java.io.IOException ex)
	{
	    Ice.SocketException se = new Ice.SocketException();
	    se.initCause(ex);
	    throw se;
	}
    }

    public static void
    setBlock(java.nio.channels.SelectableChannel fd, boolean block)
    {
        try
        {
            fd.configureBlocking(block);
        }
        catch(java.io.IOException ex)
        {
	    closeSocketNoThrow(fd);
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
    }

    public static java.net.InetSocketAddress
    doBind(java.nio.channels.ServerSocketChannel fd, java.net.InetSocketAddress addr)
    {
        try
        {
            java.net.ServerSocket sock = fd.socket();
            sock.bind(addr);
            return (java.net.InetSocketAddress)sock.getLocalSocketAddress();
        }
        catch(java.io.IOException ex)
        {
	    closeSocketNoThrow(fd);
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
    }

    public static java.net.InetSocketAddress
    doBind(java.nio.channels.DatagramChannel fd, java.net.InetSocketAddress addr)
    {
        try
        {
            java.net.DatagramSocket sock = fd.socket();
            sock.bind(addr);
            return (java.net.InetSocketAddress)sock.getLocalSocketAddress();
        }
        catch(java.io.IOException ex)
        {
	    closeSocketNoThrow(fd);
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
    }

    public static void
    doConnect(java.nio.channels.SocketChannel fd, java.net.InetSocketAddress addr, int timeout)
    {
        try
        {
            if(!fd.connect(addr))
            {
                int delay;
                if(timeout > 0 && timeout < 100)
                {
                    delay = timeout;
                }
                else
                {
                    delay = 100; // 100 ms
                }

                int timer = 0;
                while(!fd.finishConnect())
                {
                    if(timeout > 0 && timer >= timeout)
                    {
                        closeSocketNoThrow(fd);
                        throw new Ice.ConnectTimeoutException();
                    }
                    try
                    {
                        Thread.sleep(delay);
                        timer += delay;
                    }
                    catch(InterruptedException ex)
                    {
                    }
                }
            }
        }
        catch(java.net.ConnectException ex)
        {
	    closeSocketNoThrow(fd);

            Ice.ConnectFailedException se;
	    if(connectionRefused(ex))
	    {
		se = new Ice.ConnectionRefusedException();
	    }
	    else
	    {
		se = new Ice.ConnectFailedException();
	    }
            se.initCause(ex);
            throw se;
        }
        catch(java.io.IOException ex)
        {
	    closeSocketNoThrow(fd);
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
    }

    public static void
    doConnect(java.nio.channels.DatagramChannel fd, java.net.InetSocketAddress addr, int timeout)
    {
        try
        {
            fd.connect(addr);
        }
        catch(java.net.ConnectException ex)
        {
	    closeSocketNoThrow(fd);

            Ice.ConnectFailedException se;
	    if(connectionRefused(ex))
	    {
		se = new Ice.ConnectionRefusedException();
	    }
	    else
	    {
		se = new Ice.ConnectFailedException();
	    }
            se.initCause(ex);
            throw se;
        }
        catch(java.io.IOException ex)
        {
	    closeSocketNoThrow(fd);
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
    }

    public static java.nio.channels.SocketChannel
    doAccept(java.nio.channels.ServerSocketChannel fd, int timeout)
    {
        java.nio.channels.SocketChannel result = null;
        while(result == null)
        {
            try
            {
                result = fd.accept();
                if(result == null)
                {
                    java.nio.channels.Selector selector = java.nio.channels.Selector.open();

                    try
                    {
                        while(true)
                        {
                            try
                            {
                                java.nio.channels.SelectionKey key =
                                    fd.register(selector, java.nio.channels.SelectionKey.OP_ACCEPT);
                                int n;
                                if(timeout > 0)
                                {
                                    n = selector.select(timeout);
                                }
                                else if(timeout == 0)
                                {
                                    n = selector.selectNow();
                                }
                                else
                                {
                                    n = selector.select();
                                }

                                if(n == 0)
                                {
                                    throw new Ice.TimeoutException();
                                }

                                break;
                            }
                            catch(java.io.IOException ex)
                            {
				if(interrupted(ex))
				{
				    continue;
				}
                                Ice.SocketException se = new Ice.SocketException();
                                se.initCause(ex);
                                throw se;
                            }
                        }
                    }
                    finally
                    {
                        try
                        {
                            selector.close();
                        }
                        catch(java.io.IOException ex)
                        {
                            // Ignore
                        }
                    }
                }
            }
            catch(java.io.IOException ex)
            {
		if(interrupted(ex))
		{
		    continue;
		}
                Ice.SocketException se = new Ice.SocketException();
                se.initCause(ex);
                throw se;
            }
        }

        try
        {
            java.net.Socket socket = result.socket();
            socket.setTcpNoDelay(true);
            socket.setKeepAlive(true);
        }
        catch(java.io.IOException ex)
        {
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }

        return result;
    }

    public static void
    setSendBufferSize(java.nio.channels.DatagramChannel fd, int size)
    {
	try
	{
	    java.net.DatagramSocket socket = fd.socket();
	    socket.setSendBufferSize(size);
	}
        catch(java.io.IOException ex)
        {
	    closeSocketNoThrow(fd);
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
    }

    public static int
    getSendBufferSize(java.nio.channels.DatagramChannel fd)
    {
	int size;
	try
	{
	    java.net.DatagramSocket socket = fd.socket();
	    size = socket.getSendBufferSize();
	}
        catch(java.io.IOException ex)
        {
	    closeSocketNoThrow(fd);
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
	return size;
    }

    public static void
    setRecvBufferSize(java.nio.channels.ServerSocketChannel fd, int size)
    {
    	try
	{
	    java.net.ServerSocket socket = fd.socket();
	    socket.setReceiveBufferSize(size);
	}
        catch(java.io.IOException ex)
        {
	    closeSocketNoThrow(fd);
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
    }

    public static void
    setRecvBufferSize(java.nio.channels.DatagramChannel fd, int size)
    {
    	try
	{
	    java.net.DatagramSocket socket = fd.socket();
	    socket.setReceiveBufferSize(size);
	}
        catch(java.io.IOException ex)
        {
	    closeSocketNoThrow(fd);
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
    }

    public static int
    getRecvBufferSize(java.nio.channels.ServerSocketChannel fd)
    {
        int size;
	try
	{
	    java.net.ServerSocket socket = fd.socket();
	    size = socket.getReceiveBufferSize();
	}
        catch(java.io.IOException ex)
        {
	    closeSocketNoThrow(fd);
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
	return size;
    }

    public static int
    getRecvBufferSize(java.nio.channels.DatagramChannel fd)
    {
        int size;
	try
	{
	    java.net.DatagramSocket socket = fd.socket();
	    size = socket.getReceiveBufferSize();
	}
        catch(java.io.IOException ex)
        {
	    closeSocketNoThrow(fd);
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
	return size;
    }

    public static java.net.InetSocketAddress
    getAddress(String host, int port)
    {
        try
        {
            java.net.InetAddress[] addrs = java.net.InetAddress.getAllByName(host);
	    for(int i = 0; i < addrs.length; ++i)
	    {
	        if(addrs[i] instanceof java.net.Inet4Address)
		{
            	    return new java.net.InetSocketAddress(addrs[i], port);
		}
	    }
        }
        catch(java.net.UnknownHostException ex)
        {
	    Ice.DNSException e = new Ice.DNSException();
	    e.host = host;
	    throw e;
        }

	//
	// No Inet4Address available.
	//
	Ice.DNSException e = new Ice.DNSException();
	e.host = host;
	throw e;
    }

    public static java.net.InetAddress
    getLocalAddress()
    {
        java.net.InetAddress addr = null;

        try
        {
            addr = java.net.InetAddress.getLocalHost();
        }
        catch(java.net.UnknownHostException ex)
        {
            //
            // May be raised on DHCP systems.
            //
        }
        catch(NullPointerException ex)
        {
            //
            // Workaround for bug in JDK.
            //
        }

        if(addr == null || addr instanceof java.net.Inet6Address)
        {
            //
            // Iterate over the network interfaces and pick an IP
            // address (preferably not the loopback address).
            //
            java.net.InetAddress loopback = null;
	    java.util.ArrayList addrs = getLocalAddresses();
            java.util.Iterator iter = addrs.iterator();
            while(addr == null && iter.hasNext())
            {
		java.net.InetAddress a = (java.net.InetAddress)iter.next();
                if(!a.isLoopbackAddress())
                {
                    addr = a;
                }
                else
                {
                    loopback = a;
                }
            }

            if(addr == null)
            {
                addr = loopback; // Use the loopback address as the last resort.
            }
        }

        assert(addr != null);
        return addr;
    }

    public static java.util.ArrayList
    getLocalHosts()
    {
        java.util.ArrayList hosts = new java.util.ArrayList();
        java.util.ArrayList addrs = getLocalAddresses();
	java.util.Iterator iter = addrs.iterator();
	while(iter.hasNext())
	{
	    hosts.add(((java.net.InetAddress)iter.next()).getHostAddress());
	}
	return hosts;
    }

    public static java.util.ArrayList
    getLocalAddresses()
    {
        java.util.ArrayList result = new java.util.ArrayList();

	try
	{
	    java.util.Enumeration ifaces = java.net.NetworkInterface.getNetworkInterfaces();
	    while(ifaces.hasMoreElements())
	    {
                java.net.NetworkInterface iface = (java.net.NetworkInterface)ifaces.nextElement();
                java.util.Enumeration addrs = iface.getInetAddresses();
		while(addrs.hasMoreElements())
		{
		    java.net.InetAddress addr = (java.net.InetAddress)addrs.nextElement();
		    if(!(addr instanceof java.net.Inet6Address))
		    {
	                result.add(addr);
		    }
		}
	    }
	}
	catch(java.net.SocketException e)
	{
	    Ice.SocketException se = new Ice.SocketException();
	    se.initCause(e);
	    throw se;
	}

	return result;
    }

    public static final class SocketPair
    {
        public java.nio.channels.spi.AbstractSelectableChannel source;
        public java.nio.channels.WritableByteChannel sink;
    }

    public static SocketPair
    createPipe()
    {
        SocketPair fds = new SocketPair();

	//
	// BUGFIX: This method should really be very simple.
	// Unfortunately, using a pipe causes a kernel crash under
	// MacOS 10.3.9.
	//
	//try
	//{
	//   java.nio.channels.Pipe pipe = java.nio.channels.Pipe.open();
	//   fds.sink = pipe.sink();
	//   fds.source = pipe.source();
	//}
        //catch(java.io.IOException ex)
	//{
	//   Ice.SocketException se = new Ice.SocketException();
	//   se.initCause(ex);
	//   throw se;
	//}
	//
	
        java.nio.channels.ServerSocketChannel fd = createTcpServerSocket();
	
	java.net.InetSocketAddress addr = new java.net.InetSocketAddress("127.0.0.1", 0);
	
	addr = doBind(fd, addr);
	
        try
	{
            java.nio.channels.SocketChannel sink = createTcpSocket();
	    fds.sink = sink;
	    doConnect(sink, addr, -1);
            try
	    {
		fds.source = doAccept(fd, -1);
	    }
	    catch(Ice.LocalException ex)
            {
		try
		{
                    fds.sink.close();
		}
		catch(java.io.IOException e)
		{
                }
		throw ex;
	    }
        }
	finally
	{
 	    closeSocketNoThrow(fd);
	}
	
	return fds;
    }
    
    public static String
    fdToString(java.nio.channels.SelectableChannel fd)
    {
	if(fd == null)
	{
	    return "<closed>";
	}

	java.net.InetAddress localAddr = null, remoteAddr = null;
	int localPort = -1, remotePort = -1;

	if(fd instanceof java.nio.channels.SocketChannel)
	{
	    java.net.Socket socket = ((java.nio.channels.SocketChannel)fd).socket();
	    localAddr = socket.getLocalAddress();
	    localPort = socket.getLocalPort();
	    remoteAddr = socket.getInetAddress();
	    remotePort = socket.getPort();
	}
	else if(fd instanceof java.nio.channels.DatagramChannel)
	{
	    java.net.DatagramSocket socket = ((java.nio.channels.DatagramChannel)fd).socket();
	    localAddr = socket.getLocalAddress();
	    localPort = socket.getLocalPort();
	    remoteAddr = socket.getInetAddress();
	    remotePort = socket.getPort();
	}
	else
	{
	    assert(false);
	}

	return addressesToString(localAddr, localPort, remoteAddr, remotePort);
    }

    public static String
    fdToString(java.net.Socket fd)
    {
	if(fd == null)
	{
	    return "<closed>";
	}

	java.net.InetAddress localAddr = fd.getLocalAddress();
	int localPort = fd.getLocalPort();
	java.net.InetAddress remoteAddr = fd.getInetAddress();
	int remotePort = fd.getPort();

	return addressesToString(localAddr, localPort, remoteAddr, remotePort);
    }

    public static String
    addressesToString(java.net.InetAddress localAddr, int localPort, java.net.InetAddress remoteAddr, int remotePort)
    {
	StringBuffer s = new StringBuffer();
	s.append("local address = ");
	s.append(localAddr.getHostAddress());
	s.append(':');
	s.append(localPort);
	if(remoteAddr == null)
	{
	    s.append("\nremote address = <not connected>");
	}
	else
	{
	    s.append("\nremote address = ");
	    s.append(remoteAddr.getHostAddress());
	    s.append(':');
	    s.append(remotePort);
	}

	return s.toString();
    }

    public static String
    addrToString(java.net.InetSocketAddress addr)
    {
        StringBuffer s = new StringBuffer();
        s.append(addr.getAddress().getHostAddress());
        s.append(':');
        s.append(addr.getPort());
        return s.toString();
    }

    public static boolean
    interrupted(java.io.IOException ex)
    {
	return ex instanceof java.io.InterruptedIOException ||
	    ex.getMessage().indexOf("Interrupted system call") >= 0 ||
	    ex.getMessage().indexOf("A system call received an interrupt") >= 0; // AIX JDK 1.4.2
    }
}