summaryrefslogtreecommitdiff
path: root/x-net/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/SSLEngineImplTest.java
blob: c366d962e9cb63dd679d80f753b55abdac3be5c4 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You 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.apache.harmony.xnet.provider.jsse;

import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * SSLEngine implementation test.
 */
public class SSLEngineImplTest extends TestCase {

    /**
     * The cipher suites used for functionality testing.
     */
    private static final String[] cipher_suites = {
            "RSA_WITH_RC4_128_MD5",
            "RSA_WITH_DES_CBC_SHA",
            "DH_anon_EXPORT_WITH_DES40_CBC_SHA"
    };

    /**
     * Test logging switch.
     */
    private static boolean doLog = false;

    /**
     * Sets up the test case.
     */
    @Override
    public void setUp() throws Exception {
        if (doLog) {
            System.out.println("");
            System.out.println("========================");
            System.out.println("====== Running the test: " + getName());
            System.out.println("========================");
        }
    }

    /**
     * Tests the interaction between the engines.
     */
    public void testSelfInteraction() throws Exception {
        String[] protocols = { "SSLv3", "TLSv1" };
        for (int i = 0; i < cipher_suites.length; i++) {
            for (int j = 0; j < 2; j++) {
                if (doLog) {
                    System.out.println("\n===== Interact over suite: "
                            + cipher_suites[i]);
                }
                SSLEngine client = getEngine();
                SSLEngine server = getEngine();
                initEngines(client, server);

                doHandshake(client, server);
                doDataExchange(client, server);
                doClose(client, server);
            }
        }
    }

    /**
     * Tests the session negotiation process.
     */
    public void testHandshake() throws Exception {
        SSLEngine client = getEngine();
        SSLEngine server = getEngine();

        initEngines(client, server);

        // checks the impossibility of initial handshake
        // with the server not allowed to session creation
        doNoRenegotiationTest(client, server, true);

        client = getEngine();
        server = getEngine();
        initEngines(client, server);

        client.setUseClientMode(true);
        server.setUseClientMode(false);

        // do initial handshake
        doHandshake(client, server);

        // client initiates rehandshake
        client.beginHandshake();
        doHandshakeImpl(client, server);

        // server initiates rehandshake
        server.beginHandshake();
        doHandshakeImpl(client, server);

        // client initiates rehandshake while server invalidates
        // used session
        server.getSession().invalidate();
        client.beginHandshake();
        doHandshakeImpl(client, server);

        // server initiates rehandshake while client invalidates
        // used session
        client.getSession().invalidate();
        server.beginHandshake();
        doHandshakeImpl(client, server);

        client.getSession().invalidate();
        server.getSession().invalidate();
        doHandshake(client, server);

        doNoRenegotiationTest(client, server, false);

        doNoRenegotiationTest(server, client, false);

        doClose(client, server);
    }

    /**
     * setNeedClientAuth(boolean need) method testing.
     * getNeedClientAuth() method testing.
     */
    public void testSetGetNeedClientAuth() throws Exception {
        SSLEngine engine = getEngine();

        engine.setWantClientAuth(true);
        engine.setNeedClientAuth(false);
        assertFalse("Result differs from expected",
                engine.getNeedClientAuth());
        assertFalse("Socket did not reset its want client auth state",
                engine.getWantClientAuth());
        engine.setWantClientAuth(true);
        engine.setNeedClientAuth(true);
        assertTrue("Result differs from expected",
                engine.getNeedClientAuth());
        assertFalse("Socket did not reset its want client auth state",
                engine.getWantClientAuth());
    }

    /**
     * setWantClientAuth(boolean want) method testing.
     * getWantClientAuth() method testing.
     */
    public void testSetGetWantClientAuth() throws Exception {
        SSLEngine engine = getEngine();

        engine.setNeedClientAuth(true);
        engine.setWantClientAuth(false);
        assertFalse("Result differs from expected",
                engine.getWantClientAuth());
        assertFalse("Socket did not reset its want client auth state",
                engine.getNeedClientAuth());
        engine.setNeedClientAuth(true);
        engine.setWantClientAuth(true);
        assertTrue("Result differs from expected",
                engine.getWantClientAuth());
        assertFalse("Socket did not reset its want client auth state",
                engine.getNeedClientAuth());
    }

    /**
     * getSupportedCipherSuites() method testing.
     */
    public void testGetSupportedCipherSuites() throws Exception {
        SSLEngine engine = getEngine();
        String[] supported = engine.getSupportedCipherSuites();
        assertNotNull(supported);
        supported[0] = "NOT_SUPPORTED_CIPHER_SUITE";
        supported = engine.getEnabledCipherSuites();
        for (int i = 0; i < supported.length; i++) {
            if ("NOT_SUPPORTED_CIPHER_SUITE".equals(supported[i])) {
                fail("Modification of the returned result "
                        + "causes the modification of the internal state");
            }
        }
    }

