File: SocketImplCombinations.java

package info (click to toggle)
openjdk-21 21.0.8%2B9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 823,976 kB
  • sloc: java: 5,613,338; xml: 1,643,607; cpp: 1,296,296; ansic: 420,291; asm: 404,850; objc: 20,994; sh: 15,271; javascript: 11,245; python: 6,895; makefile: 2,362; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (864 lines) | stat: -rw-r--r-- 29,659 bytes parent folder | download | duplicates (11)
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
/*
 * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test
 * @bug 8220493
 * @modules java.base/java.net:+open java.base/sun.nio.ch:+open
 * @run testng/othervm SocketImplCombinations
 * @summary Test Socket and ServerSocket with combinations of SocketImpls
 */

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketImpl;
import java.net.SocketImplFactory;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.function.BiConsumer;

import org.testng.annotations.Test;
import static org.testng.Assert.*;

@Test
public class SocketImplCombinations {

    /**
     * Test creating an unconnected Socket, it should be created with a platform SocketImpl.
     */
    public void testNewSocket1() throws IOException {
        try (Socket s = new Socket()) {
            SocketImpl si = getSocketImpl(s);
            assertTrue(isSocksSocketImpl(si));
            SocketImpl delegate = getDelegate(si);
            assertTrue(isPlatformSocketImpl(delegate));
        }
    }

    /**
     * Test creating a connected Socket, it should be created with a platform SocketImpl.
     */
    public void testNewSocket2() throws IOException {
        try (ServerSocket ss = boundServerSocket()) {
            try (Socket s = new Socket(ss.getInetAddress(), ss.getLocalPort())) {
                SocketImpl si = getSocketImpl(s);
                assertTrue(isSocksSocketImpl(si));
                SocketImpl delegate = getDelegate(si);
                assertTrue(isPlatformSocketImpl(delegate));
            }
        }
    }

    /**
     * Test creating a Socket for a DIRECT connection, it should be created with a
     * platform SocketImpl.
     */
    public void testNewSocket3() throws IOException {
        try (Socket s = new Socket(Proxy.NO_PROXY)) {
            SocketImpl si = getSocketImpl(s);
            assertTrue(isPlatformSocketImpl(si));
        }
    }

    /**
     * Test creating a Socket for a SOCKS connection, it should be created with a
     * SOCKS SocketImpl.
     */
    public void testNewSocket4() throws IOException {
        var address = new InetSocketAddress("127.0.0.1", 1080);
        var socksProxy = new Proxy(Proxy.Type.SOCKS, address);
        try (Socket s = new Socket(socksProxy)) {
            SocketImpl si = getSocketImpl(s);
            assertTrue(isSocksSocketImpl(si));
            SocketImpl delegate = getDelegate(si);
            assertTrue(isPlatformSocketImpl(delegate));
        }
    }

    /**
     * Test creating a Socket for a HTTP proxy connection, it should be created with
     * a HTTP proxy SocketImpl.
     */
    public void testNewSocket5() throws IOException {
        var address = new InetSocketAddress("127.0.0.1", 8080);
        var httpProxy = new Proxy(Proxy.Type.HTTP, address);
        try (Socket s = new Socket(httpProxy)) {
            SocketImpl si = getSocketImpl(s);
            assertTrue(isHttpConnectSocketImpl(si));
            SocketImpl delegate = getDelegate(si);
            assertTrue(isPlatformSocketImpl(delegate));
        }
    }

    /**
     * Test creating a Socket no SocketImpl. A platform SocketImpl should be
     * created lazily.
     */
    public void testNewSocket6() throws IOException {
        Socket s = new Socket((SocketImpl) null) { };
        try (s) {
            assertTrue(getSocketImpl(s) == null);
            s.bind(loopbackSocketAddress());   // force SocketImpl to be created
            SocketImpl si = getSocketImpl(s);
            assertTrue(isSocksSocketImpl(si));
            SocketImpl delegate = getDelegate(si);
            assertTrue(isPlatformSocketImpl(delegate));
        }
    }

    /**
     * Test creating a Socket with a custom SocketImpl.
     */
    public void testNewSocket7() throws IOException {
        Socket s = new Socket(new CustomSocketImpl(false)) { };
        try (s) {
            SocketImpl si = getSocketImpl(s);
            assertTrue(si instanceof CustomSocketImpl);
        }
    }

