aboutsummaryrefslogtreecommitdiff
path: root/src/java/com/android/internal/net/ipsec/ike/message/IkeSaPayload.java
blob: 40eecf02df5ff30ccbde5e31eaf04d42fd3064cc (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
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.internal.net.ipsec.ike.message;

import static android.net.ipsec.ike.IkeManager.getIkeLog;
import static android.net.ipsec.ike.SaProposal.DhGroup;
import static android.net.ipsec.ike.SaProposal.EncryptionAlgorithm;
import static android.net.ipsec.ike.SaProposal.IntegrityAlgorithm;
import static android.net.ipsec.ike.SaProposal.PseudorandomFunction;

import android.annotation.IntDef;
import android.annotation.NonNull;
import android.net.IpSecManager.ResourceUnavailableException;
import android.net.IpSecManager.SecurityParameterIndex;
import android.net.IpSecManager.SpiUnavailableException;
import android.net.ipsec.ike.ChildSaProposal;
import android.net.ipsec.ike.IkeSaProposal;
import android.net.ipsec.ike.SaProposal;
import android.net.ipsec.ike.exceptions.IkeProtocolException;
import android.util.ArraySet;
import android.util.Pair;

import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.net.ipsec.ike.exceptions.InvalidSyntaxException;
import com.android.internal.net.ipsec.ike.exceptions.NoValidProposalChosenException;
import com.android.internal.net.ipsec.ike.utils.IkeSecurityParameterIndex;
import com.android.internal.net.ipsec.ike.utils.IkeSpiGenerator;
import com.android.internal.net.ipsec.ike.utils.IpSecSpiGenerator;

import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * IkeSaPayload represents a Security Association payload. It contains one or more {@link Proposal}.
 *
 * @see <a href="https://tools.ietf.org/html/rfc7296#section-3.3">RFC 7296, Internet Key Exchange
 *     Protocol Version 2 (IKEv2)</a>
 */
public final class IkeSaPayload extends IkePayload {
    private static final String TAG = "IkeSaPayload";

    public final boolean isSaResponse;
    public final List<Proposal> proposalList;
    /**
     * Construct an instance of IkeSaPayload for decoding an inbound packet.
     *
     * @param critical indicates if this payload is critical. Ignored in supported payload as
     *     instructed by the RFC 7296.
     * @param isResp indicates if this payload is in a response message.
     * @param payloadBody the encoded payload body in byte array.
     */
    IkeSaPayload(boolean critical, boolean isResp, byte[] payloadBody) throws IkeProtocolException {
        super(IkePayload.PAYLOAD_TYPE_SA, critical);

        ByteBuffer inputBuffer = ByteBuffer.wrap(payloadBody);
        proposalList = new LinkedList<>();
        while (inputBuffer.hasRemaining()) {
            Proposal proposal = Proposal.readFrom(inputBuffer);
            proposalList.add(proposal);
        }

        if (proposalList.isEmpty()) {
            throw new InvalidSyntaxException("Found no SA Proposal in this SA Payload.");
        }

        // An SA response must have exactly one SA proposal.
        if (isResp && proposalList.size() != 1) {
            throw new InvalidSyntaxException(
                    "Expected only one negotiated proposal from SA response: "
                            + "Multiple negotiated proposals found.");
        }
        isSaResponse = isResp;

        boolean firstIsIkeProposal = (proposalList.get(0).protocolId == PROTOCOL_ID_IKE);
        for (int i = 1; i < proposalList.size(); i++) {
            boolean isIkeProposal = (proposalList.get(i).protocolId == PROTOCOL_ID_IKE);
            if (firstIsIkeProposal != isIkeProposal) {
                getIkeLog()
                        .w(TAG, "Found both IKE proposals and Child proposals in this SA Payload.");
                break;
            }
        }

        getIkeLog().d(TAG, "Receive " + toString());
    }

    /** Package private constructor for building a request for IKE SA initial creation or rekey */
    @VisibleForTesting
    IkeSaPayload(
            boolean isResp,
            byte spiSize,
            IkeSaProposal[] saProposals,
            IkeSpiGenerator ikeSpiGenerator,
            InetAddress localAddress)
            throws IOException {
        this(isResp, spiSize, localAddress);

        if (saProposals.length < 1 || isResp && (saProposals.length > 1)) {
            throw new IllegalArgumentException("Invalid SA payload.");
        }

        for (int i = 0; i < saProposals.length; i++) {
            // Proposal number must start from 1.
            proposalList.add(
                    IkeProposal.createIkeProposal(
                            (byte) (i + 1) /* number */,
                            spiSize,
                            saProposals[i],
                            ikeSpiGenerator,
                            localAddress));
        }

        getIkeLog().d(TAG, "Generate " + toString());
    }

    /** Package private constructor for building an response SA Payload for IKE SA rekeys. */
    @VisibleForTesting
    IkeSaPayload(
            boolean isResp,
            byte spiSize,
            byte proposalNumber,
            IkeSaProposal saProposal,
            IkeSpiGenerator ikeSpiGenerator,
            InetAddress localAddress)
            throws IOException {
        this(isResp, spiSize, localAddress);

        proposalList.add(
                IkeProposal.createIkeProposal(
                        proposalNumber /* number */,
                        spiSize,
                        saProposal,
                        ikeSpiGenerator,
                        localAddress));

        getIkeLog().d(TAG, "Generate " + toString());
    }

    private IkeSaPayload(boolean isResp, byte spiSize, InetAddress localAddress)
            throws IOException {
        super(IkePayload.PAYLOAD_TYPE_SA, false);

        // TODO: Check that proposals.length <= 255 in IkeSessionParams and ChildSessionParams
        isSaResponse = isResp;

        // TODO: Allocate IKE SPI and pass to IkeProposal.createIkeProposal()

        // ProposalList populated in other constructors
        proposalList = new ArrayList<Proposal>();
    }

    /**
     * Package private constructor for building an outbound request SA Payload for Child SA
     * negotiation.
     */
    @VisibleForTesting
    IkeSaPayload(
            ChildSaProposal[] saProposals,
            IpSecSpiGenerator ipSecSpiGenerator,
            InetAddress localAddress)
            throws SpiUnavailableException, ResourceUnavailableException {
        this(false /* isResp */, ipSecSpiGenerator, localAddress);

        if (saProposals.length < 1) {
            throw new IllegalArgumentException("Invalid SA payload.");
        }

        // TODO: Check that saProposals.length <= 255 in IkeSessionParams and ChildSessionParams

        for (int i = 0; i < saProposals.length; i++) {
            // Proposal number must start from 1.
            proposalList.add(
                    ChildProposal.createChildProposal(
                            (byte) (i + 1) /* number */,
                            saProposals[i],
                            ipSecSpiGenerator,
                            localAddress));
        }

        getIkeLog().d(TAG, "Generate " + toString());
    }

    /**
     * Package private constructor for building an outbound response SA Payload for Child SA
     * negotiation.
     */
    @VisibleForTesting
    IkeSaPayload(
            byte proposalNumber,
            ChildSaProposal saProposal,
            IpSecSpiGenerator ipSecSpiGenerator,
            InetAddress localAddress)
            throws SpiUnavailableException, ResourceUnavailableException {
        this(true /* isResp */, ipSecSpiGenerator, localAddress);

        proposalList.add(
                ChildProposal.createChildProposal(
                        proposalNumber /* number */, saProposal, ipSecSpiGenerator, localAddress));

        getIkeLog().d(TAG, "Generate " + toString());
    }

    /** Constructor for building an outbound SA Payload for Child SA negotiation. */
    private IkeSaPayload(
            boolean isResp, IpSecSpiGenerator ipSecSpiGenerator, InetAddress localAddress) {
        super(IkePayload.PAYLOAD_TYPE_SA, false);

        isSaResponse = isResp;

        // TODO: Allocate Child SPI and pass to ChildProposal.createChildProposal()

        // ProposalList populated in other constructors
        proposalList = new ArrayList<Proposal>();
    }

    /**
     * Construct an instance of IkeSaPayload for building an outbound IKE initial setup request.
     *
     * <p>According to RFC 7296, for an initial IKE SA negotiation, no SPI is included in SA
     * Proposal. IKE library, as a client, only supports requesting this initial negotiation.
     *
     * @param saProposals the array of all SA Proposals.
     */
    public static IkeSaPayload createInitialIkeSaPayload(IkeSaProposal[] saProposals)
            throws IOException {
        return new IkeSaPayload(
                false /* isResp */,
                SPI_LEN_NOT_INCLUDED,
                saProposals,
                null /* ikeSpiGenerator unused */,
                null /* localAddress unused */);
    }

    /**
     * Construct an instance of IkeSaPayload for building an outbound request for Rekey IKE.
     *
     * @param saProposals the array of all IKE SA Proposals.
     * @param ikeSpiGenerator the IKE SPI generator.
     * @param localAddress the local address assigned on-device.
     */
    public static IkeSaPayload createRekeyIkeSaRequestPayload(
            IkeSaProposal[] saProposals, IkeSpiGenerator ikeSpiGenerator, InetAddress localAddress)
            throws IOException {
        return new IkeSaPayload(
                false /* isResp */, SPI_LEN_IKE, saProposals, ikeSpiGenerator, localAddress);
    }

    /**
     * Construct an instance of IkeSaPayload for building an outbound response for Rekey IKE.
     *
     * @param respProposalNumber the selected proposal's number.
     * @param saProposal the expected selected IKE SA Proposal.
     * @param ikeSpiGenerator the IKE SPI generator.
     * @param localAddress the local address assigned on-device.
     */
    public static IkeSaPayload createRekeyIkeSaResponsePayload(
            byte respProposalNumber,
            IkeSaProposal saProposal,
            IkeSpiGenerator ikeSpiGenerator,
            InetAddress localAddress)
            throws IOException {
        return new IkeSaPayload(
                true /* isResp */,
                SPI_LEN_IKE,
                respProposalNumber,
                saProposal,
                ikeSpiGenerator,
                localAddress);
    }

    /**
     * Construct an instance of IkeSaPayload for building an outbound request for Child SA
     * negotiation.
     *
     * @param saProposals the array of all Child SA Proposals.
     * @param ipSecSpiGenerator the IPsec SPI generator.
     * @param localAddress the local address assigned on-device.
     * @throws ResourceUnavailableException if too many SPIs are currently allocated for this user.
     */
    public static IkeSaPayload createChildSaRequestPayload(
            ChildSaProposal[] saProposals,
            IpSecSpiGenerator ipSecSpiGenerator,
            InetAddress localAddress)
            throws SpiUnavailableException, ResourceUnavailableException {

        return new IkeSaPayload(saProposals, ipSecSpiGenerator, localAddress);
    }

    /**
     * Construct an instance of IkeSaPayload for building an outbound response for Child SA
     * negotiation.
     *
     * @param respProposalNumber the selected proposal's number.
     * @param saProposal the expected selected Child SA Proposal.
     * @param ipSecSpiGenerator the IPsec SPI generator.
     * @param localAddress the local address assigned on-device.
     */
    public static IkeSaPayload createChildSaResponsePayload(
            byte respProposalNumber,
            ChildSaProposal saProposal,
            IpSecSpiGenerator ipSecSpiGenerator,
            InetAddress localAddress)
            throws SpiUnavailableException, ResourceUnavailableException {
        return new IkeSaPayload(respProposalNumber, saProposal, ipSecSpiGenerator, localAddress);
    }

    /**
     * Finds the proposal in this (request) payload that matches the response proposal.
     *
     * @param respProposal the Proposal to match against.
     * @return the byte-value proposal number of the selected proposal
     * @throws NoValidProposalChosenException if no matching proposal was found.
     */
    public byte getNegotiatedProposalNumber(SaProposal respProposal)
            throws NoValidProposalChosenException {
        for (int i = 0; i < proposalList.size(); i++) {
            Proposal reqProposal = proposalList.get(i);
            if (respProposal.isNegotiatedFrom(reqProposal.getSaProposal())
                    && reqProposal.getSaProposal().getProtocolId()
                            == respProposal.getProtocolId()) {
                return reqProposal.number;
            }
        }
        throw new NoValidProposalChosenException("No remotely proposed protocol acceptable");
    }

    /**
     * Validate the IKE SA Payload pair (request/response) and return the IKE SA negotiation result.
     *
     * <p>Caller is able to extract the negotiated IKE SA Proposal from the response Proposal and
     * the IKE SPI pair generated by both sides.
     *
     * <p>In a locally-initiated case all IKE SA proposals (from users in initial creation or from
     * previously negotiated proposal in rekey creation) in the locally generated reqSaPayload have
     * been validated during building and are unmodified. All Transform combinations in these SA
     * proposals are valid for IKE SA negotiation. It means each IKE SA request proposal MUST have
     * Encryption algorithms, DH group configurations and PRFs. Integrity algorithms can only be
     * omitted when AEAD is used.
     *
     * <p>In a remotely-initiated case the locally generated respSaPayload has exactly one SA
     * proposal. It is validated during building and are unmodified. This proposal has a valid
     * Transform combination for an IKE SA and has at most one value for each Transform type.
     *
     * <p>The response IKE SA proposal is validated against one of the request IKE SA proposals. It
     * is guaranteed that for each Transform type that the request proposal has provided options,
     * the response proposal has exact one Transform value.
     *
     * @param reqSaPayload the request payload.
     * @param respSaPayload the response payload.
     * @param remoteAddress the address of the remote IKE peer.
     * @return the Pair of selected IkeProposal in request and the IkeProposal in response.
     * @throws NoValidProposalChosenException if the response SA Payload cannot be negotiated from
     *     the request SA Payload.
     */
    public static Pair<IkeProposal, IkeProposal> getVerifiedNegotiatedIkeProposalPair(
            IkeSaPayload reqSaPayload,
            IkeSaPayload respSaPayload,
            IkeSpiGenerator ikeSpiGenerator,
            InetAddress remoteAddress)
            throws NoValidProposalChosenException, IOException {
        Pair<Proposal, Proposal> proposalPair =
                getVerifiedNegotiatedProposalPair(reqSaPayload, respSaPayload);
        IkeProposal reqProposal = (IkeProposal) proposalPair.first;
        IkeProposal respProposal = (IkeProposal) proposalPair.second;

        try {
            // Allocate initiator's inbound SPI as needed for remotely initiated IKE SA creation
            if (reqProposal.spiSize != SPI_NOT_INCLUDED
                    && reqProposal.getIkeSpiResource() == null) {
                reqProposal.allocateResourceForRemoteIkeSpi(ikeSpiGenerator, remoteAddress);
            }
            // Allocate responder's inbound SPI as needed for locally initiated IKE SA creation
            if (respProposal.spiSize != SPI_NOT_INCLUDED
                    && respProposal.getIkeSpiResource() == null) {
                respProposal.allocateResourceForRemoteIkeSpi(ikeSpiGenerator, remoteAddress);
            }

            return new Pair(reqProposal, respProposal);
        } catch (Exception e) {
            reqProposal.releaseSpiResourceIfExists();
            respProposal.releaseSpiResourceIfExists();
            throw e;
        }
    }

    /**
     * Validate the SA Payload pair (request/response) and return the Child SA negotiation result.
     *
     * <p>Caller is able to extract the negotiated SA Proposal from the response Proposal and the
     * IPsec SPI pair generated by both sides.
     *
     * <p>In a locally-initiated case all Child SA proposals (from users in initial creation or from
     * previously negotiated proposal in rekey creation) in the locally generated reqSaPayload have
     * been validated during building and are unmodified. All Transform combinations in these SA
     * proposals are valid for Child SA negotiation. It means each request SA proposal MUST have
     * Encryption algorithms and ESN configurations.
     *
     * <p>In a remotely-initiated case the locally generated respSapayload has exactly one SA
     * proposal. It is validated during building and are unmodified. This proposal has a valid
     * Transform combination for an Child SA and has at most one value for each Transform type.
     *
     * <p>The response Child SA proposal is validated against one of the request SA proposals. It is
     * guaranteed that for each Transform type that the request proposal has provided options, the
     * response proposal has exact one Transform value.
     *
     * @param reqSaPayload the request payload.
     * @param respSaPayload the response payload.
     * @param ipSecSpiGenerator the SPI generator to allocate SPI resource for the Proposal in this
     *     inbound SA Payload.
     * @param remoteAddress the address of the remote IKE peer.
     * @return the Pair of selected ChildProposal in the locally generated request and the
     *     ChildProposal in this response.
     * @throws NoValidProposalChosenException if the response SA Payload cannot be negotiated from
     *     the request SA Payload.
     * @throws ResourceUnavailableException if too many SPIs are currently allocated for this user.
     * @throws SpiUnavailableException if the remotely generated SPI is in use.
     */
    public static Pair<ChildProposal, ChildProposal> getVerifiedNegotiatedChildProposalPair(
            IkeSaPayload reqSaPayload,
            IkeSaPayload respSaPayload,
            IpSecSpiGenerator ipSecSpiGenerator,
            InetAddress remoteAddress)
            throws NoValidProposalChosenException, ResourceUnavailableException,
                    SpiUnavailableException {
        Pair<Proposal, Proposal> proposalPair =
                getVerifiedNegotiatedProposalPair(reqSaPayload, respSaPayload);
        ChildProposal reqProposal = (ChildProposal) proposalPair.first;
        ChildProposal respProposal = (ChildProposal) proposalPair.second;

        try {
            // Allocate initiator's inbound SPI as needed for remotely initiated Child SA creation
            if (reqProposal.getChildSpiResource() == null) {
                reqProposal.allocateResourceForRemoteChildSpi(ipSecSpiGenerator, remoteAddress);
            }
            // Allocate responder's inbound SPI as needed for locally initiated Child SA creation
            if (respProposal.getChildSpiResource() == null) {
                respProposal.allocateResourceForRemoteChildSpi(ipSecSpiGenerator, remoteAddress);
            }

            return new Pair(reqProposal, respProposal);
        } catch (Exception e) {
            reqProposal.releaseSpiResourceIfExists();
            respProposal.releaseSpiResourceIfExists();
            throw e;
        }
    }

    private static Pair<Proposal, Proposal> getVerifiedNegotiatedProposalPair(
            IkeSaPayload reqSaPayload, IkeSaPayload respSaPayload)
            throws NoValidProposalChosenException {
        try {
            // If negotiated proposal has an unrecognized Transform, throw an exception.
            Proposal respProposal = respSaPayload.proposalList.get(0);
            if (respProposal.hasUnrecognizedTransform) {
                throw new NoValidProposalChosenException(
                        "Negotiated proposal has unrecognized Transform.");
            }

            // In SA request payload, the first proposal MUST be 1, and subsequent proposals MUST be
            // one more than the previous proposal. In SA response payload, the negotiated proposal
            // number MUST match the selected proposal number in SA request Payload.
            int negotiatedProposalNum = respProposal.number;
            List<Proposal> reqProposalList = reqSaPayload.proposalList;
            if (negotiatedProposalNum < 1 || negotiatedProposalNum > reqProposalList.size()) {
                throw new NoValidProposalChosenException(
                        "Negotiated proposal has invalid proposal number.");
            }

            Proposal reqProposal = reqProposalList.get(negotiatedProposalNum - 1);
            if (!respProposal.isNegotiatedFrom(reqProposal)) {
                throw new NoValidProposalChosenException("Invalid negotiated proposal.");
            }

            // In a locally-initiated creation, release locally generated SPIs in unselected request
            // Proposals. In remotely-initiated SA creation, unused proposals do not have SPIs, and
            // will silently succeed.
            for (Proposal p : reqProposalList) {
                if (reqProposal != p) p.releaseSpiResourceIfExists();
            }

            return new Pair<Proposal, Proposal>(reqProposal, respProposal);
        } catch (Exception e) {
            // In a locally-initiated case, release all locally generated SPIs in the SA request
            // payload.
            for (Proposal p : reqSaPayload.proposalList) p.releaseSpiResourceIfExists();
            throw e;
        }
    }

    @VisibleForTesting
    interface TransformDecoder {
        Transform[] decodeTransforms(int count, ByteBuffer inputBuffer) throws IkeProtocolException;
    }

    /**
     * Release IPsec SPI resources in the outbound Create Child request
     *
     * <p>This method is usually called when an IKE library fails to receive a Create Child response
     * before it is terminated. It is also safe to call after the Create Child exchange has
     * succeeded because the newly created IpSecTransform pair will hold the IPsec SPI resource.
     */
    public void releaseChildSpiResourcesIfExists() {
        for (Proposal proposal : proposalList) {
            if (proposal instanceof ChildProposal) {
                proposal.releaseSpiResourceIfExists();
            }
        }
    }

    /**
     * This class represents the common information of an IKE Proposal and a Child Proposal.
     *
     * <p>Proposal represents a set contains cryptographic algorithms and key generating materials.
     * It contains multiple {@link Transform}.
     *
     * @see <a href="https://tools.ietf.org/html/rfc7296#section-3.3.1">RFC 7296, Internet Key
     *     Exchange Protocol Version 2 (IKEv2)</a>
     *     <p>Proposals with an unrecognized Protocol ID, containing an unrecognized Transform Type
     *     or lacking a necessary Transform Type shall be ignored when processing a received SA
     *     Payload.
     */
    public abstract static class Proposal {
        private static final byte LAST_PROPOSAL = 0;
        private static final byte NOT_LAST_PROPOSAL = 2;

        private static final int PROPOSAL_RESERVED_FIELD_LEN = 1;
        private static final int PROPOSAL_HEADER_LEN = 8;

        @VisibleForTesting
        static TransformDecoder sTransformDecoder =
                new TransformDecoder() {
                    @Override
                    public Transform[] decodeTransforms(int count, ByteBuffer inputBuffer)
                            throws IkeProtocolException {
                        Transform[] transformArray = new Transform[count];
                        for (int i = 0; i < count; i++) {
                            Transform transform = Transform.readFrom(inputBuffer);
                            if (transform.isSupported) {
                                transformArray[i] = transform;
                            }
                        }
                        return transformArray;
                    }
                };

        public final byte number;
        /** All supported protocol will fall into {@link ProtocolId} */
        public final int protocolId;

        public final byte spiSize;
        public final long spi;

        public final boolean hasUnrecognizedTransform;

        @VisibleForTesting
        Proposal(
                byte number,
                int protocolId,
                byte spiSize,
                long spi,
                boolean hasUnrecognizedTransform) {
            this.number = number;
            this.protocolId = protocolId;
            this.spiSize = spiSize;
            this.spi = spi;
            this.hasUnrecognizedTransform = hasUnrecognizedTransform;
        }

        @VisibleForTesting
        static Proposal readFrom(ByteBuffer inputBuffer) throws IkeProtocolException {
            byte isLast = inputBuffer.get();
            if (isLast != LAST_PROPOSAL && isLast != NOT_LAST_PROPOSAL) {
                throw new InvalidSyntaxException(
                        "Invalid value of Last Proposal Substructure: " + isLast);
            }
            // Skip RESERVED byte
            inputBuffer.get(new byte[PROPOSAL_RESERVED_FIELD_LEN]);

            int length = Short.toUnsignedInt(inputBuffer.getShort());
            byte number = inputBuffer.get();
            int protocolId = Byte.toUnsignedInt(inputBuffer.get());

            byte spiSize = inputBuffer.get();
            int transformCount = Byte.toUnsignedInt(inputBuffer.get());

            // TODO: Add check: spiSize must be 0 in initial IKE SA negotiation
            // spiSize should be either 8 for IKE or 4 for IPsec.
            long spi = SPI_NOT_INCLUDED;
            switch (spiSize) {
                case SPI_LEN_NOT_INCLUDED:
                    // No SPI attached for IKE initial exchange.
                    break;
                case SPI_LEN_IPSEC:
                    spi = Integer.toUnsignedLong(inputBuffer.getInt());
                    break;
                case SPI_LEN_IKE:
                    spi = inputBuffer.getLong();
                    break;
                default:
                    throw new InvalidSyntaxException(
                            "Invalid value of spiSize in Proposal Substructure: " + spiSize);
            }

            Transform[] transformArray =
                    sTransformDecoder.decodeTransforms(transformCount, inputBuffer);
            // TODO: Validate that sum of all Transforms' lengths plus Proposal header length equals
            // to Proposal's length.

            List<EncryptionTransform> encryptAlgoList = new LinkedList<>();
            List<PrfTransform> prfList = new LinkedList<>();
            List<IntegrityTransform> integAlgoList = new LinkedList<>();
            List<DhGroupTransform> dhGroupList = new LinkedList<>();
            List<EsnTransform> esnList = new LinkedList<>();

            boolean hasUnrecognizedTransform = false;

            for (Transform transform : transformArray) {
                switch (transform.type) {
                    case Transform.TRANSFORM_TYPE_ENCR:
                        encryptAlgoList.add((EncryptionTransform) transform);
                        break;
                    case Transform.TRANSFORM_TYPE_PRF:
                        prfList.add((PrfTransform) transform);
                        break;
                    case Transform.TRANSFORM_TYPE_INTEG:
                        integAlgoList.add((IntegrityTransform) transform);
                        break;
                    case Transform.TRANSFORM_TYPE_DH:
                        dhGroupList.add((DhGroupTransform) transform);
                        break;
                    case Transform.TRANSFORM_TYPE_ESN:
                        esnList.add((EsnTransform) transform);
                        break;
                    default:
                        hasUnrecognizedTransform = true;
                }
            }

            if (protocolId == PROTOCOL_ID_IKE) {
                IkeSaProposal saProposal =
                        new IkeSaProposal(
                                encryptAlgoList.toArray(
                                        new EncryptionTransform[encryptAlgoList.size()]),
                                prfList.toArray(new PrfTransform[prfList.size()]),
                                integAlgoList.toArray(new IntegrityTransform[integAlgoList.size()]),
                                dhGroupList.toArray(new DhGroupTransform[dhGroupList.size()]));
                return new IkeProposal(number, spiSize, spi, saProposal, hasUnrecognizedTransform);
            } else {
                ChildSaProposal saProposal =
                        new ChildSaProposal(
                                encryptAlgoList.toArray(
                                        new EncryptionTransform[encryptAlgoList.size()]),
                                integAlgoList.toArray(new IntegrityTransform[integAlgoList.size()]),
                                dhGroupList.toArray(new DhGroupTransform[dhGroupList.size()]),
                                esnList.toArray(new EsnTransform[esnList.size()]));
                return new ChildProposal(number, spi, saProposal, hasUnrecognizedTransform);
            }
        }

        /** Package private */
        boolean isNegotiatedFrom(Proposal reqProposal) {
            if (protocolId != reqProposal.protocolId || number != reqProposal.number) {
                return false;
            }
            return getSaProposal().isNegotiatedFrom(reqProposal.getSaProposal());
        }

        protected void encodeToByteBuffer(boolean isLast, ByteBuffer byteBuffer) {
            Transform[] allTransforms = getSaProposal().getAllTransforms();
            byte isLastIndicator = isLast ? LAST_PROPOSAL : NOT_LAST_PROPOSAL;

            byteBuffer
                    .put(isLastIndicator)
                    .put(new byte[PROPOSAL_RESERVED_FIELD_LEN])
                    .putShort((short) getProposalLength())
                    .put(number)
                    .put((byte) protocolId)
                    .put(spiSize)
                    .put((byte) allTransforms.length);

            switch (spiSize) {
                case SPI_LEN_NOT_INCLUDED:
                    // No SPI attached for IKE initial exchange.
                    break;
                case SPI_LEN_IPSEC:
                    byteBuffer.putInt((int) spi);
                    break;
                case SPI_LEN_IKE:
                    byteBuffer.putLong((long) spi);
                    break;
                default:
                    throw new IllegalArgumentException(
                            "Invalid value of spiSize in Proposal Substructure: " + spiSize);
            }

            // Encode all Transform.
            for (int i = 0; i < allTransforms.length; i++) {
                // The last transform has the isLast flag set to true.
                allTransforms[i].encodeToByteBuffer(i == allTransforms.length - 1, byteBuffer);
            }
        }

        protected int getProposalLength() {
            int len = PROPOSAL_HEADER_LEN + spiSize;

            Transform[] allTransforms = getSaProposal().getAllTransforms();
            for (Transform t : allTransforms) len += t.getTransformLength();
            return len;
        }

        @Override
        @NonNull
        public String toString() {
            return "Proposal(" + number + ") " + getSaProposal().toString();
        }

        /** Package private method for releasing SPI resource in this unselected Proposal. */
        abstract void releaseSpiResourceIfExists();

        /** Package private method for getting SaProposal */
        abstract SaProposal getSaProposal();
    }

    /** This class represents a Proposal for IKE SA negotiation. */
    public static final class IkeProposal extends Proposal {
        private IkeSecurityParameterIndex mIkeSpiResource;

        public final IkeSaProposal saProposal;

        /**
         * Construct IkeProposal from a decoded inbound message for IKE negotiation.
         *
         * <p>Package private
         */
        IkeProposal(
                byte number,
                byte spiSize,
                long spi,
                IkeSaProposal saProposal,
                boolean hasUnrecognizedTransform) {
            super(number, PROTOCOL_ID_IKE, spiSize, spi, hasUnrecognizedTransform);
            this.saProposal = saProposal;
        }

        /** Construct IkeProposal for an outbound message for IKE negotiation. */
        private IkeProposal(
                byte number,
                byte spiSize,
                IkeSecurityParameterIndex ikeSpiResource,
                IkeSaProposal saProposal) {
            super(
                    number,
                    PROTOCOL_ID_IKE,
                    spiSize,
                    ikeSpiResource == null ? SPI_NOT_INCLUDED : ikeSpiResource.getSpi(),
                    false /* hasUnrecognizedTransform */);
            mIkeSpiResource = ikeSpiResource;
            this.saProposal = saProposal;
        }

        /**
         * Construct IkeProposal for an outbound message for IKE negotiation.
         *
         * <p>Package private
         */
        @VisibleForTesting
        static IkeProposal createIkeProposal(
                byte number,
                byte spiSize,
                IkeSaProposal saProposal,
                IkeSpiGenerator ikeSpiGenerator,
                InetAddress localAddress)
                throws IOException {
            // IKE_INIT uses SPI_LEN_NOT_INCLUDED, while rekeys use SPI_LEN_IKE
            IkeSecurityParameterIndex spiResource =
                    (spiSize == SPI_LEN_NOT_INCLUDED
                            ? null
                            : ikeSpiGenerator.allocateSpi(localAddress));
            return new IkeProposal(number, spiSize, spiResource, saProposal);
        }

        /** Package private method for releasing SPI resource in this unselected Proposal. */
        void releaseSpiResourceIfExists() {
            // mIkeSpiResource is null when doing IKE initial exchanges.
            if (mIkeSpiResource == null) return;
            mIkeSpiResource.close();
            mIkeSpiResource = null;
        }

        /**
         * Package private method for allocating SPI resource for a validated remotely generated IKE
         * SA proposal.
         */
        void allocateResourceForRemoteIkeSpi(
                IkeSpiGenerator ikeSpiGenerator, InetAddress remoteAddress) throws IOException {
            mIkeSpiResource = ikeSpiGenerator.allocateSpi(remoteAddress, spi);
        }

        @Override
        public SaProposal getSaProposal() {
            return saProposal;
        }

        /**
         * Get the IKE SPI resource.
         *
         * @return the IKE SPI resource or null for IKE initial exchanges.
         */
        public IkeSecurityParameterIndex getIkeSpiResource() {
            return mIkeSpiResource;
        }
    }

    /** This class represents a Proposal for Child SA negotiation. */
    public static final class ChildProposal extends Proposal {
        private SecurityParameterIndex mChildSpiResource;

        public final ChildSaProposal saProposal;

        /**
         * Construct ChildProposal from a decoded inbound message for Child SA negotiation.
         *
         * <p>Package private
         */
        ChildProposal(
                byte number,
                long spi,
                ChildSaProposal saProposal,
                boolean hasUnrecognizedTransform) {
            super(
                    number,
                    PROTOCOL_ID_ESP,
                    SPI_LEN_IPSEC,
                    spi,
                    hasUnrecognizedTransform);
            this.saProposal = saProposal;
        }

        /** Construct ChildProposal for an outbound message for Child SA negotiation. */
        private ChildProposal(
                byte number, SecurityParameterIndex childSpiResource, ChildSaProposal saProposal) {
            super(
                    number,
                    PROTOCOL_ID_ESP,
                    SPI_LEN_IPSEC,
                    (long) childSpiResource.getSpi(),
                    false /* hasUnrecognizedTransform */);
            mChildSpiResource = childSpiResource;
            this.saProposal = saProposal;
        }

        /**
         * Construct ChildProposal for an outbound message for Child SA negotiation.
         *
         * <p>Package private
         */
        @VisibleForTesting
        static ChildProposal createChildProposal(
                byte number,
                ChildSaProposal saProposal,
                IpSecSpiGenerator ipSecSpiGenerator,
                InetAddress localAddress)
                throws SpiUnavailableException, ResourceUnavailableException {
            return new ChildProposal(
                    number, ipSecSpiGenerator.allocateSpi(localAddress), saProposal);
        }

        /** Package private method for releasing SPI resource in this unselected Proposal. */
        void releaseSpiResourceIfExists() {
            if (mChildSpiResource ==  null) return;

            mChildSpiResource.close();
            mChildSpiResource = null;
        }

        /**
         * Package private method for allocating SPI resource for a validated remotely generated
         * Child SA proposal.
         */
        void allocateResourceForRemoteChildSpi(
                IpSecSpiGenerator ipSecSpiGenerator, InetAddress remoteAddress)
                throws ResourceUnavailableException, SpiUnavailableException {
            mChildSpiResource = ipSecSpiGenerator.allocateSpi(remoteAddress, (int) spi);
        }

        @Override
        public SaProposal getSaProposal() {
            return saProposal;
        }

        /**
         * Get the IPsec SPI resource.
         *
         * @return the IPsec SPI resource.
         */
        public SecurityParameterIndex getChildSpiResource() {
            return mChildSpiResource;
        }
    }

    @VisibleForTesting
    interface AttributeDecoder {
        List<Attribute> decodeAttributes(int length, ByteBuffer inputBuffer)
                throws IkeProtocolException;
    }

    /**
     * Transform is an abstract base class that represents the common information for all Transform
     * types. It may contain one or more {@link Attribute}.
     *
     * @see <a href="https://tools.ietf.org/html/rfc7296#section-3.3.2">RFC 7296, Internet Key
     *     Exchange Protocol Version 2 (IKEv2)</a>
     *     <p>Transforms with unrecognized Transform ID or containing unrecognized Attribute Type
     *     shall be ignored when processing received SA payload.
     */
    public abstract static class Transform {

        @Retention(RetentionPolicy.SOURCE)
        @IntDef({
            TRANSFORM_TYPE_ENCR,
            TRANSFORM_TYPE_PRF,
            TRANSFORM_TYPE_INTEG,
            TRANSFORM_TYPE_DH,
            TRANSFORM_TYPE_ESN
        })
        public @interface TransformType {}

        public static final int TRANSFORM_TYPE_ENCR = 1;
        public static final int TRANSFORM_TYPE_PRF = 2;
        public static final int TRANSFORM_TYPE_INTEG = 3;
        public static final int TRANSFORM_TYPE_DH = 4;
        public static final int TRANSFORM_TYPE_ESN = 5;

        private static final byte LAST_TRANSFORM = 0;
        private static final byte NOT_LAST_TRANSFORM = 3;

        // Length of reserved field of a Transform.
        private static final int TRANSFORM_RESERVED_FIELD_LEN = 1;

        // Length of the Transform that with no Attribute.
        protected static final int BASIC_TRANSFORM_LEN = 8;

        // TODO: Add constants for supported algorithms

        @VisibleForTesting
        static AttributeDecoder sAttributeDecoder =
                new AttributeDecoder() {
                    public List<Attribute> decodeAttributes(int length, ByteBuffer inputBuffer)
                            throws IkeProtocolException {
                        List<Attribute> list = new LinkedList<>();
                        int parsedLength = BASIC_TRANSFORM_LEN;
                        while (parsedLength < length) {
                            Pair<Attribute, Integer> pair = Attribute.readFrom(inputBuffer);
                            parsedLength += pair.second;
                            list.add(pair.first);
                        }
                        // TODO: Validate that parsedLength equals to length.
                        return list;
                    }
                };

        // Only supported type falls into {@link TransformType}
        public final int type;
        public final int id;
        public final boolean isSupported;

        /** Construct an instance of Transform for building an outbound packet. */
        protected Transform(int type, int id) {
            this.type = type;
            this.id = id;
            if (!isSupportedTransformId(id)) {
                throw new IllegalArgumentException(
                        "Unsupported " + getTransformTypeString() + " Algorithm ID: " + id);
            }
            this.isSupported = true;
        }

        /** Construct an instance of Transform for decoding an inbound packet. */
        protected Transform(int type, int id, List<Attribute> attributeList) {
            this.type = type;
            this.id = id;
            this.isSupported =
                    isSupportedTransformId(id) && !hasUnrecognizedAttribute(attributeList);
        }

        @VisibleForTesting
        static Transform readFrom(ByteBuffer inputBuffer) throws IkeProtocolException {
            byte isLast = inputBuffer.get();
            if (isLast != LAST_TRANSFORM && isLast != NOT_LAST_TRANSFORM) {
                throw new InvalidSyntaxException(
                        "Invalid value of Last Transform Substructure: " + isLast);
            }

            // Skip RESERVED byte
            inputBuffer.get(new byte[TRANSFORM_RESERVED_FIELD_LEN]);

            int length = Short.toUnsignedInt(inputBuffer.getShort());
            int type = Byte.toUnsignedInt(inputBuffer.get());

            // Skip RESERVED byte
            inputBuffer.get(new byte[TRANSFORM_RESERVED_FIELD_LEN]);

            int id = Short.toUnsignedInt(inputBuffer.getShort());

            // Decode attributes
            List<Attribute> attributeList = sAttributeDecoder.decodeAttributes(length, inputBuffer);

            validateAttributeUniqueness(attributeList);

            switch (type) {
                case TRANSFORM_TYPE_ENCR:
                    return new EncryptionTransform(id, attributeList);
                case TRANSFORM_TYPE_PRF:
                    return new PrfTransform(id, attributeList);
                case TRANSFORM_TYPE_INTEG:
                    return new IntegrityTransform(id, attributeList);
                case TRANSFORM_TYPE_DH:
                    return new DhGroupTransform(id, attributeList);
                case TRANSFORM_TYPE_ESN:
                    return new EsnTransform(id, attributeList);
                default:
                    return new UnrecognizedTransform(type, id, attributeList);
            }
        }

        // Throw InvalidSyntaxException if there are multiple Attributes of the same type
        private static void validateAttributeUniqueness(List<Attribute> attributeList)
                throws IkeProtocolException {
            Set<Integer> foundTypes = new ArraySet<>();
            for (Attribute attr : attributeList) {
                if (!foundTypes.add(attr.type)) {
                    throw new InvalidSyntaxException(
                            "There are multiple Attributes of the same type. ");
                }
            }
        }

        // Check if there is Attribute with unrecognized type.
        protected abstract boolean hasUnrecognizedAttribute(List<Attribute> attributeList);

        // Check if this Transform ID is supported.
        protected abstract boolean isSupportedTransformId(int id);

        // Encode Transform to a ByteBuffer.
        protected abstract void encodeToByteBuffer(boolean isLast, ByteBuffer byteBuffer);

        // Get entire Transform length.
        protected abstract int getTransformLength();

        protected void encodeBasicTransformToByteBuffer(boolean isLast, ByteBuffer byteBuffer) {
            byte isLastIndicator = isLast ? LAST_TRANSFORM : NOT_LAST_TRANSFORM;
            byteBuffer
                    .put(isLastIndicator)
                    .put(new byte[TRANSFORM_RESERVED_FIELD_LEN])
                    .putShort((short) getTransformLength())
                    .put((byte) type)
                    .put(new byte[TRANSFORM_RESERVED_FIELD_LEN])
                    .putShort((short) id);
        }

        /**
         * Get Tranform Type as a String.
         *
         * @return Tranform Type as a String.
         */
        public abstract String getTransformTypeString();

        // TODO: Add abstract getTransformIdString() to return specific algorithm/dhGroup name
    }

    /**
     * EncryptionTransform represents an encryption algorithm. It may contain an Atrribute
     * specifying the key length.
     *
     * @see <a href="https://tools.ietf.org/html/rfc7296#section-3.3.2">RFC 7296, Internet Key
     *     Exchange Protocol Version 2 (IKEv2)</a>
     */
    public static final class EncryptionTransform extends Transform {
        public static final int KEY_LEN_UNSPECIFIED = 0;

        // When using encryption algorithm with variable-length keys, mSpecifiedKeyLength MUST be
        // set and a KeyLengthAttribute MUST be attached. Otherwise, mSpecifiedKeyLength MUST NOT be
        // set and KeyLengthAttribute MUST NOT be attached.
        private final int mSpecifiedKeyLength;

        /**
         * Contruct an instance of EncryptionTransform with fixed key length for building an
         * outbound packet.
         *
         * @param id the IKE standard Transform ID.
         */
        public EncryptionTransform(@EncryptionAlgorithm int id) {
            this(id, KEY_LEN_UNSPECIFIED);
        }

        /**
         * Contruct an instance of EncryptionTransform with variable key length for building an
         * outbound packet.
         *
         * @param id the IKE standard Transform ID.
         * @param specifiedKeyLength the specified key length of this encryption algorithm.
         */
        public EncryptionTransform(@EncryptionAlgorithm int id, int specifiedKeyLength) {
            super(Transform.TRANSFORM_TYPE_ENCR, id);

            mSpecifiedKeyLength = specifiedKeyLength;
            try {
                validateKeyLength();
            } catch (InvalidSyntaxException e) {
                throw new IllegalArgumentException(e);
            }
        }

        /**
         * Contruct an instance of EncryptionTransform for decoding an inbound packet.
         *
         * @param id the IKE standard Transform ID.
         * @param attributeList the decoded list of Attribute.
         * @throws InvalidSyntaxException for syntax error.
         */
        protected EncryptionTransform(int id, List<Attribute> attributeList)
                throws InvalidSyntaxException {
            super(Transform.TRANSFORM_TYPE_ENCR, id, attributeList);
            if (!isSupported) {
                mSpecifiedKeyLength = KEY_LEN_UNSPECIFIED;
            } else {
                if (attributeList.size() == 0) {
                    mSpecifiedKeyLength = KEY_LEN_UNSPECIFIED;
                } else {
                    KeyLengthAttribute attr = getKeyLengthAttribute(attributeList);
                    mSpecifiedKeyLength = attr.keyLength;
                }
                validateKeyLength();
            }
        }

        /**
         * Get the specified key length.
         *
         * @return the specified key length.
         */
        public int getSpecifiedKeyLength() {
            return mSpecifiedKeyLength;
        }

        @Override
        public int hashCode() {
            return Objects.hash(type, id, mSpecifiedKeyLength);
        }

        @Override
        public boolean equals(Object o) {
            if (!(o instanceof EncryptionTransform)) return false;

            EncryptionTransform other = (EncryptionTransform) o;
            return (type == other.type
                    && id == other.id
                    && mSpecifiedKeyLength == other.mSpecifiedKeyLength);
        }

        @Override
        protected boolean isSupportedTransformId(int id) {
            return SaProposal.isSupportedEncryptionAlgorithm(id);
        }

        @Override
        protected boolean hasUnrecognizedAttribute(List<Attribute> attributeList) {
            for (Attribute attr : attributeList) {
                if (attr instanceof UnrecognizedAttribute) {
                    return true;
                }
            }
            return false;
        }

        private KeyLengthAttribute getKeyLengthAttribute(List<Attribute> attributeList) {
            for (Attribute attr : attributeList) {
                if (attr.type == Attribute.ATTRIBUTE_TYPE_KEY_LENGTH) {
                    return (KeyLengthAttribute) attr;
                }
            }
            throw new IllegalArgumentException("Cannot find Attribute with Key Length type");
        }

        private void validateKeyLength() throws InvalidSyntaxException {
            switch (id) {
                case SaProposal.ENCRYPTION_ALGORITHM_3DES:
                    if (mSpecifiedKeyLength != KEY_LEN_UNSPECIFIED) {
                        throw new InvalidSyntaxException(
                                "Must not set Key Length value for this "
                                        + getTransformTypeString()
                                        + " Algorithm ID: "
                                        + id);
                    }
                    return;
                case SaProposal.ENCRYPTION_ALGORITHM_AES_CBC:
                    /* fall through */
                case SaProposal.ENCRYPTION_ALGORITHM_AES_GCM_8:
                    /* fall through */
                case SaProposal.ENCRYPTION_ALGORITHM_AES_GCM_12:
                    /* fall through */
                case SaProposal.ENCRYPTION_ALGORITHM_AES_GCM_16:
                    if (mSpecifiedKeyLength == KEY_LEN_UNSPECIFIED) {
                        throw new InvalidSyntaxException(
                                "Must set Key Length value for this "
                                        + getTransformTypeString()
                                        + " Algorithm ID: "
                                        + id);
                    }
                    if (mSpecifiedKeyLength != SaProposal.KEY_LEN_AES_128
                            && mSpecifiedKeyLength != SaProposal.KEY_LEN_AES_192
                            && mSpecifiedKeyLength != SaProposal.KEY_LEN_AES_256) {
                        throw new InvalidSyntaxException(
                                "Invalid key length for this "
                                        + getTransformTypeString()
                                        + " Algorithm ID: "
                                        + id);
                    }
                    return;
                default:
                    // Won't hit here.
                    throw new IllegalArgumentException(
                            "Unrecognized Encryption Algorithm ID: " + id);
            }
        }

        @Override
        protected void encodeToByteBuffer(boolean isLast, ByteBuffer byteBuffer) {
            encodeBasicTransformToByteBuffer(isLast, byteBuffer);

            if (mSpecifiedKeyLength != KEY_LEN_UNSPECIFIED) {
                new KeyLengthAttribute(mSpecifiedKeyLength).encodeToByteBuffer(byteBuffer);
            }
        }

        @Override
        protected int getTransformLength() {
            int len = BASIC_TRANSFORM_LEN;

            if (mSpecifiedKeyLength != KEY_LEN_UNSPECIFIED) {
                len += new KeyLengthAttribute(mSpecifiedKeyLength).getAttributeLength();
            }

            return len;
        }

        @Override
        public String getTransformTypeString() {
            return "Encryption Algorithm";
        }

        @Override
        @NonNull
        public String toString() {
            return SaProposal.getEncryptionAlgorithmString(id)
                    + "("
                    + getSpecifiedKeyLength()
                    + ")";
        }
    }

    /**
     * PrfTransform represents an pseudorandom function.
     *
     * @see <a href="https://tools.ietf.org/html/rfc7296#section-3.3.2">RFC 7296, Internet Key
     *     Exchange Protocol Version 2 (IKEv2)</a>
     */
    public static final class PrfTransform extends Transform {
        /**
         * Contruct an instance of PrfTransform for building an outbound packet.
         *
         * @param id the IKE standard Transform ID.
         */
        public PrfTransform(@PseudorandomFunction int id) {
            super(Transform.TRANSFORM_TYPE_PRF, id);
        }

        /**
         * Contruct an instance of PrfTransform for decoding an inbound packet.
         *
         * @param id the IKE standard Transform ID.
         * @param attributeList the decoded list of Attribute.
         * @throws InvalidSyntaxException for syntax error.
         */
        protected PrfTransform(int id, List<Attribute> attributeList)
                throws InvalidSyntaxException {
            super(Transform.TRANSFORM_TYPE_PRF, id, attributeList);
        }

        @Override
        public int hashCode() {
            return Objects.hash(type, id);
        }

        @Override
        public boolean equals(Object o) {
            if (!(o instanceof PrfTransform)) return false;

            PrfTransform other = (PrfTransform) o;
            return (type == other.type && id == other.id);
        }

        @Override
        protected boolean isSupportedTransformId(int id) {
            return SaProposal.isSupportedPseudorandomFunction(id);
        }

        @Override
        protected boolean hasUnrecognizedAttribute(List<Attribute> attributeList) {
            return !attributeList.isEmpty();
        }

        @Override
        protected void encodeToByteBuffer(boolean isLast, ByteBuffer byteBuffer) {
            encodeBasicTransformToByteBuffer(isLast, byteBuffer);
        }

        @Override
        protected int getTransformLength() {
            return BASIC_TRANSFORM_LEN;
        }

        @Override
        public String getTransformTypeString() {
            return "Pseudorandom Function";
        }

        @Override
        @NonNull
        public String toString() {
            return SaProposal.getPseudorandomFunctionString(id);
        }
    }

    /**
     * IntegrityTransform represents an integrity algorithm.
     *
     * <p>Proposing integrity algorithm for ESP SA is optional. Omitting the IntegrityTransform is
     * equivalent to including it with a value of NONE. When multiple integrity algorithms are
     * provided, choosing any of them are acceptable.
     *
     * @see <a href="https://tools.ietf.org/html/rfc7296#section-3.3.2">RFC 7296, Internet Key
     *     Exchange Protocol Version 2 (IKEv2)</a>
     */
    public static final class IntegrityTransform extends Transform {
        /**
         * Contruct an instance of IntegrityTransform for building an outbound packet.
         *
         * @param id the IKE standard Transform ID.
         */
        public IntegrityTransform(@IntegrityAlgorithm int id) {
            super(Transform.TRANSFORM_TYPE_INTEG, id);
        }

        /**
         * Contruct an instance of IntegrityTransform for decoding an inbound packet.
         *
         * @param id the IKE standard Transform ID.
         * @param attributeList the decoded list of Attribute.
         * @throws InvalidSyntaxException for syntax error.
         */
        protected IntegrityTransform(int id, List<Attribute> attributeList)
                throws InvalidSyntaxException {
            super(Transform.TRANSFORM_TYPE_INTEG, id, attributeList);
        }

        @Override
        public int hashCode() {
            return Objects.hash(type, id);
        }

        @Override
        public boolean equals(Object o) {
            if (!(o instanceof IntegrityTransform)) return false;

            IntegrityTransform other = (IntegrityTransform) o;
            return (type == other.type && id == other.id);
        }

        @Override
        protected boolean isSupportedTransformId(int id) {
            return SaProposal.isSupportedIntegrityAlgorithm(id);
        }

        @Override
        protected boolean hasUnrecognizedAttribute(List<Attribute> attributeList) {
            return !attributeList.isEmpty();
        }

        @Override
        protected void encodeToByteBuffer(boolean isLast, ByteBuffer byteBuffer) {
            encodeBasicTransformToByteBuffer(isLast, byteBuffer);
        }

        @Override
        protected int getTransformLength() {
            return BASIC_TRANSFORM_LEN;
        }

        @Override
        public String getTransformTypeString() {
            return "Integrity Algorithm";
        }

        @Override
        @NonNull
        public String toString() {
            return SaProposal.getIntegrityAlgorithmString(id);
        }
    }

    /**
     * DhGroupTransform represents a Diffie-Hellman Group
     *
     * <p>Proposing DH group for non-first Child SA is optional. Omitting the DhGroupTransform is
     * equivalent to including it with a value of NONE. When multiple DH groups are provided,
     * choosing any of them are acceptable.
     *
     * @see <a href="https://tools.ietf.org/html/rfc7296#section-3.3.2">RFC 7296, Internet Key
     *     Exchange Protocol Version 2 (IKEv2)</a>
     */
    public static final class DhGroupTransform extends Transform {
        /**
         * Contruct an instance of DhGroupTransform for building an outbound packet.
         *
         * @param id the IKE standard Transform ID.
         */
        public DhGroupTransform(@DhGroup int id) {
            super(Transform.TRANSFORM_TYPE_DH, id);
        }

        /**
         * Contruct an instance of DhGroupTransform for decoding an inbound packet.
         *
         * @param id the IKE standard Transform ID.
         * @param attributeList the decoded list of Attribute.
         * @throws InvalidSyntaxException for syntax error.
         */
        protected DhGroupTransform(int id, List<Attribute> attributeList)
                throws InvalidSyntaxException {
            super(Transform.TRANSFORM_TYPE_DH, id, attributeList);
        }

        @Override
        public int hashCode() {
            return Objects.hash(type, id);
        }

        @Override
        public boolean equals(Object o) {
            if (!(o instanceof DhGroupTransform)) return false;

            DhGroupTransform other = (DhGroupTransform) o;
            return (type == other.type && id == other.id);
        }

        @Override
        protected boolean isSupportedTransformId(int id) {
            return SaProposal.isSupportedDhGroup(id);
        }

        @Override
        protected boolean hasUnrecognizedAttribute(List<Attribute> attributeList) {
            return !attributeList.isEmpty();
        }

        @Override
        protected void encodeToByteBuffer(boolean isLast, ByteBuffer byteBuffer) {
            encodeBasicTransformToByteBuffer(isLast, byteBuffer);
        }

        @Override
        protected int getTransformLength() {
            return BASIC_TRANSFORM_LEN;
        }

        @Override
        public String getTransformTypeString() {
            return "Diffie-Hellman Group";
        }

        @Override
        @NonNull
        public String toString() {
            return SaProposal.getDhGroupString(id);
        }
    }

    /**
     * EsnTransform represents ESN policy that indicates if IPsec SA uses tranditional 32-bit
     * sequence numbers or extended(64-bit) sequence numbers.
     *
     * <p>Currently IKE library only supports negotiating IPsec SA that do not use extended sequence
     * numbers. The Transform ID of EsnTransform in outbound packets is not user configurable.
     *
     * @see <a href="https://tools.ietf.org/html/rfc7296#section-3.3.2">RFC 7296, Internet Key
     *     Exchange Protocol Version 2 (IKEv2)</a>
     */
    public static final class EsnTransform extends Transform {
        @Retention(RetentionPolicy.SOURCE)
        @IntDef({ESN_POLICY_NO_EXTENDED, ESN_POLICY_EXTENDED})
        public @interface EsnPolicy {}

        public static final int ESN_POLICY_NO_EXTENDED = 0;
        public static final int ESN_POLICY_EXTENDED = 1;

        /**
         * Construct an instance of EsnTransform indicates using no-extended sequence numbers for
         * building an outbound packet.
         */
        public EsnTransform() {
            super(Transform.TRANSFORM_TYPE_ESN, ESN_POLICY_NO_EXTENDED);
        }

        /**
         * Contruct an instance of EsnTransform for decoding an inbound packet.
         *
         * @param id the IKE standard Transform ID.
         * @param attributeList the decoded list of Attribute.
         * @throws InvalidSyntaxException for syntax error.
         */
        protected EsnTransform(int id, List<Attribute> attributeList)
                throws InvalidSyntaxException {
            super(Transform.TRANSFORM_TYPE_ESN, id, attributeList);
        }

        @Override
        public int hashCode() {
            return Objects.hash(type, id);
        }

        @Override
        public boolean equals(Object o) {
            if (!(o instanceof EsnTransform)) return false;

            EsnTransform other = (EsnTransform) o;
            return (type == other.type && id == other.id);
        }

        @Override
        protected boolean isSupportedTransformId(int id) {
            return (id == ESN_POLICY_NO_EXTENDED || id == ESN_POLICY_EXTENDED);
        }

        @Override
        protected boolean hasUnrecognizedAttribute(List<Attribute> attributeList) {
            return !attributeList.isEmpty();
        }

        @Override
        protected void encodeToByteBuffer(boolean isLast, ByteBuffer byteBuffer) {
            encodeBasicTransformToByteBuffer(isLast, byteBuffer);
        }

        @Override
        protected int getTransformLength() {
            return BASIC_TRANSFORM_LEN;
        }

        @Override
        public String getTransformTypeString() {
            return "Extended Sequence Numbers";
        }

        @Override
        @NonNull
        public String toString() {
            if (id == ESN_POLICY_NO_EXTENDED) {
                return "ESN_No_Extended";
            }
            return "ESN_Extended";
        }
    }

    /**
     * UnrecognizedTransform represents a Transform with unrecognized Transform Type.
     *
     * <p>Proposals containing an UnrecognizedTransform should be ignored.
     */
    protected static final class UnrecognizedTransform extends Transform {
        protected UnrecognizedTransform(int type, int id, List<Attribute> attributeList) {
            super(type, id, attributeList);
        }

        @Override
        protected boolean isSupportedTransformId(int id) {
            return false;
        }

        @Override
        protected boolean hasUnrecognizedAttribute(List<Attribute> attributeList) {
            return !attributeList.isEmpty();
        }

        @Override
        protected void encodeToByteBuffer(boolean isLast, ByteBuffer byteBuffer) {
            throw new UnsupportedOperationException(
                    "It is not supported to encode a Transform with" + getTransformTypeString());
        }

        @Override
        protected int getTransformLength() {
            throw new UnsupportedOperationException(
                    "It is not supported to get length of a Transform with "
                            + getTransformTypeString());
        }

        /**
         * Return Tranform Type of Unrecognized Transform as a String.
         *
         * @return Tranform Type of Unrecognized Transform as a String.
         */
        @Override
        public String getTransformTypeString() {
            return "Unrecognized Transform Type.";
        }
    }

    /**
     * Attribute is an abtract base class for completing the specification of some {@link
     * Transform}.
     *
     * <p>Attribute is either in Type/Value format or Type/Length/Value format. For TV format,
     * Attribute length is always 4 bytes containing value for 2 bytes. While for TLV format,
     * Attribute length is determined by length field.
     *
     * <p>Currently only Key Length type is supported
     *
     * @see <a href="https://tools.ietf.org/html/rfc7296#section-3.3.5">RFC 7296, Internet Key
     *     Exchange Protocol Version 2 (IKEv2)</a>
     */
    public abstract static class Attribute {
        @Retention(RetentionPolicy.SOURCE)
        @IntDef({ATTRIBUTE_TYPE_KEY_LENGTH})
        public @interface AttributeType {}

        // Support only one Attribute type: Key Length. Should use Type/Value format.
        public static final int ATTRIBUTE_TYPE_KEY_LENGTH = 14;

        // Mask to extract the left most AF bit to indicate Attribute Format.
        private static final int ATTRIBUTE_FORMAT_MASK = 0x8000;
        // Mask to extract 15 bits after the AF bit to indicate Attribute Type.
        private static final int ATTRIBUTE_TYPE_MASK = 0x7fff;

        // Package private mask to indicate that Type-Value (TV) Attribute Format is used.
        static final int ATTRIBUTE_FORMAT_TV = ATTRIBUTE_FORMAT_MASK;

        // Package private
        static final int TV_ATTRIBUTE_VALUE_LEN = 2;
        static final int TV_ATTRIBUTE_TOTAL_LEN = 4;
        static final int TVL_ATTRIBUTE_HEADER_LEN = TV_ATTRIBUTE_TOTAL_LEN;

        // Only Key Length type belongs to AttributeType
        public final int type;

        /** Construct an instance of an Attribute when decoding message. */
        protected Attribute(int type) {
            this.type = type;
        }

        @VisibleForTesting
        static Pair<Attribute, Integer> readFrom(ByteBuffer inputBuffer)
                throws IkeProtocolException {
            short formatAndType = inputBuffer.getShort();
            int format = formatAndType & ATTRIBUTE_FORMAT_MASK;
            int type = formatAndType & ATTRIBUTE_TYPE_MASK;

            int length = 0;
            byte[] value = new byte[0];
            if (format == ATTRIBUTE_FORMAT_TV) {
                // Type/Value format
                length = TV_ATTRIBUTE_TOTAL_LEN;
                value = new byte[TV_ATTRIBUTE_VALUE_LEN];
            } else {
                // Type/Length/Value format
                if (type == ATTRIBUTE_TYPE_KEY_LENGTH) {
                    throw new InvalidSyntaxException("Wrong format in Transform Attribute");
                }

                length = Short.toUnsignedInt(inputBuffer.getShort());
                int valueLen = length - TVL_ATTRIBUTE_HEADER_LEN;
                // IkeMessage will catch exception if valueLen is negative.
                value = new byte[valueLen];
            }

            inputBuffer.get(value);

            switch (type) {
                case ATTRIBUTE_TYPE_KEY_LENGTH:
                    return new Pair(new KeyLengthAttribute(value), length);
                default:
                    return new Pair(new UnrecognizedAttribute(type, value), length);
            }
        }

        // Encode Attribute to a ByteBuffer.
        protected abstract void encodeToByteBuffer(ByteBuffer byteBuffer);

        // Get entire Attribute length.
        protected abstract int getAttributeLength();
    }

    /** KeyLengthAttribute represents a Key Length type Attribute */
    public static final class KeyLengthAttribute extends Attribute {
        public final int keyLength;

        protected KeyLengthAttribute(byte[] value) {
            this(Short.toUnsignedInt(ByteBuffer.wrap(value).getShort()));
        }

        protected KeyLengthAttribute(int keyLength) {
            super(ATTRIBUTE_TYPE_KEY_LENGTH);
            this.keyLength = keyLength;
        }

        @Override
        protected void encodeToByteBuffer(ByteBuffer byteBuffer) {
            byteBuffer
                    .putShort((short) (ATTRIBUTE_FORMAT_TV | ATTRIBUTE_TYPE_KEY_LENGTH))
                    .putShort((short) keyLength);
        }

        @Override
        protected int getAttributeLength() {
            return TV_ATTRIBUTE_TOTAL_LEN;
        }
    }

    /**
     * UnrecognizedAttribute represents a Attribute with unrecoginzed Attribute Type.
     *
     * <p>Transforms containing UnrecognizedAttribute should be ignored.
     */
    protected static final class UnrecognizedAttribute extends Attribute {
        protected UnrecognizedAttribute(int type, byte[] value) {
            super(type);
        }

        @Override
        protected void encodeToByteBuffer(ByteBuffer byteBuffer) {
            throw new UnsupportedOperationException(
                    "It is not supported to encode an unrecognized Attribute.");
        }

        @Override
        protected int getAttributeLength() {
            throw new UnsupportedOperationException(
                    "It is not supported to get length of an unrecognized Attribute.");
        }
    }

    /**
     * Encode SA payload to ByteBUffer.
     *
     * @param nextPayload type of payload that follows this payload.
     * @param byteBuffer destination ByteBuffer that stores encoded payload.
     */
    @Override
    protected void encodeToByteBuffer(@PayloadType int nextPayload, ByteBuffer byteBuffer) {
        encodePayloadHeaderToByteBuffer(nextPayload, getPayloadLength(), byteBuffer);

        for (int i = 0; i < proposalList.size(); i++) {
            // The last proposal has the isLast flag set to true.
            proposalList.get(i).encodeToByteBuffer(i == proposalList.size() - 1, byteBuffer);
        }
    }

    /**
     * Get entire payload length.
     *
     * @return entire payload length.
     */
    @Override
    protected int getPayloadLength() {
        int len = GENERIC_HEADER_LENGTH;

        for (Proposal p : proposalList) len += p.getProposalLength();

        return len;
    }

    /**
     * Return the payload type as a String.
     *
     * @return the payload type as a String.
     */
    @Override
    public String getTypeString() {
        return "SA";
    }

    @Override
    @NonNull
    public String toString() {
        StringBuilder sb = new StringBuilder();
        if (isSaResponse) {
            sb.append("SA Response: ");
        } else {
            sb.append("SA Request: ");
        }

        int len = proposalList.size();
        for (int i = 0; i < len; i++) {
            sb.append(proposalList.get(i).toString());
            if (i < len - 1) sb.append(", ");
        }

        return sb.toString();
    }
}