    /**
     * getEnabledCipherSuites() method testing.
     */
    public void testGetEnabledCipherSuites() throws Exception {
        SSLEngine engine = getEngine();
        String[] enabled = engine.getEnabledCipherSuites();
        assertNotNull(enabled);
        String[] supported = engine.getSupportedCipherSuites();
        for (int i = 0; i < enabled.length; i++) {
            found:
            {
                for (int j = 0; j < supported.length; j++) {
                    if (enabled[i].equals(supported[j])) {
                        break found;
                    }
                }
                fail("Enabled suite does not belong to the set "
                        + "of supported cipher suites: " + enabled[i]);
            }
        }
        engine.setEnabledCipherSuites(supported);
        for (int i = 0; i < supported.length; i++) {
            enabled = new String[supported.length - i];
            System.arraycopy(supported, 0,
                    enabled, 0, supported.length - i);
            engine.setEnabledCipherSuites(enabled);
            String[] result = engine.getEnabledCipherSuites();
            if (result.length != enabled.length) {
                fail("Returned result differs from expected.");
            }
            for (int k = 0; k < result.length; k++) {
                found:
                {
                    for (int n = 0; n < enabled.length; n++) {
                        if (result[k].equals(enabled[n])) {
                            break found;
                        }
                    }
                    if (result.length != enabled.length) {
                        fail("Returned result does not correspond "
                                + "to expected.");
                    }
                }
            }
        }
    }

    /**
     * setEnabledCipherSuites(String[] suites) method testing.
     */
    public void testSetEnabledCipherSuites() throws Exception {
        SSLEngine engine = getEngine();
        String[] enabled = engine.getEnabledCipherSuites();
        assertNotNull(enabled);
        String[] supported = engine.getSupportedCipherSuites();
        for (int i = 0; i < enabled.length; i++) {
            found:
            {
                for (int j = 0; j < supported.length; j++) {
                    if (enabled[i].equals(supported[j])) {
                        break found;
                    }
                }
                fail("Enabled suite does not belong to the set "
                        + "of supported cipher suites: " + enabled[i]);
            }
        }
        engine.setEnabledCipherSuites(supported);
        engine.setEnabledCipherSuites(enabled);
        engine.setEnabledCipherSuites(supported);
        String[] more_than_supported = new String[supported.length + 1];
        for (int i = 0; i < supported.length + 1; i++) {
            more_than_supported[i]
                    = "NOT_SUPPORTED_CIPHER_SUITE";
            System.arraycopy(supported, 0,
                    more_than_supported, 0, i);
            System.arraycopy(supported, i,
                    more_than_supported, i + 1, supported.length - i);
            try {
                engine.setEnabledCipherSuites(more_than_supported);
                fail("Expected IllegalArgumentException was not thrown");
            } catch (IllegalArgumentException e) {
            }
        }
        enabled = engine.getEnabledCipherSuites();
        enabled[0] = "NOT_SUPPORTED_CIPHER_SUITE";
        enabled = engine.getEnabledCipherSuites();
        for (int i = 0; i < enabled.length; i++) {
            if ("NOT_SUPPORTED_CIPHER_SUITE".equals(enabled[i])) {
                fail("Modification of the returned result "
                        + "causes the modification of the internal state");
            }
        }
    }

    /**
     * getSupportedProtocols() method testing.
     */
    public void testGetSupportedProtocols() throws Exception {
        SSLEngine engine = getEngine();
        String[] supported = engine.getSupportedProtocols();
        assertNotNull(supported);
        assertFalse(supported.length == 0);
        supported[0] = "NOT_SUPPORTED_PROTOCOL";
        supported = engine.getSupportedProtocols();
        for (int i = 0; i < supported.length; i++) {
            if ("NOT_SUPPORTED_PROTOCOL".equals(supported[i])) {
                fail("Modification of the returned result "
                        + "causes the modification of the internal state");
            }
        }
    }

    /**
     * getEnabledProtocols() method testing.
     */
    public void testGetEnabledProtocols() throws Exception {
        SSLEngine engine = getEngine();
        String[] enabled = engine.getEnabledProtocols();
        assertNotNull(enabled);
        String[] supported = engine.getSupportedProtocols();
        for (int i = 0; i < enabled.length; i++) {
            found:
            {
                for (int j = 0; j < supported.length; j++) {
                    if (enabled[i].equals(supported[j])) {
                        break found;
                    }
                }
                fail("Enabled protocol does not belong to the set "
                        + "of supported protocols: " + enabled[i]);
            }
        }
        engine.setEnabledProtocols(supported);
        for (int i = 0; i < supported.length; i++) {
            enabled = new String[supported.length - i];
            System.arraycopy(supported, i,
                    enabled, 0, supported.length - i);
            engine.setEnabledProtocols(enabled);
            String[] result = engine.getEnabledProtocols();
            if (result.length != enabled.length) {
                fail("Returned result differs from expected.");
            }
            for (int k = 0; k < result.length; k++) {
                found:
                {
                    for (int n = 0; n < enabled.length; n++) {
                        if (result[k].equals(enabled[n])) {
                            break found;
                        }
                    }
                    if (result.length != enabled.length) {
                        fail("Returned result does not correspond "
                                + "to expected.");
                    }
                }
            }
        }
    }

    /**
     * setUseClientMode(boolean mode) method testing.
     * getUseClientMode() method testing.
     */
    public void testSetGetUseClientMode() throws Exception {
        SSLEngine engine = getEngine();

        engine.setUseClientMode(false);
        assertFalse("Result differs from expected",
                engine.getUseClientMode());
        engine.setUseClientMode(true);
        assertTrue("Result differs from expected",
                engine.getUseClientMode());

        engine.beginHandshake();
        try {
            engine.setUseClientMode(false);
            fail("Expected IllegalArgumentException was not thrown");
        } catch (IllegalArgumentException e) {
        }

        engine.wrap(ByteBuffer.allocate(0), ByteBuffer.allocate(
                engine.getSession().getPacketBufferSize()));
        try {
            engine.setUseClientMode(false);
            fail("Expected IllegalArgumentException was not thrown");
        } catch (IllegalArgumentException e) {
        }
    }