    /**
     * Test creating a Socket when there is a SocketImplFactory set.
     */
    public void testNewSocket8() throws IOException {
        setSocketSocketImplFactory(() -> new CustomSocketImpl(false));
        try (Socket s = new Socket()) {
            SocketImpl si = getSocketImpl(s);
            assertTrue(si instanceof CustomSocketImpl);
        } finally {
            setSocketSocketImplFactory(null);
        }
    }

    /**
     * Test creating a Socket for a DIRECT connection when there is a
     * SocketImplFactory set.
     */
    public void testNewSocket9() throws IOException {
        setSocketSocketImplFactory(() -> new CustomSocketImpl(false));
        try (Socket s = new Socket(Proxy.NO_PROXY)) {
            SocketImpl si = getSocketImpl(s);
            assertTrue(si instanceof CustomSocketImpl);
        } finally {
            setSocketSocketImplFactory(null);
        }
    }

    /**
     * Test creating a Socket for a SOCKS connection when there is a
     * SocketImplFactory set.
     */
    public void testNewSocket10() throws IOException {
        var address = new InetSocketAddress("127.0.0.1", 1080);
        var socksProxy = new Proxy(Proxy.Type.SOCKS, address);
        setSocketSocketImplFactory(() -> new CustomSocketImpl(false));
        try (Socket s = new Socket(socksProxy)) {
            SocketImpl si = getSocketImpl(s);
            assertTrue(isSocksSocketImpl(si));
            SocketImpl delegate = getDelegate(si);
            assertTrue(isPlatformSocketImpl(delegate));
        } finally {
            setSocketSocketImplFactory(null);
        }
    }

    /**
     * Test creating a Socket for a HTTP proxy connection when there is a
     * SocketImplFactory set.
     */
    public void testNewSocket11() throws IOException {
        var address = new InetSocketAddress("127.0.0.1", 8080);
        var httpProxy = new Proxy(Proxy.Type.HTTP, address);
        setSocketSocketImplFactory(() -> new CustomSocketImpl(false));
        try (Socket s = new Socket(httpProxy)) {
            SocketImpl si = getSocketImpl(s);
            assertTrue(isHttpConnectSocketImpl(si));
            SocketImpl delegate = getDelegate(si);
            assertTrue(isPlatformSocketImpl(delegate));
        } finally {
            setSocketSocketImplFactory(null);
        }
    }

    /**
     * Test creating a Socket no SocketImpl when there is a SocketImplFactory set.
     */
    public void testNewSocket12() throws IOException {
        setSocketSocketImplFactory(() -> new CustomSocketImpl(false));
        try {
            Socket s = new Socket((SocketImpl) null) { };
            try (s) {
                assertTrue(getSocketImpl(s) == null);
                s.bind(loopbackSocketAddress());   // force SocketImpl to be created
                assertTrue(getSocketImpl(s) instanceof CustomSocketImpl);
            }
        } finally {
            setSocketSocketImplFactory(null);
        }
    }

    /**
     * Test creating an unbound ServerSocket, it should be created with a platform
     * SocketImpl.
     */
    public void testNewServerSocket1() throws IOException {
        try (ServerSocket ss = new ServerSocket()) {
            SocketImpl si = getSocketImpl(ss);
            assertTrue(isPlatformSocketImpl(si));
        }
    }

    /**
     * Test creating a bound ServerSocket, it should be created with a platform
     * SocketImpl.
     */
    public void testNewServerSocket2() throws IOException {
        try (ServerSocket ss = new ServerSocket(0)) {
            SocketImpl si = getSocketImpl(ss);
            assertTrue(isPlatformSocketImpl(si));
        }
    }

    /**
     * Test creating a ServerSocket with a custom SocketImpl.
     */
    public void testNewServerSocket3() throws IOException {
        ServerSocket ss = new ServerSocket(new CustomSocketImpl(true)) { };
        try (ss) {
            SocketImpl si = getSocketImpl(ss);
            assertTrue(si instanceof CustomSocketImpl);
        }
    }

    /**
     * Test creating an unbound ServerSocket when there is a SocketImplFactory set.
     */
    public void testNewServerSocket4() throws IOException {
        setServerSocketImplFactory(() -> new CustomSocketImpl(true));
        try (ServerSocket ss = new ServerSocket()) {
            SocketImpl si = getSocketImpl(ss);
            assertTrue(si instanceof CustomSocketImpl);
        } finally {
            setServerSocketImplFactory(null);
        }
    }