    /**
     * setEnableSessionCreation(boolean flag) method testing.
     * getEnableSessionCreation() method testing.
     */
    public void testSetGetEnableSessionCreation() throws Exception {
        SSLEngine engine = getEngine();

        engine.setEnableSessionCreation(false);
        assertFalse("Result differs from expected",
                engine.getEnableSessionCreation());
        engine.setEnableSessionCreation(true);
        assertTrue("Result differs from expected",
                engine.getEnableSessionCreation());
    }

    /**
     * getSession() method testing.
     */
    public void testGetSession() throws Exception {
        SSLEngine engine = getEngine();

        SSLSession session = engine.getSession();
        if ((session == null)
                || (!session.getCipherSuite()
                .endsWith("_NULL_WITH_NULL_NULL"))) {
            fail("Returned session is null "
                    + "or not TLS_NULL_WITH_NULL_NULL");
        }
    }

    /**
     * beginHandshake() method testing
     */
    public void testBeginHandshake() throws Exception {
        SSLEngine engine = getEngine();
        assertEquals("Incorrect initial handshake status",
                engine.getHandshakeStatus(),
                SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING);
        try {
            engine.beginHandshake();
            fail("Expected IllegalStateException was not thrown");
        } catch (IllegalStateException e) {
        }

        engine = getEngine();
        engine.setUseClientMode(false);
        engine.beginHandshake();
        assertEquals("Incorrect initial handshake status",
                engine.getHandshakeStatus(),
                SSLEngineResult.HandshakeStatus.NEED_UNWRAP);

        engine = getEngine();
        engine.setUseClientMode(true);
        engine.beginHandshake();
        assertEquals("Incorrect initial handshake status",
                engine.getHandshakeStatus(),
                SSLEngineResult.HandshakeStatus.NEED_WRAP);
    }

    /**
     * closeOutbound() method testing.
     */
    public void testCloseOutbound() throws Exception {
        SSLEngine engine = getEngine();
        assertFalse(engine.isOutboundDone());
        engine.closeOutbound();
        SSLEngineResult result = engine.wrap(ByteBuffer.allocate(0),
                ByteBuffer.allocate(20000));
        assertEquals("Incorrect status", result.getStatus(),
                SSLEngineResult.Status.CLOSED);
        assertEquals("Incorrect status", result.getHandshakeStatus(),
                SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING);
        try {
            // should throw SSLException "engine already closed"
            engine.beginHandshake();
            fail("Expected exception was not thrown.");
        } catch (SSLException e) {
        }
        assertTrue(engine.isOutboundDone());
    }

    /**
     * closeInbound() method testing.
     */
    public void testCloseInbound() throws Exception {
        SSLEngine engine = getEngine();
        assertFalse(engine.isInboundDone());
        engine.closeInbound();
        SSLEngineResult result = engine.wrap(ByteBuffer.allocate(0),
                ByteBuffer.allocate(20000));
        assertEquals("Incorrect status", result.getStatus(),
                SSLEngineResult.Status.CLOSED);
        assertEquals("Incorrect status", result.getHandshakeStatus(),
                SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING);
        try {
            // should throw SSLException "engine already closed"
            engine.beginHandshake();
            fail("Expected exception was not thrown.");
        } catch (SSLException e) {
        }
        assertTrue(engine.isInboundDone());
    }

    /**
     * closeInbound() method testing.
     * Tests error processing in the case of unexpected closeInbound.
     */
    public void testCloseInbound2() throws Exception {
        SSLEngine client = getEngine();
        SSLEngine server = getEngine();
        initEngines(client, server);

        int packetBufferSize =
                client.getSession().getPacketBufferSize();
        int applicationBufferSize =
                server.getSession().getApplicationBufferSize();

        ByteBuffer buffer = ByteBuffer.allocate(packetBufferSize);
        ByteBuffer app_data_buffer = ByteBuffer.allocate(applicationBufferSize);

        client.setUseClientMode(true);
        server.setUseClientMode(false);

        doHandshake(client, server);

        if (doLog) {
            System.out.println("\nError processing test:");
        }
        try {
            // should cause SSLException, prepare fatal alert "internal error",
            // and set HandshakeStatus to NEED_WRAP
            // (to send alert to another side)
            server.closeInbound();
            fail("Expected exception was not thrown.");
        } catch (Exception e) {
            if (doLog) {
                System.out.println("Server threw exception: "
                        + e.getMessage());
            }
            // e.printStackTrace();
            // should do nothing
            server.closeInbound();
            assertEquals("Unexpected status:",
                    SSLEngineResult.HandshakeStatus.NEED_WRAP,
                    server.getHandshakeStatus());

            if (doLog) {
                System.out.println("Wrapping of the alert message");
            }
            SSLEngineResult result = null;
            print(result = server.wrap(ByteBuffer.allocate(0), buffer));
            assertEquals("Unexpected status of operation:",
                    SSLEngineResult.Status.CLOSED,
                    result.getStatus());
            assertEquals("Unexpected status of operation:",
                    SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                    result.getHandshakeStatus());
            assertEquals(
                    "The length of the consumed data differs from expected",
                    0, result.bytesConsumed());
            assertTrue(
                    "The length of the produced data differs from expected",
                    result.bytesProduced() > 0);
            // tune buffer to be read
            buffer.flip();
            try {
                // should rethrow the SSLException "internal error"
                print(client.unwrap(buffer, app_data_buffer));
                fail("Expected exception was not thrown.");
            } catch (Exception ex) {
                if (doLog) {
                    System.out.println("Client rethrew received alert: "
                            + ex.getMessage());
                }
                // NOT_HANDSHAKING..
                assertEquals("Unexpected status of operation:",
                        SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                        client.getHandshakeStatus());
                client.closeOutbound();
                // NEED_WRAP.. should it be so? it contradicts to the TLS spec:
                // "Upon transmission or receipt of an fatal alert message, both
                // parties immediately close the connection. Servers and clients
                // are required to forget any session-identifiers, keys, and
                // secrets associated with a failed connection."
                // So in this case we expect NOT_HANDSHAKING
                assertEquals("Unexpected status of operation:",
                        SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                        client.getHandshakeStatus());
                assertTrue("Outbound should be closed.",
                        client.isOutboundDone());
                assertTrue("Inbound should be closed.",
                        client.isInboundDone());
            }
        }
    }

    /**
     * closeInbound() method testing.
     * Tests error processing
     */
    public void testErrorProcessing() throws Exception {
        SSLEngine client = getEngine();
        SSLEngine server = getEngine();
        initEngines(client, server);

        int packetBufferSize =
                client.getSession().getPacketBufferSize();
        int applicationBufferSize =
                server.getSession().getApplicationBufferSize();

        ByteBuffer buffer = ByteBuffer.allocate(packetBufferSize);
        ByteBuffer app_data_buffer = ByteBuffer.allocate(applicationBufferSize);

        client.setUseClientMode(true);
        server.setUseClientMode(false);

        doHandshake(client, server);

        if (doLog) {
            System.out.println("\nError processing test:");
        }
        try {
            print(server.unwrap(ByteBuffer.allocate(40), app_data_buffer));
            fail("Expected exception was not thrown.");
        } catch (Exception e) {
            if (doLog) {
                System.out.println("\nServer threw exception: "
                        + e.getMessage());
            }
            assertEquals("Unexpected status of operation:",
                    SSLEngineResult.HandshakeStatus.NEED_WRAP,
                    server.getHandshakeStatus());

            SSLEngineResult result = null;
            assertFalse("Outbound should not be closed.",
                    server.isOutboundDone());
            assertTrue("Inbound should be closed.",
                    server.isInboundDone());

            if (doLog) {
                System.out.println(
                        "\nServer tries to unwrap the data after error");
            }
            print(result =
                    server.unwrap(ByteBuffer.allocate(40), app_data_buffer));
            assertEquals("Unexpected status of operation:",
                    SSLEngineResult.Status.CLOSED,
                    result.getStatus());
            assertEquals("Unexpected status of operation:",
                    SSLEngineResult.HandshakeStatus.NEED_WRAP,
                    result.getHandshakeStatus());
            assertEquals(
                    "The length of the consumed data differs from expected",
                    0, result.bytesConsumed());
            assertEquals(
                    "The length of the produced data differs from expected",
                    0, result.bytesProduced());

            if (doLog) {
                System.out.println("\nServer wraps the fatal alert");
            }
            print(result = server.wrap(ByteBuffer.allocate(0), buffer));
            assertEquals("Unexpected status of operation:",
                    SSLEngineResult.Status.CLOSED,
                    result.getStatus());
            assertEquals("Unexpected status of operation:",
                    SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                    result.getHandshakeStatus());
            assertEquals(
                    "The length of the consumed data differs from expected",
                    0, result.bytesConsumed());
            assertTrue(
                    "The length of the produced data differs from expected",
                    result.bytesProduced() > 0);

            assertTrue("Outbound should be closed.",
                    server.isOutboundDone());
            assertTrue("Inbound should be closed.",
                    server.isInboundDone());

            buffer.flip();
            try {
                if (doLog) {
                    System.out.println("\nClient unwraps the fatal alert");
                }
                print(client.unwrap(buffer, app_data_buffer));
                fail("Expected exception was not thrown.");
            } catch (Exception ex) {
                if (doLog) {
                    System.out.println("\nClient rethrew the exception: "
                            + ex.getMessage());
                }
                // NOT_HANDSHAKING..
                assertEquals("Unexpected status of operation:",
                        SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                        client.getHandshakeStatus());
                client.closeOutbound();
                // NEED_WRAP.. should it be so? it contradicts to the TLS spec:
                // "Upon transmission or receipt of an fatal alert message, both
                // parties immediately close the connection. Servers and clients
                // are required to forget any session-identifiers, keys, and
                // secrets associated with a failed connection."
                // So in this case we expect NOT_HANDSHAKING
                assertEquals("Unexpected status of operation:",
                        SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                        client.getHandshakeStatus());
                assertTrue("Outbound should be closed.",
                        client.isOutboundDone());
                assertTrue("Inbound should be closed.",
                        client.isInboundDone());
            }
        }
    }