    /**
     * Test creating a bound ServerSocket when there is a SocketImplFactory set.
     */
    public void testNewServerSocket5() throws IOException {
        setServerSocketImplFactory(() -> new CustomSocketImpl(true));
        try (ServerSocket ss = new ServerSocket(0)) {
            SocketImpl si = getSocketImpl(ss);
            assertTrue(si instanceof CustomSocketImpl);
        } finally {
            setServerSocketImplFactory(null);
        }
    }

    /**
     * Test ServerSocket.accept. The ServerSocket uses a platform SocketImpl,
     * the Socket to accept is created with no SocketImpl.
     */
    public void testServerSocketAccept1() throws IOException {
        var socket = new Socket((SocketImpl) null) { };
        assertTrue(getSocketImpl(socket) == null);

        serverSocketAccept(socket, (ss, s) -> {
            assertTrue(isPlatformSocketImpl(getSocketImpl(ss)));
            assertTrue(s == socket);
            SocketImpl si = getSocketImpl(s);
            assertTrue(isPlatformSocketImpl(si));
            checkFields(si);
        });
    }

    /**
     * Test ServerSocket.accept. The ServerSocket uses a platform SocketImpl,
     * the Socket to accept is created with no SocketImpl, and there is a custom
     * client SocketImplFactory set.
     */
    public void testServerSocketAccept2() throws IOException {
        var socket = new Socket((SocketImpl) null) { };
        assertTrue(getSocketImpl(socket) == null);

        serverSocketAccept(socket, () -> new CustomSocketImpl(false), (ss, s) -> {
            assertTrue(isPlatformSocketImpl(getSocketImpl(ss)));
            assertTrue(s == socket);
            SocketImpl si = getSocketImpl(s);
            assertTrue(isPlatformSocketImpl(si));
            checkFields(si);
        });
    }

    /**
     * Test ServerSocket.accept. The ServerSocket uses a platform SocketImpl,
     * the Socket to accept is created with a SocketImpl that delegates to a
     * platform SocketImpl.
     */
    public void testServerSocketAccept3() throws IOException {
        var socket = new Socket();
        SocketImpl si = getSocketImpl(socket);
        assertTrue(isSocksSocketImpl(si));
        SocketImpl delegate = getDelegate(si);
        assertTrue(isPlatformSocketImpl(delegate));

        serverSocketAccept(socket, (ss, s) -> {
            assertTrue(isPlatformSocketImpl(getSocketImpl(ss)));
            assertTrue(s == socket);
            SocketImpl psi = getSocketImpl(socket);
            assertTrue(isPlatformSocketImpl(psi));
            checkFields(psi);
        });
    }

    /**
     * Test ServerSocket.accept. The ServerSocket uses a platform SocketImpl,
     * the Socket to accept is created with a custom SocketImpl.
     */
    public void testServerSocketAccept4a() throws IOException {
        SocketImpl clientImpl = new CustomSocketImpl(false);
        Socket socket = new Socket(clientImpl) { };
        assertTrue(getSocketImpl(socket) == clientImpl);

        try (ServerSocket ss = serverSocketToAccept(socket)) {
            expectThrows(IOException.class, ss::accept);
        } finally {
            socket.close();
        }
    }

    public void testServerSocketAccept4b() throws IOException {
        SocketImpl clientImpl = new CustomSocketImpl(false);
        Socket socket = new Socket(clientImpl) { };
        assertTrue(getSocketImpl(socket) == clientImpl);

        setSocketSocketImplFactory(() -> new CustomSocketImpl(false));
        try (ServerSocket ss = serverSocketToAccept(socket)) {
            expectThrows(IOException.class, ss::accept);
        } finally {
            setSocketSocketImplFactory(null);
            socket.close();
        }
    }

    /**
     * Test ServerSocket.accept. The ServerSocket uses a custom SocketImpl,
     * the Socket to accept is created no SocketImpl.
     */
    public void testServerSocketAccept5a() throws IOException {
        SocketImpl serverImpl = new CustomSocketImpl(true);
        try (ServerSocket ss = new ServerSocket(serverImpl) { }) {
            ss.bind(loopbackSocketAddress());
            expectThrows(IOException.class, ss::accept);
        }
    }

    public void testServerSocketAccept5b() throws IOException {
        var socket = new Socket((SocketImpl) null) { };
        assertTrue(getSocketImpl(socket) == null);

        SocketImpl serverImpl = new CustomSocketImpl(true);
        try (ServerSocket ss = serverSocketToAccept(serverImpl, socket)) {
            expectThrows(IOException.class, ss::accept);
        } finally {
            socket.close();
        }
    }

    public void testServerSocketAccept5c() throws IOException {
        setServerSocketImplFactory(() -> new CustomSocketImpl(true));
        try (ServerSocket ss = new ServerSocket(0)) {
            expectThrows(IOException.class, ss::accept);
        } finally {
            setServerSocketImplFactory(null);
        }
    }

    public void testServerSocketAccept5d() throws IOException {
        var socket = new Socket((SocketImpl) null) { };
        assertTrue(getSocketImpl(socket) == null);

        setServerSocketImplFactory(() -> new CustomSocketImpl(true));
        try (ServerSocket ss = serverSocketToAccept(socket)) {
            expectThrows(IOException.class, ss::accept);
        } finally {
            setServerSocketImplFactory(null);
            socket.close();
        }
    }

    /**
     * Test ServerSocket.accept. The ServerSocket uses a custom SocketImpl,
     * the Socket to accept is created with no SocketImpl, and there is a custom
     * client SocketImplFactory set.
     */
    public void testServerSocketAccept6() throws Exception {
        var socket = new Socket((SocketImpl) null) { };
        assertTrue(getSocketImpl(socket) == null);

        SocketImpl serverImpl = new CustomSocketImpl(true);
        SocketImplFactory clientFactory = () -> new CustomSocketImpl(false);
        serverSocketAccept(serverImpl, socket, clientFactory, (ss, s) -> {
            assertTrue(getSocketImpl(ss) == serverImpl);
            SocketImpl si = getSocketImpl(s);
            assertTrue(si instanceof CustomSocketImpl);
            checkFields(si);
        });
    }

    /**
     * Test ServerSocket.accept. The ServerSocket uses a custom SocketImpl,
     * the Socket to accept is created with a SocketImpl that delegates to a
     * platform SocketImpl.
     */
    public void testServerSocketAccept7a() throws IOException {
        var socket = new Socket();
        SocketImpl si = getSocketImpl(socket);
        assertTrue(isSocksSocketImpl(si));
        SocketImpl delegate = getDelegate(si);
        assertTrue(isPlatformSocketImpl(delegate));

        SocketImpl serverImpl = new CustomSocketImpl(true);
        try (ServerSocket ss = serverSocketToAccept(serverImpl, socket)) {
            expectThrows(IOException.class, ss::accept);
        } finally {
            socket.close();
        }
    }

    public void testServerSocketAccept7b() throws IOException {
        var socket = new Socket();
        SocketImpl si = getSocketImpl(socket);
        assertTrue(isSocksSocketImpl(si));
        SocketImpl delegate = getDelegate(si);
        assertTrue(isPlatformSocketImpl(delegate));

        setServerSocketImplFactory(() -> new CustomSocketImpl(true));
        try (ServerSocket ss = serverSocketToAccept(socket)) {
            expectThrows(IOException.class, ss::accept);
        } finally {
            setServerSocketImplFactory(null);
            socket.close();
        }
    }

    /**
     * Test ServerSocket.accept. The ServerSocket uses a custom SocketImpl,
     * the Socket to accept is created with a custom SocketImpl.
     */
    public void testServerSocketAccept8() throws Exception {
        SocketImpl clientImpl = new CustomSocketImpl(false);
        Socket socket = new Socket(clientImpl) { };
        assertTrue(getSocketImpl(socket) == clientImpl);

        SocketImpl serverImpl = new CustomSocketImpl(true);
        SocketImplFactory clientFactory = () -> new CustomSocketImpl(false);
        serverSocketAccept(serverImpl, socket, clientFactory, (ss, s) -> {
            assertTrue(getSocketImpl(ss) == serverImpl);
            assertTrue(getSocketImpl(s) == clientImpl);
            checkFields(clientImpl);
        });
    }

    /**
     * Creates a ServerSocket that returns the given Socket from accept.
     * The consumer is invoked with the server socket and the accepted socket.
     */
    static void serverSocketAccept(Socket socket,
                                   BiConsumer<ServerSocket, Socket> consumer)
        throws IOException
    {
        Socket s1 = null;
        Socket s2 = null;
        try (ServerSocket ss = serverSocketToAccept(socket)) {
            s1 = new Socket(ss.getInetAddress(), ss.getLocalPort());
            s2 = ss.accept();
            consumer.accept(ss, s2);
        } finally {
            if (s1 != null) s1.close();
            if (s2 != null) s2.close();
        }
    }