    // --------------------------------------------------------------------
    // ------------------------ Staff methods -----------------------------
    // --------------------------------------------------------------------

    /*
     * Performs the handshake over the specified engines
     */
    private void doHandshake(SSLEngine client,
            SSLEngine server) throws Exception {
        if (doLog) {
            System.out.println("\n--- doHandshake:");
            System.out.println("Server: " + server.getSession().getClass());
            System.out.println("Client: " + client.getSession().getClass());
        }

        client.beginHandshake();
        server.beginHandshake();

        doHandshakeImpl(client, server);
    }

    /*
     * Performs the handshake over the specified engines.
     * Note that method passes app data between the engines during
     * the handshake process.
     */
    private void doHandshakeImpl(SSLEngine client,
            SSLEngine server) throws Exception {
        if (doLog) {
            System.out.println("\n--- doHandshakeImpl:");
            System.out.println("Client's hsh status: "
                    + client.getHandshakeStatus());
            System.out.println("Client's session: " + client.getSession());
            System.out.println("Server's hsh status: "
                    + server.getHandshakeStatus());
            System.out.println("Server's session: " + server.getSession());
        }

        int packetBufferSize =
                client.getSession().getPacketBufferSize();
        int applicationBufferSize =
                server.getSession().getApplicationBufferSize();

        // buffer will contain handshake messages
        ByteBuffer clients_buffer = ByteBuffer.allocate(packetBufferSize + 1000);
        ByteBuffer servers_buffer = ByteBuffer.allocate(packetBufferSize + 1000);
        // buffers will contain application data messages
        ByteBuffer app_data = ByteBuffer.allocate(packetBufferSize);
        ByteBuffer app_data_plain = ByteBuffer.allocate(applicationBufferSize);

        SSLEngine[] engines = new SSLEngine[] { client, server };
        ByteBuffer[] buffers =
                new ByteBuffer[] { clients_buffer, servers_buffer };

        // choose which peer will start handshake negotiation
        // (initial handshake is initiated by client, but rehandshake
        // can be initiated by any peer)
        int step = (client.getHandshakeStatus()
                != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) ? 0 : 1;

        SSLEngine current_engine = engines[step];
        ByteBuffer buffer;
        SSLEngineResult result = null;
        SSLEngineResult.HandshakeStatus status;

        while ((client.getHandshakeStatus()
                != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING)
                || (server.getHandshakeStatus()
                != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING)) {
            if (doLog) {
                System.out.print("\n"
                        + ((current_engine == client) ? "CLIENT " : "SERVER "));
            }
            status = current_engine.getHandshakeStatus();
            if (status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
                // so another peer produced
                // the handshaking data which has to be unwrapped
                if (doLog) {
                    System.out.print("(NOT_HANDSHAKING) ");
                }
                status = SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
            }
            if (status == SSLEngineResult.HandshakeStatus.NEED_WRAP) {
                if (doLog) {
                    System.out.println("NEED_WRAP");
                }
                // will wrap handshake data into its special buffer
                buffer = buffers[step];
                if (buffer.remaining() == 0) {
                    // handshake data was fully read by another peer,
                    // so we need clear the buffer before reusing it
                    buffer.clear();
                }
                // wrap the next handshake message
                print(result = current_engine.wrap(app_data, buffer));
                // if there are no any messages to send, switch the engine
                if (current_engine.getHandshakeStatus()
                        != SSLEngineResult.HandshakeStatus.NEED_WRAP) {
                    // switch the current engine
                    step ^= 1;
                    current_engine = engines[step];
                    // and prepare the buffer for reading
                    buffer.flip();
                }
            } else if (status == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) {
                if (doLog) {
                    System.out.println("NEED_UNWRAP");
                }

                // If there are no unread handshake messages produced by the
                // current engine, try to wrap the application data and unwrap
                // it by another engine. It will test app data flow during
                // the rehandshake.
                if (!buffers[step].hasRemaining()) {
                    if (doLog) {
                        System.out.println(
                                "\nTry to WRAP the application data");
                    }
                    print(result = current_engine.wrap(
                            ByteBuffer.wrap(new byte[] { 0 }), app_data));
                    // The output in app_data will be produced only if it
                    // is rehandshaking stage
                    // (i.e. initial handshake has been done)
                    if (result.bytesProduced() > 0) {
                        // if the app data message has been produced,
                        // unwrap it by another peer
                        if (doLog) {
                            System.out.print("\n" + ((current_engine != client)
                                    ? "CLIENT " : "SERVER "));
                            System.out.println(
                                    "UNWRAPs app data sent during handshake");
                        }
                        app_data.flip();
                        print(result = engines[(step + 1) % 2].unwrap(
                                app_data, app_data_plain));
                        app_data.clear();
                        app_data_plain.clear();
                    }
                }

                buffer = buffers[step ^ 1];

                // check if there is handshake data to be unwrapped
                if (buffer.remaining() == 0) {
                    if (doLog) {
                        System.out.println(
                                "There is no handshake data to be unwrapped.");
                    }
                    // switch the current engine
                    step ^= 1;
                    current_engine = engines[step];
                    if ((current_engine.getHandshakeStatus()
                            == SSLEngineResult.HandshakeStatus.NEED_UNWRAP)
                            && (buffers[step ^ 1].remaining() == 0)) {
                        System.out.println(
                                "Both engines are in NEED_UNWRAP state");
                        fail("Both engines are in NEED_UNWRAP state");
                    }
                    continue;
                }

                print(result = current_engine.unwrap(buffer, app_data));
                if (current_engine.getHandshakeStatus()
                        == SSLEngineResult.HandshakeStatus.NEED_TASK) {
                    if (doLog) {
                        System.out.println("NEED_TASK");
                    }
                    current_engine.getDelegatedTask().run();
                    if (doLog) {
                        System.out.println("status after the task: "
                                + current_engine.getHandshakeStatus());
                    }
                }
            } else {
                fail("Unexpected HandshakeStatus: " + status);
            }
            assertEquals("Unexpected status of operation:",
                    SSLEngineResult.Status.OK,
                    result.getStatus());
        }
    }

    /*
     * Performs the session renegotiation process when one
     * of the peers is not allowed to create the session.
     */
    private void doNoRenegotiationTest(SSLEngine allowed,
            SSLEngine not_allowed, boolean is_initial) throws Exception {
        if (doLog) {
            System.out.println(
                    "\n--- doNoRenegotiationTest: is_initial: " + is_initial);
        }

        not_allowed.setEnableSessionCreation(false);
        not_allowed.getSession().invalidate();

        int packetBufferSize =
                allowed.getSession().getPacketBufferSize();
        int applicationBufferSize =
                not_allowed.getSession().getApplicationBufferSize();

        // buffer will contain handshake messages
        ByteBuffer buffer = ByteBuffer.allocate(packetBufferSize + 1000);
        // buffers will contain application data messages
        ByteBuffer app_data = ByteBuffer.allocate(packetBufferSize);
        ByteBuffer app_data_plain = ByteBuffer.allocate(applicationBufferSize);

        SSLEngineResult result = null;

        allowed.beginHandshake();
        //not_allowed.beginHandshake();

        if (doLog) {
            System.out.println(
                    "\nAllowed peer wraps the initial session negotiation message");
        }
        // wrap the initial session negotiation message
        while (allowed.getHandshakeStatus().equals(
                SSLEngineResult.HandshakeStatus.NEED_WRAP)) {
            print(result = allowed.wrap(app_data_plain, buffer));
            assertTrue("Engine did not produce any data",
                    result.bytesProduced() > 0);
        }
        // prepare the buffer for reading
        buffer.flip();
        if (doLog) {
            System.out.println("\nNot allowed unwraps the message");
        }
        try {
            // unwrap the message. expecting whether SSLException or NEED_WRAP
            print(result = not_allowed.unwrap(buffer, app_data_plain));
        } catch (SSLException e) {
            if (is_initial) {
                return; // ok, exception was thrown
            } else {
                fail("Unexpected SSLException was thrown " + e);
            }
        }
        // if it is not an initial handshake phase it is posible
        // SSLException to be thrown.
        try {
            while (!not_allowed.getHandshakeStatus().equals(
                    SSLEngineResult.HandshakeStatus.NEED_WRAP)) {
                assertTrue("Engine did not consume any data",
                        result.bytesConsumed() > 0);
                if (not_allowed.getHandshakeStatus().equals(
                        SSLEngineResult.HandshakeStatus.NEED_TASK)) {
                    not_allowed.getDelegatedTask().run();
                    if (doLog) {
                        System.out.println("Status after the task: "
                                + not_allowed.getHandshakeStatus());
                    }
                    continue;
                } else if (not_allowed.getHandshakeStatus().equals(
                        SSLEngineResult.HandshakeStatus.NEED_UNWRAP)) {
                    print(result = not_allowed.unwrap(buffer, app_data_plain));
                } else {
                    fail("Unexpected status of operation: "
                            + not_allowed.getHandshakeStatus());
                }
            }
            // prepare for writting
            buffer.clear();
            if (doLog) {
                System.out.println(
                        "\nWrapping the message. Expecting no_renegotiation alert");
            }
            // wrapping the message. expecting no_renegotiation alert
            print(result = not_allowed.wrap(app_data_plain, buffer));
        } catch (SSLException e) {
            if (!is_initial) {
                fail("Unexpected SSLException was thrown." + e.getMessage());
            }
            if (doLog) {
                System.out.println("Throwed exception during the unwrapping "
                        + "of handshake initiation message:");
                e.printStackTrace();
                System.out.println("Handshake Status: "
                        + not_allowed.getHandshakeStatus());
            }
            if (not_allowed.getHandshakeStatus().equals(
                    SSLEngineResult.HandshakeStatus.NEED_WRAP)) {
                // needs to wrap fatal alert message
                if (doLog) {
                    System.out.println(
                            "\nnot_allowed wraps fatal alert message");
                }
                // prepare for writting
                buffer.clear();
                print(result = not_allowed.wrap(app_data_plain, buffer));
            }
        }
        // check whether alert message has been sent
        assertTrue("Engine did not produce any data",
                result.bytesProduced() > 0);
        // check whether not_allowed engine stoped handshake operation
        assertEquals("Unexpected status of operation: not_allowed "
                + "to session creation peer did not stop its handshake process",
                SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                not_allowed.getHandshakeStatus());
        // prepare for reading
        buffer.flip();
        try {
            print(result = allowed.unwrap(buffer, app_data_plain));
            assertTrue("Engine did not consume any data",
                    result.bytesConsumed() > 0);
            assertEquals("Responce from the peer not allowed to create "
                    + "the session did not cause the stopping of "
                    + "the session negotiation process",
                    SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                    result.getHandshakeStatus());
        } catch (SSLException e) {
            if (!is_initial) {
                fail("Unexpected SSLException was thrown." + e.getMessage());
            }
            if (doLog) {
                System.out.println("Throwed exception during the unwrapping "
                        + "of responce from allowed peer:");
                e.printStackTrace();
                System.out.println("Handshake Status: "
                        + not_allowed.getHandshakeStatus());
            }
        }
    }