    /**
     * Creates a ServerSocket that returns the given Socket from accept. The
     * given SocketImplFactory is set during the accept and the consumer is
     * invoked when the server socket and the accepted socket.
     */
    static void serverSocketAccept(Socket socket,
                                   SocketImplFactory factory,
                                   BiConsumer<ServerSocket, Socket> consumer)
        throws IOException
    {
        Socket s1 = null;
        Socket s2 = null;
        try (ServerSocket ss = serverSocketToAccept(socket)) {
            s1 = new Socket(ss.getInetAddress(), ss.getLocalPort());
            setSocketSocketImplFactory(factory);
            try {
                s2 = ss.accept();
            } finally {
                setSocketSocketImplFactory(null);
            }
            consumer.accept(ss, s2);
        } finally {
            if (s1 != null) s1.close();
            if (s2 != null) s2.close();
        }
    }

    /**
     * Creates a ServerSocket with a SocketImpl returns the given Socket from
     * accept. The given SocketImplFactory is set during the accept and the
     * consumer is invoked when the server socket and the accepted socket.
     */
    static void serverSocketAccept(SocketImpl impl,
                                   Socket socket,
                                   SocketImplFactory factory,
                                   BiConsumer<ServerSocket, Socket> consumer)
        throws IOException
    {
        Socket s1 = null;
        Socket s2 = null;
        try (ServerSocket ss = serverSocketToAccept(impl, socket)) {
            s1 = new Socket(ss.getInetAddress(), ss.getLocalPort());
            setSocketSocketImplFactory(factory);
            try {
                s2 = ss.accept();
            } finally {
                setSocketSocketImplFactory(null);
            }
            consumer.accept(ss, s2);
        } finally {
            if (s1 != null) s1.close();
            if (s2 != null) s2.close();
        }
    }

    /**
     * Returns a new InetSocketAddress with the loopback interface
     * and port 0.
     */
    static InetSocketAddress loopbackSocketAddress() {
        InetAddress loopback = InetAddress.getLoopbackAddress();
        return new InetSocketAddress(loopback, 0);
    }

    /**
     * Returns a ServerSocket bound to a port on the loopback address
     */
    static ServerSocket boundServerSocket() throws IOException {
        ServerSocket ss = new ServerSocket();
        ss.bind(loopbackSocketAddress());
        return ss;
    }

    /**
     * Creates a ServerSocket that returns the given Socket from accept.
     */
    static ServerSocket serverSocketToAccept(Socket s) throws IOException {
        ServerSocket ss = new ServerSocket() {
            @Override
            public Socket accept() throws IOException {
                implAccept(s);
                return s;
            }
        };
        ss.bind(loopbackSocketAddress());
        return ss;
    }

    /**
     * Creates a ServerSocket with a SocketImpl that returns the given Socket
     * from accept.
     */
    static ServerSocket serverSocketToAccept(SocketImpl impl, Socket s) throws IOException {
        ServerSocket ss = new ServerSocket(impl) {
            @Override
            public Socket accept() throws IOException {
                implAccept(s);
                return s;
            }
        };
        ss.bind(loopbackSocketAddress());
        return ss;
    }

    /**
     * Returns the socket's SocketImpl
     */
    static SocketImpl getSocketImpl(Socket s) {
        try {
            Field f = Socket.class.getDeclaredField("impl");
            f.setAccessible(true);
            return (SocketImpl) f.get(s);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Returns the server socket's SocketImpl
     */
    static SocketImpl getSocketImpl(ServerSocket ss) {
        try {
            Field f = ServerSocket.class.getDeclaredField("impl");
            f.setAccessible(true);
            return (SocketImpl) f.get(ss);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Returns the SocketImpl that the given SocketImpl delegates to
     */
    static SocketImpl getDelegate(SocketImpl si) {
        try {
            Class<?> clazz = Class.forName("java.net.DelegatingSocketImpl");
            Field f = clazz.getDeclaredField("delegate");
            f.setAccessible(true);
            return (SocketImpl) f.get(si);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Returns the value of a SocketImpl field
     */
    static <T> T get(SocketImpl si, String name) {
        try {
            Field f = SocketImpl.class.getDeclaredField(name);
            f.setAccessible(true);
            return (T) f.get(si);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Sets the value of SocketImpl field
     */
    static void set(SocketImpl si, String name, Object value) {
        try {
            Field f = SocketImpl.class.getDeclaredField(name);
            f.setAccessible(true);
            f.set(si, value);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Returns true if the SocketImpl is a PlatformSocketImpl
     */
    static boolean isPlatformSocketImpl(SocketImpl si) {
        try {
            Class<?> clazz = Class.forName("sun.net.PlatformSocketImpl");
            return clazz.isInstance(si);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Returns true if the SocketImpl is a SocksSocketImpl
     */
    static boolean isSocksSocketImpl(SocketImpl si) {
        try {
            Class<?> clazz = Class.forName("java.net.SocksSocketImpl");
            return clazz.isInstance(si);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Returns true if the SocketImpl is a HttpConnectSocketImpl
     */
    static boolean isHttpConnectSocketImpl(SocketImpl si) {
        try {
            Class<?> clazz = Class.forName("java.net.HttpConnectSocketImpl");
            return clazz.isInstance(si);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Socket.setSocketImplFactory(SocketImplFactory)
     */
    static void setSocketSocketImplFactory(SocketImplFactory factory) {
        try {
            Field f = Socket.class.getDeclaredField("factory");
            f.setAccessible(true);
            f.set(null, factory);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * ServerSocket.setSocketFactory(SocketImplFactory)
     */
    static void setServerSocketImplFactory(SocketImplFactory factory) {
        try {
            Field f = ServerSocket.class.getDeclaredField("factory");
            f.setAccessible(true);
            f.set(null, factory);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Checks the 4 protected fields of a SocketImpl to make sure that they
     * have been initialized.
     */
    static void checkFields(SocketImpl si) {
        FileDescriptor fd = get(si, "fd");
        InetAddress address = get(si, "address");
        int port = get(si, "port");
        int localport = get(si, "localport");
        assertTrue(fd.valid() && address != null && port != 0 && localport != 0);
    }

    /**
     * Custom SocketImpl that is layed on a SocketChannel or ServerSocketChannel
     */
    static class CustomSocketImpl extends SocketImpl {
        private final boolean server;
        private ServerSocketChannel ssc;
        private SocketChannel sc;

        CustomSocketImpl(boolean server) {
            this.server = server;
        }

        @Override
        protected void create(boolean stream) throws IOException {
            if (server) {
                ssc = ServerSocketChannel.open();
            } else {
                sc = SocketChannel.open();
            }
        }

        @Override
        protected void connect(String host, int port) throws IOException {
            connect(new InetSocketAddress(host, port), 0);
        }

        @Override
        protected void connect(InetAddress address, int port) throws IOException {
            connect(new InetSocketAddress(address, port), 0);
        }

        @Override
        protected void connect(SocketAddress remote, int timeout) throws IOException {
            sc.connect(remote);
            super.address = ((InetSocketAddress) remote).getAddress();
            super.port = ((InetSocketAddress) remote).getPort();
        }

        @Override
        protected void bind(InetAddress address, int port) throws IOException {
            if (server) {
                ssc.bind(new InetSocketAddress(address, port));
                super.localport = ssc.socket().getLocalPort();
            } else {
                sc.bind(new InetSocketAddress(address, port));
                super.localport = sc.socket().getLocalPort();
            }
            super.address = address;
        }

        @Override
        protected void listen(int backlog) {
            // do nothing
        }

        @Override
        protected void accept(SocketImpl si) throws IOException {
            SocketChannel peer = ssc.accept();
            FileDescriptor fd;
            try {
                Class<?> clazz = Class.forName("sun.nio.ch.SocketChannelImpl");
                Field f = clazz.getDeclaredField("fd");
                f.setAccessible(true);
                fd = (FileDescriptor) f.get(peer);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            set(si, "fd", fd);
            set(si, "address", peer.socket().getInetAddress());
            set(si, "port", peer.socket().getPort());
            set(si, "localport", peer.socket().getLocalPort());
        }

        @Override
        protected InputStream getInputStream() {
            throw new RuntimeException();
        }

        @Override
        protected OutputStream getOutputStream() {
            throw new RuntimeException();
        }

        @Override
        protected int available() {
            return 0;
        }

        @Override
        protected void close() {
        }

        @Override
        protected void sendUrgentData(int data) {
            throw new RuntimeException();
        }

        @Override
        public void setOption(int option, Object value) {
            throw new RuntimeException();
        }

        @Override
        public Object getOption(int option) {
            throw new RuntimeException();
        }
    }
}