    /*
     * Tests the data exchange process between two engines
     */
    private void doDataExchange(SSLEngine client,
            SSLEngine server) throws Exception {
        if (doLog) {
            System.out.println("\n--- doDataExchange:");
        }
        ByteBuffer co = ByteBuffer.allocate(
                client.getSession().getPacketBufferSize());
        ByteBuffer si = ByteBuffer.allocate(
                server.getSession().getPacketBufferSize());
        SSLEngineResult result;

        String data_2b_sent = "data to be sent";
        ByteBuffer data = ByteBuffer.wrap(data_2b_sent.getBytes());

        if (doLog) {
            System.out.println("\nTry to wrap the data into small buffer");
        }
        print(result = client.wrap(data, ByteBuffer.allocate(35)));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.BUFFER_OVERFLOW,
                result.getStatus());

        if (doLog) {
            System.out.println("\nWrapping the data of length "
                    + data.remaining());
        }
        print(result = client.wrap(data, co));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.OK,
                result.getStatus());

        // tune the buffer to read from it
        co.limit(co.position());
        co.rewind();

        if (doLog) {
            System.out.println("\nTry to unwrap the data into small buffer");
        }
        print(result = server.unwrap(co, ByteBuffer.allocate(0)));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.BUFFER_OVERFLOW,
                result.getStatus());
        if (doLog) {
            System.out.println("\nUnwrapping the data into buffer");
        }
        print(result = server.unwrap(co, si));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.OK,
                result.getStatus());
        assertEquals(
                "The length of the received data differs from expected",
                "data to be sent".length(), result.bytesProduced());

        // take the data from the buffer
        byte[] resulting_data = new byte[result.bytesProduced()];
        si.rewind();
        si.get(resulting_data);
        si.clear();
        assertTrue(Arrays.equals(data_2b_sent.getBytes(), resulting_data));

        co.clear();
        for (int i = 1; i < 10; i++) {
            byte[] buff = new byte[i];
            data = ByteBuffer.wrap(buff);
            if (doLog) {
                System.out.println("\nWrap the data");
            }
            print(result = client.wrap(data, co));
            assertEquals("Unexpected status of operation:",
                    SSLEngineResult.Status.OK,
                    result.getStatus());
            if (doLog) {
                System.out.println("\nUnwrap the data");
            }
            co.rewind();
            print(result = server.unwrap(co, si));
            assertEquals("Unexpected status of operation:",
                    SSLEngineResult.Status.OK,
                    result.getStatus());
            assertEquals(
                    "The length of the received data differs from expected",
                    i, result.bytesProduced());
            resulting_data = new byte[i];
            si.rewind();
            si.get(resulting_data);
            si.clear();
            assertTrue(Arrays.equals(buff, resulting_data));
            co.clear();
            si.clear();
        }
    }

    /*
     * Performs the closure process over the two communicationg engines.
     * The handshake process should be performed before the call of this
     * method.
     */
    private void doClose(SSLEngine client, SSLEngine server) throws Exception {
        if (doLog) {
            System.out.println("\n--- doClose: ");
        }
        ByteBuffer buffer = ByteBuffer.allocate(
                // +100 because we put the data into the buffer multiple times
                server.getSession().getPacketBufferSize() + 100);
        ByteBuffer app_data_buffer = ByteBuffer.allocate(
                client.getSession().getApplicationBufferSize());
        SSLEngineResult result;
        // first: send 0 just for fun
        if (doLog) {
            System.out.println("\nServer sends pending outboud data:");
        }
        print(result = server.wrap(ByteBuffer.wrap(new byte[] { 0 }), buffer));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.OK,
                result.getStatus());
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                result.getHandshakeStatus());
        // second: initiate a close
        if (doLog) {
            System.out.println("\nServer initiates a closure:");
        }
        server.closeOutbound();
        // should do nothing:
        server.closeOutbound();

        assertEquals("Unexpected status of operation:",
                SSLEngineResult.HandshakeStatus.NEED_WRAP,
                server.getHandshakeStatus());

        // will cause SSLException because closure alert was not received yet:
        // server.closeInbound();

        // wrap closure alert (previosly sent 0 should not be lost)
        print(result = server.wrap(ByteBuffer.allocate(0), buffer));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.CLOSED,
                result.getStatus());
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.HandshakeStatus.NEED_UNWRAP,
                result.getHandshakeStatus());

        if (doLog) {
            System.out.println("\nServer sends pending outboud data again:");
        }
        // will do nothing because closure alert has been sent
        // and outbound has been closed
        print(result = server.wrap(ByteBuffer.wrap(new byte[] { 0 }), buffer));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.CLOSED,
                result.getStatus());
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.HandshakeStatus.NEED_UNWRAP,
                result.getHandshakeStatus());
        assertEquals(
                "The length of the consumed data differs from expected",
                0, result.bytesConsumed());
        assertEquals(
                "The length of the produced data differs from expected",
                0, result.bytesProduced());

        // prepare the buffer for reading
        buffer.flip();

        if (doLog) {
            System.out.println(
                    "\nClient receives pending servers' outbound data");
        }
        print(result = client.unwrap(buffer, app_data_buffer));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.OK,
                result.getStatus());
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                result.getHandshakeStatus());
        assertEquals(
                "The length of the produced data differs from expected",
                1, result.bytesProduced());

        app_data_buffer.clear();

        if (doLog) {
            System.out.println("\nClient receives close notify");
        }
        print(result = client.unwrap(buffer, app_data_buffer));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.CLOSED,
                result.getStatus());
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.HandshakeStatus.NEED_WRAP,
                result.getHandshakeStatus());
        assertTrue(
                "The length of the consumed data differs from expected",
                result.bytesConsumed() > 0);
        assertEquals(
                "The length of the received data differs from expected",
                0, result.bytesProduced());

        // prepare the buffer for writing
        app_data_buffer.clear();

        // it's needless, but should work (don't cause exceptions):
        client.closeInbound();
        client.closeOutbound();

        if (doLog) {
            System.out.println("\nClient tries to read data again");
        }
        // CLOSED, 0 consumed, 0 produced
        print(result = client.unwrap(buffer, app_data_buffer));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.CLOSED,
                result.getStatus());
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.HandshakeStatus.NEED_WRAP,
                result.getHandshakeStatus());
        assertEquals(
                "The length of the consumed data differs from expected",
                0, result.bytesConsumed());
        assertEquals(
                "The length of the received data differs from expected",
                0, result.bytesProduced());

        // prepare the buffer for writing
        buffer.clear();

        if (doLog) {
            System.out.println("\nClient sends responding close notify");
        }
        print(result = client.wrap(ByteBuffer.wrap(new byte[] { 0 }), buffer));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.CLOSED,
                result.getStatus());
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                result.getHandshakeStatus());
        assertEquals(
                "The length of the consumed data differs from expected",
                0, result.bytesConsumed());
        assertTrue(
                "The length of the produced data differs from expected",
                result.bytesProduced() > 0);
        if (doLog) {
            System.out.println(
                    "\nClient tries to send data after closure alert");
        }
        // this data will not be sent (should do nothing - 0 cons, 0 prod)
        print(result = client.wrap(ByteBuffer.wrap(new byte[] { 0 }), buffer));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.CLOSED,
                result.getStatus());
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                result.getHandshakeStatus());
        assertEquals(
                "The length of the consumed data differs from expected",
                0, result.bytesConsumed());
        assertEquals(
                "The length of the produced data differs from expected",
                0, result.bytesProduced());

        // prepare the buffers for reading
        app_data_buffer.clear();
        buffer.flip();

        if (doLog) {
            System.out.println("\nServer receives close notify");
        }
        print(result = server.unwrap(buffer, app_data_buffer));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.CLOSED,
                result.getStatus());
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                result.getHandshakeStatus());
        assertTrue(
                "The length of the consumed data differs from expected",
                result.bytesConsumed() > 0);
        assertEquals(
                "The length of the produced data differs from expected",
                0, result.bytesProduced());

        if (doLog) {
            System.out.println("\nServer tries to read after closure");
        }
        // will be ignored
        print(result = server.unwrap(buffer, app_data_buffer));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.CLOSED,
                result.getStatus());
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                result.getHandshakeStatus());
        assertEquals(
                "The length of the consumed data differs from expected",
                0, result.bytesConsumed());
        assertEquals(
                "The length of the produced data differs from expected",
                0, result.bytesProduced());

        // it's needless, but should work:
        client.closeInbound();
        // will be ignored

        if (doLog) {
            System.out.println("\nServer tries to write after closure");
        }
        buffer.clear();
        print(result = server.wrap(ByteBuffer.allocate(0), buffer));
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.Status.CLOSED,
                result.getStatus());
        assertEquals("Unexpected status of operation:",
                SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                result.getHandshakeStatus());
        assertEquals(
                "The length of the consumed data differs from expected",
                0, result.bytesConsumed());
        assertEquals(
                "The length of the produced data differs from expected",
                0, result.bytesProduced());
    }

    private static void print(SSLEngineResult result) {
        if (doLog) {
            System.out.println("result:\n" + result);
        }
    }

    /**
     * Returns the engine to be tested.
     */
    private SSLEngine getEngine() throws Exception {
        return JSSETestData.getContext().createSSLEngine("localhost", 2345);
    }

    /**
     * Initializes the engines.
     */
    private void initEngines(SSLEngine client, SSLEngine server) {
        String prefix = "TLS_";

        client.setEnabledProtocols(new String[] { "TLSv1" });
        server.setEnabledProtocols(new String[] { "TLSv1" });
        client.setEnabledCipherSuites(
                new String[] { prefix + cipher_suites[0] });
        server.setEnabledCipherSuites(
                new String[] { prefix + cipher_suites[0] });

        client.setUseClientMode(true);
        server.setUseClientMode(false);
    }

    public static Test suite() {
        return new TestSuite(SSLEngineImplTest.class);
    }

}