Loading...
   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
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
/*
 * Copyright (c) 2008-2020 Apple Inc. All rights reserved.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. The rights granted to you under the License
 * may not be used to create, or enable the creation or redistribution of,
 * unlawful or unlicensed copies of an Apple operating system, or to
 * circumvent, violate, or enable the circumvention or violation of, any
 * terms of an Apple operating system software license agreement.
 *
 * Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
 */

/*	$FreeBSD: src/sys/netinet6/ipsec.c,v 1.3.2.7 2001/07/19 06:37:23 kris Exp $	*/
/*	$KAME: ipsec.c,v 1.103 2001/05/24 07:14:18 sakane Exp $	*/

/*
 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * IPsec controller part.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/mcache.h>
#include <sys/domain.h>
#include <sys/protosw.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/errno.h>
#include <sys/time.h>
#include <sys/kernel.h>
#include <sys/syslog.h>
#include <sys/sysctl.h>
#include <sys/priv.h>
#include <kern/locks.h>
#include <sys/kauth.h>
#include <sys/bitstring.h>

#include <libkern/OSAtomic.h>
#include <libkern/sysctl.h>

#include <net/if.h>
#include <net/route.h>
#include <net/if_ipsec.h>
#include <net/if_ports_used.h>

#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_var.h>
#include <netinet/in_var.h>
#include <netinet/udp.h>
#include <netinet/udp_var.h>
#include <netinet/ip_ecn.h>
#include <netinet6/ip6_ecn.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>

#include <netinet/ip6.h>
#include <netinet6/ip6_var.h>
#include <netinet/in_pcb.h>
#include <netinet/icmp6.h>

#include <netinet6/ipsec.h>
#include <netinet6/ipsec6.h>
#include <netinet6/ah.h>
#include <netinet6/ah6.h>
#if IPSEC_ESP
#include <netinet6/esp.h>
#include <netinet6/esp6.h>
#endif
#include <netkey/key.h>
#include <netkey/keydb.h>
#include <netkey/key_debug.h>

#include <net/net_osdep.h>

#include <IOKit/pwr_mgt/IOPM.h>

#include <os/log_private.h>

#if IPSEC_DEBUG
int ipsec_debug = 1;
#else
int ipsec_debug = 0;
#endif

#include <sys/kdebug.h>
#define DBG_LAYER_BEG                   NETDBG_CODE(DBG_NETIPSEC, 1)
#define DBG_LAYER_END                   NETDBG_CODE(DBG_NETIPSEC, 3)
#define DBG_FNC_GETPOL_SOCK             NETDBG_CODE(DBG_NETIPSEC, (1 << 8))
#define DBG_FNC_GETPOL_ADDR             NETDBG_CODE(DBG_NETIPSEC, (2 << 8))
#define DBG_FNC_IPSEC_OUT               NETDBG_CODE(DBG_NETIPSEC, (3 << 8))

extern lck_mtx_t *sadb_mutex;

struct ipsecstat ipsecstat;
int ip4_ah_cleartos = 1;
int ip4_ah_offsetmask = 0;      /* maybe IP_DF? */
int ip4_ipsec_dfbit = 0;        /* DF bit on encap. 0: clear 1: set 2: copy */
int ip4_esp_trans_deflev = IPSEC_LEVEL_USE;
int ip4_esp_net_deflev = IPSEC_LEVEL_USE;
int ip4_ah_trans_deflev = IPSEC_LEVEL_USE;
int ip4_ah_net_deflev = IPSEC_LEVEL_USE;
struct secpolicy ip4_def_policy;
int ip4_ipsec_ecn = ECN_COMPATIBILITY;          /* ECN ignore(-1)/compatibility(0)/normal(1) */
int ip4_esp_randpad = -1;
int     esp_udp_encap_port = 0;
static int sysctl_def_policy SYSCTL_HANDLER_ARGS;
extern int natt_keepalive_interval;
extern u_int64_t natt_now;

struct ipsec_tag;

void *sleep_wake_handle = NULL;
bool ipsec_save_wake_pkt = false;

SYSCTL_DECL(_net_inet_ipsec);
SYSCTL_DECL(_net_inet6_ipsec6);
/* net.inet.ipsec */
SYSCTL_STRUCT(_net_inet_ipsec, IPSECCTL_STATS,
    stats, CTLFLAG_RD | CTLFLAG_LOCKED, &ipsecstat, ipsecstat, "");
SYSCTL_PROC(_net_inet_ipsec, IPSECCTL_DEF_POLICY, def_policy, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
    &ip4_def_policy.policy, 0, &sysctl_def_policy, "I", "");
SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
    CTLFLAG_RW | CTLFLAG_LOCKED, &ip4_esp_trans_deflev, 0, "");
SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
    CTLFLAG_RW | CTLFLAG_LOCKED, &ip4_esp_net_deflev, 0, "");
SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
    CTLFLAG_RW | CTLFLAG_LOCKED, &ip4_ah_trans_deflev, 0, "");
SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
    CTLFLAG_RW | CTLFLAG_LOCKED, &ip4_ah_net_deflev, 0, "");
SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS,
    ah_cleartos, CTLFLAG_RW | CTLFLAG_LOCKED, &ip4_ah_cleartos, 0, "");
SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_OFFSETMASK,
    ah_offsetmask, CTLFLAG_RW | CTLFLAG_LOCKED, &ip4_ah_offsetmask, 0, "");
SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT,
    dfbit, CTLFLAG_RW | CTLFLAG_LOCKED, &ip4_ipsec_dfbit, 0, "");
SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN,
    ecn, CTLFLAG_RW | CTLFLAG_LOCKED, &ip4_ipsec_ecn, 0, "");
SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEBUG,
    debug, CTLFLAG_RW | CTLFLAG_LOCKED, &ipsec_debug, 0, "");
SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ESP_RANDPAD,
    esp_randpad, CTLFLAG_RW | CTLFLAG_LOCKED, &ip4_esp_randpad, 0, "");

/* for performance, we bypass ipsec until a security policy is set */
int ipsec_bypass = 1;
SYSCTL_INT(_net_inet_ipsec, OID_AUTO, bypass, CTLFLAG_RD | CTLFLAG_LOCKED, &ipsec_bypass, 0, "");

/*
 * NAT Traversal requires a UDP port for encapsulation,
 * esp_udp_encap_port controls which port is used. Racoon
 * must set this port to the port racoon is using locally
 * for nat traversal.
 */
SYSCTL_INT(_net_inet_ipsec, OID_AUTO, esp_port,
    CTLFLAG_RW | CTLFLAG_LOCKED, &esp_udp_encap_port, 0, "");

struct ipsecstat ipsec6stat;
int ip6_esp_trans_deflev = IPSEC_LEVEL_USE;
int ip6_esp_net_deflev = IPSEC_LEVEL_USE;
int ip6_ah_trans_deflev = IPSEC_LEVEL_USE;
int ip6_ah_net_deflev = IPSEC_LEVEL_USE;
struct secpolicy ip6_def_policy;
int ip6_ipsec_ecn = ECN_COMPATIBILITY;          /* ECN ignore(-1)/compatibility(0)/normal(1) */
int ip6_esp_randpad = -1;

/* net.inet6.ipsec6 */
SYSCTL_STRUCT(_net_inet6_ipsec6, IPSECCTL_STATS,
    stats, CTLFLAG_RD | CTLFLAG_LOCKED, &ipsec6stat, ipsecstat, "");
SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY,
    def_policy, CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_def_policy.policy, 0, "");
SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
    CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_esp_trans_deflev, 0, "");
SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
    CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_esp_net_deflev, 0, "");
SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
    CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_ah_trans_deflev, 0, "");
SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
    CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_ah_net_deflev, 0, "");
SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN,
    ecn, CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_ipsec_ecn, 0, "");
SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEBUG,
    debug, CTLFLAG_RW | CTLFLAG_LOCKED, &ipsec_debug, 0, "");
SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ESP_RANDPAD,
    esp_randpad, CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_esp_randpad, 0, "");

SYSCTL_DECL(_net_link_generic_system);

struct ipsec_wake_pkt_info ipsec_wake_pkt;

static int ipsec_setspidx_interface(struct secpolicyindex *, u_int8_t, struct mbuf *,
    int, int, int);
static int ipsec_setspidx_mbuf(struct secpolicyindex *, u_int8_t, u_int,
    struct mbuf *, int);
static int ipsec4_setspidx_inpcb(struct mbuf *, struct inpcb *pcb);
static int ipsec6_setspidx_in6pcb(struct mbuf *, struct in6pcb *pcb);
static int ipsec_setspidx(struct mbuf *, struct secpolicyindex *, int, int);
static void ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *, int);
static int ipsec4_setspidx_ipaddr(struct mbuf *, struct secpolicyindex *);
static void ipsec6_get_ulp(struct mbuf *m, struct secpolicyindex *, int);
static int ipsec6_setspidx_ipaddr(struct mbuf *, struct secpolicyindex *);
static struct inpcbpolicy *ipsec_newpcbpolicy(void);
static void ipsec_delpcbpolicy(struct inpcbpolicy *);
static struct secpolicy *ipsec_deepcopy_policy(struct secpolicy *src);
static int ipsec_set_policy(struct secpolicy **pcb_sp,
    int optname, caddr_t request, size_t len, int priv);
static void vshiftl(unsigned char *, int, size_t);
static int ipsec_in_reject(struct secpolicy *, struct mbuf *);
static int ipsec64_encapsulate(struct mbuf *, struct secasvar *);
static int ipsec6_update_routecache_and_output(struct ipsec_output_state *state, struct secasvar *sav);
static int ipsec46_encapsulate(struct ipsec_output_state *state, struct secasvar *sav);
static struct ipsec_tag *ipsec_addaux(struct mbuf *);
static struct ipsec_tag *ipsec_findaux(struct mbuf *);
static void ipsec_optaux(struct mbuf *, struct ipsec_tag *);
int ipsec_send_natt_keepalive(struct secasvar *sav);
bool ipsec_fill_offload_frame(ifnet_t ifp, struct secasvar *sav, struct ifnet_keepalive_offload_frame *frame, size_t frame_data_offset);

extern bool IOPMCopySleepWakeUUIDKey(char *, size_t);

typedef IOReturn (*IOServiceInterestHandler)( void * target, void * refCon,
    UInt32 messageType, void * provider,
    void * messageArgument, vm_size_t argSize );
extern void *registerSleepWakeInterest(IOServiceInterestHandler, void *, void *);

static int
sysctl_def_policy SYSCTL_HANDLER_ARGS
{
	int new_policy = ip4_def_policy.policy;
	int error = sysctl_handle_int(oidp, &new_policy, 0, req);

#pragma unused(arg1, arg2)
	if (error == 0) {
		if (new_policy != IPSEC_POLICY_NONE &&
		    new_policy != IPSEC_POLICY_DISCARD) {
			return EINVAL;
		}
		ip4_def_policy.policy = new_policy;

		/* Turn off the bypass if the default security policy changes */
		if (ipsec_bypass != 0 && ip4_def_policy.policy != IPSEC_POLICY_NONE) {
			ipsec_bypass = 0;
		}
	}

	return error;
}

/*
 * For OUTBOUND packet having a socket. Searching SPD for packet,
 * and return a pointer to SP.
 * OUT:	NULL:	no apropreate SP found, the following value is set to error.
 *		0	: bypass
 *		EACCES	: discard packet.
 *		ENOENT	: ipsec_acquire() in progress, maybe.
 *		others	: error occurred.
 *	others:	a pointer to SP
 *
 * NOTE: IPv6 mapped adddress concern is implemented here.
 */
struct secpolicy *
ipsec4_getpolicybysock(struct mbuf *m,
    u_int8_t dir,
    struct socket *so,
    int *error)
{
	struct inpcbpolicy *pcbsp = NULL;
	struct secpolicy *currsp = NULL;        /* policy on socket */
	struct secpolicy *kernsp = NULL;        /* policy on kernel */

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
	/* sanity check */
	if (m == NULL || so == NULL || error == NULL) {
		panic("ipsec4_getpolicybysock: NULL pointer was passed.\n");
	}

	if (so->so_pcb == NULL) {
		printf("ipsec4_getpolicybysock: so->so_pcb == NULL\n");
		return ipsec4_getpolicybyaddr(m, dir, 0, error);
	}

	switch (SOCK_DOM(so)) {
	case PF_INET:
		pcbsp = sotoinpcb(so)->inp_sp;
		break;
	case PF_INET6:
		pcbsp = sotoin6pcb(so)->in6p_sp;
		break;
	}

	if (!pcbsp) {
		/* Socket has not specified an IPSEC policy */
		return ipsec4_getpolicybyaddr(m, dir, 0, error);
	}

	KERNEL_DEBUG(DBG_FNC_GETPOL_SOCK | DBG_FUNC_START, 0, 0, 0, 0, 0);

	switch (SOCK_DOM(so)) {
	case PF_INET:
		/* set spidx in pcb */
		*error = ipsec4_setspidx_inpcb(m, sotoinpcb(so));
		break;
	case PF_INET6:
		/* set spidx in pcb */
		*error = ipsec6_setspidx_in6pcb(m, sotoin6pcb(so));
		break;
	default:
		panic("ipsec4_getpolicybysock: unsupported address family\n");
	}
	if (*error) {
		KERNEL_DEBUG(DBG_FNC_GETPOL_SOCK | DBG_FUNC_END, 1, *error, 0, 0, 0);
		return NULL;
	}

	/* sanity check */
	if (pcbsp == NULL) {
		panic("ipsec4_getpolicybysock: pcbsp is NULL.\n");
	}

	switch (dir) {
	case IPSEC_DIR_INBOUND:
		currsp = pcbsp->sp_in;
		break;
	case IPSEC_DIR_OUTBOUND:
		currsp = pcbsp->sp_out;
		break;
	default:
		panic("ipsec4_getpolicybysock: illegal direction.\n");
	}

	/* sanity check */
	if (currsp == NULL) {
		panic("ipsec4_getpolicybysock: currsp is NULL.\n");
	}

	/* when privilieged socket */
	if (pcbsp->priv) {
		switch (currsp->policy) {
		case IPSEC_POLICY_BYPASS:
			lck_mtx_lock(sadb_mutex);
			currsp->refcnt++;
			lck_mtx_unlock(sadb_mutex);
			*error = 0;
			KERNEL_DEBUG(DBG_FNC_GETPOL_SOCK | DBG_FUNC_END, 2, *error, 0, 0, 0);
			return currsp;

		case IPSEC_POLICY_ENTRUST:
			/* look for a policy in SPD */
			kernsp = key_allocsp(&currsp->spidx, dir);

			/* SP found */
			if (kernsp != NULL) {
				KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
				    printf("DP ipsec4_getpolicybysock called "
				    "to allocate SP:0x%llx\n",
				    (uint64_t)VM_KERNEL_ADDRPERM(kernsp)));
				*error = 0;
				KERNEL_DEBUG(DBG_FNC_GETPOL_SOCK | DBG_FUNC_END, 3, *error, 0, 0, 0);
				return kernsp;
			}

			/* no SP found */
			lck_mtx_lock(sadb_mutex);
			if (ip4_def_policy.policy != IPSEC_POLICY_DISCARD
			    && ip4_def_policy.policy != IPSEC_POLICY_NONE) {
				ipseclog((LOG_INFO,
				    "fixed system default policy: %d->%d\n",
				    ip4_def_policy.policy, IPSEC_POLICY_NONE));
				ip4_def_policy.policy = IPSEC_POLICY_NONE;
			}
			ip4_def_policy.refcnt++;
			lck_mtx_unlock(sadb_mutex);
			*error = 0;
			KERNEL_DEBUG(DBG_FNC_GETPOL_SOCK | DBG_FUNC_END, 4, *error, 0, 0, 0);
			return &ip4_def_policy;

		case IPSEC_POLICY_IPSEC:
			lck_mtx_lock(sadb_mutex);
			currsp->refcnt++;
			lck_mtx_unlock(sadb_mutex);
			*error = 0;
			KERNEL_DEBUG(DBG_FNC_GETPOL_SOCK | DBG_FUNC_END, 5, *error, 0, 0, 0);
			return currsp;

		default:
			ipseclog((LOG_ERR, "ipsec4_getpolicybysock: "
			    "Invalid policy for PCB %d\n", currsp->policy));
			*error = EINVAL;
			KERNEL_DEBUG(DBG_FNC_GETPOL_SOCK | DBG_FUNC_END, 6, *error, 0, 0, 0);
			return NULL;
		}
		/* NOTREACHED */
	}

	/* when non-privilieged socket */
	/* look for a policy in SPD */
	kernsp = key_allocsp(&currsp->spidx, dir);

	/* SP found */
	if (kernsp != NULL) {
		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
		    printf("DP ipsec4_getpolicybysock called "
		    "to allocate SP:0x%llx\n",
		    (uint64_t)VM_KERNEL_ADDRPERM(kernsp)));
		*error = 0;
		KERNEL_DEBUG(DBG_FNC_GETPOL_SOCK | DBG_FUNC_END, 7, *error, 0, 0, 0);
		return kernsp;
	}

	/* no SP found */
	switch (currsp->policy) {
	case IPSEC_POLICY_BYPASS:
		ipseclog((LOG_ERR, "ipsec4_getpolicybysock: "
		    "Illegal policy for non-priviliged defined %d\n",
		    currsp->policy));
		*error = EINVAL;
		KERNEL_DEBUG(DBG_FNC_GETPOL_SOCK | DBG_FUNC_END, 8, *error, 0, 0, 0);
		return NULL;

	case IPSEC_POLICY_ENTRUST:
		lck_mtx_lock(sadb_mutex);
		if (ip4_def_policy.policy != IPSEC_POLICY_DISCARD
		    && ip4_def_policy.policy != IPSEC_POLICY_NONE) {
			ipseclog((LOG_INFO,
			    "fixed system default policy: %d->%d\n",
			    ip4_def_policy.policy, IPSEC_POLICY_NONE));
			ip4_def_policy.policy = IPSEC_POLICY_NONE;
		}
		ip4_def_policy.refcnt++;
		lck_mtx_unlock(sadb_mutex);
		*error = 0;
		KERNEL_DEBUG(DBG_FNC_GETPOL_SOCK | DBG_FUNC_END, 9, *error, 0, 0, 0);
		return &ip4_def_policy;

	case IPSEC_POLICY_IPSEC:
		lck_mtx_lock(sadb_mutex);
		currsp->refcnt++;
		lck_mtx_unlock(sadb_mutex);
		*error = 0;
		KERNEL_DEBUG(DBG_FNC_GETPOL_SOCK | DBG_FUNC_END, 10, *error, 0, 0, 0);
		return currsp;

	default:
		ipseclog((LOG_ERR, "ipsec4_getpolicybysock: "
		    "Invalid policy for PCB %d\n", currsp->policy));
		*error = EINVAL;
		KERNEL_DEBUG(DBG_FNC_GETPOL_SOCK | DBG_FUNC_END, 11, *error, 0, 0, 0);
		return NULL;
	}
	/* NOTREACHED */
}

/*
 * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet,
 * and return a pointer to SP.
 * OUT:	positive: a pointer to the entry for security policy leaf matched.
 *	NULL:	no apropreate SP found, the following value is set to error.
 *		0	: bypass
 *		EACCES	: discard packet.
 *		ENOENT	: ipsec_acquire() in progress, maybe.
 *		others	: error occurred.
 */
struct secpolicy *
ipsec4_getpolicybyaddr(struct mbuf *m,
    u_int8_t dir,
    int flag,
    int *error)
{
	struct secpolicy *sp = NULL;

	if (ipsec_bypass != 0) {
		return 0;
	}

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);

	/* sanity check */
	if (m == NULL || error == NULL) {
		panic("ipsec4_getpolicybyaddr: NULL pointer was passed.\n");
	}
	{
		struct secpolicyindex spidx;

		KERNEL_DEBUG(DBG_FNC_GETPOL_ADDR | DBG_FUNC_START, 0, 0, 0, 0, 0);
		bzero(&spidx, sizeof(spidx));

		/* make a index to look for a policy */
		*error = ipsec_setspidx_mbuf(&spidx, dir, AF_INET, m,
		    (flag & IP_FORWARDING) ? 0 : 1);

		if (*error != 0) {
			KERNEL_DEBUG(DBG_FNC_GETPOL_ADDR | DBG_FUNC_END, 1, *error, 0, 0, 0);
			return NULL;
		}

		sp = key_allocsp(&spidx, dir);
	}

	/* SP found */
	if (sp != NULL) {
		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
		    printf("DP ipsec4_getpolicybyaddr called "
		    "to allocate SP:0x%llx\n",
		    (uint64_t)VM_KERNEL_ADDRPERM(sp)));
		*error = 0;
		KERNEL_DEBUG(DBG_FNC_GETPOL_ADDR | DBG_FUNC_END, 2, *error, 0, 0, 0);
		return sp;
	}

	/* no SP found */
	lck_mtx_lock(sadb_mutex);
	if (ip4_def_policy.policy != IPSEC_POLICY_DISCARD
	    && ip4_def_policy.policy != IPSEC_POLICY_NONE) {
		ipseclog((LOG_INFO, "fixed system default policy:%d->%d\n",
		    ip4_def_policy.policy,
		    IPSEC_POLICY_NONE));
		ip4_def_policy.policy = IPSEC_POLICY_NONE;
	}
	ip4_def_policy.refcnt++;
	lck_mtx_unlock(sadb_mutex);
	*error = 0;
	KERNEL_DEBUG(DBG_FNC_GETPOL_ADDR | DBG_FUNC_END, 3, *error, 0, 0, 0);
	return &ip4_def_policy;
}

/* Match with bound interface rather than src addr.
 * Unlike getpolicybyaddr, do not set the default policy.
 * Return 0 if should continue processing, or -1 if packet
 * should be dropped.
 */
int
ipsec4_getpolicybyinterface(struct mbuf *m,
    u_int8_t dir,
    int *flags,
    struct ip_out_args *ipoa,
    struct secpolicy **sp)
{
	struct secpolicyindex spidx;
	int error = 0;

	if (ipsec_bypass != 0) {
		return 0;
	}

	/* Sanity check */
	if (m == NULL || ipoa == NULL || sp == NULL) {
		panic("ipsec4_getpolicybyinterface: NULL pointer was passed.\n");
	}

	if (ipoa->ipoa_boundif == IFSCOPE_NONE) {
		return 0;
	}

	KERNEL_DEBUG(DBG_FNC_GETPOL_ADDR | DBG_FUNC_START, 0, 0, 0, 0, 0);
	bzero(&spidx, sizeof(spidx));

	/* make a index to look for a policy */
	error = ipsec_setspidx_interface(&spidx, dir, m, (*flags & IP_FORWARDING) ? 0 : 1,
	    ipoa->ipoa_boundif, 4);

	if (error != 0) {
		KERNEL_DEBUG(DBG_FNC_GETPOL_ADDR | DBG_FUNC_END, 1, error, 0, 0, 0);
		return 0;
	}

	*sp = key_allocsp(&spidx, dir);

	/* Return SP, whether NULL or not */
	if (*sp != NULL && (*sp)->policy == IPSEC_POLICY_IPSEC) {
		if ((*sp)->ipsec_if == NULL) {
			/* Invalid to capture on an interface without redirect */
			key_freesp(*sp, KEY_SADB_UNLOCKED);
			*sp = NULL;
			return -1;
		} else if ((*sp)->disabled) {
			/* Disabled policies go in the clear */
			key_freesp(*sp, KEY_SADB_UNLOCKED);
			*sp = NULL;
			*flags |= IP_NOIPSEC; /* Avoid later IPsec check */
		} else {
			/* If policy is enabled, redirect to ipsec interface */
			ipoa->ipoa_boundif = (*sp)->ipsec_if->if_index;
		}
	}

	KERNEL_DEBUG(DBG_FNC_GETPOL_ADDR | DBG_FUNC_END, 2, error, 0, 0, 0);

	return 0;
}


/*
 * For OUTBOUND packet having a socket. Searching SPD for packet,
 * and return a pointer to SP.
 * OUT:	NULL:	no apropreate SP found, the following value is set to error.
 *		0	: bypass
 *		EACCES	: discard packet.
 *		ENOENT	: ipsec_acquire() in progress, maybe.
 *		others	: error occurred.
 *	others:	a pointer to SP
 */
struct secpolicy *
ipsec6_getpolicybysock(struct mbuf *m,
    u_int8_t dir,
    struct socket *so,
    int *error)
{
	struct inpcbpolicy *pcbsp = NULL;
	struct secpolicy *currsp = NULL;        /* policy on socket */
	struct secpolicy *kernsp = NULL;        /* policy on kernel */

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);

	/* sanity check */
	if (m == NULL || so == NULL || error == NULL) {
		panic("ipsec6_getpolicybysock: NULL pointer was passed.\n");
	}

#if DIAGNOSTIC
	if (SOCK_DOM(so) != PF_INET6) {
		panic("ipsec6_getpolicybysock: socket domain != inet6\n");
	}
#endif

	pcbsp = sotoin6pcb(so)->in6p_sp;

	if (!pcbsp) {
		return ipsec6_getpolicybyaddr(m, dir, 0, error);
	}

	/* set spidx in pcb */
	ipsec6_setspidx_in6pcb(m, sotoin6pcb(so));

	/* sanity check */
	if (pcbsp == NULL) {
		panic("ipsec6_getpolicybysock: pcbsp is NULL.\n");
	}

	switch (dir) {
	case IPSEC_DIR_INBOUND:
		currsp = pcbsp->sp_in;
		break;
	case IPSEC_DIR_OUTBOUND:
		currsp = pcbsp->sp_out;
		break;
	default:
		panic("ipsec6_getpolicybysock: illegal direction.\n");
	}

	/* sanity check */
	if (currsp == NULL) {
		panic("ipsec6_getpolicybysock: currsp is NULL.\n");
	}

	/* when privilieged socket */
	if (pcbsp->priv) {
		switch (currsp->policy) {
		case IPSEC_POLICY_BYPASS:
			lck_mtx_lock(sadb_mutex);
			currsp->refcnt++;
			lck_mtx_unlock(sadb_mutex);
			*error = 0;
			return currsp;

		case IPSEC_POLICY_ENTRUST:
			/* look for a policy in SPD */
			kernsp = key_allocsp(&currsp->spidx, dir);

			/* SP found */
			if (kernsp != NULL) {
				KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
				    printf("DP ipsec6_getpolicybysock called "
				    "to allocate SP:0x%llx\n",
				    (uint64_t)VM_KERNEL_ADDRPERM(kernsp)));
				*error = 0;
				return kernsp;
			}

			/* no SP found */
			lck_mtx_lock(sadb_mutex);
			if (ip6_def_policy.policy != IPSEC_POLICY_DISCARD
			    && ip6_def_policy.policy != IPSEC_POLICY_NONE) {
				ipseclog((LOG_INFO,
				    "fixed system default policy: %d->%d\n",
				    ip6_def_policy.policy, IPSEC_POLICY_NONE));
				ip6_def_policy.policy = IPSEC_POLICY_NONE;
			}
			ip6_def_policy.refcnt++;
			lck_mtx_unlock(sadb_mutex);
			*error = 0;
			return &ip6_def_policy;

		case IPSEC_POLICY_IPSEC:
			lck_mtx_lock(sadb_mutex);
			currsp->refcnt++;
			lck_mtx_unlock(sadb_mutex);
			*error = 0;
			return currsp;

		default:
			ipseclog((LOG_ERR, "ipsec6_getpolicybysock: "
			    "Invalid policy for PCB %d\n", currsp->policy));
			*error = EINVAL;
			return NULL;
		}
		/* NOTREACHED */
	}

	/* when non-privilieged socket */
	/* look for a policy in SPD */
	kernsp = key_allocsp(&currsp->spidx, dir);

	/* SP found */
	if (kernsp != NULL) {
		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
		    printf("DP ipsec6_getpolicybysock called "
		    "to allocate SP:0x%llx\n",
		    (uint64_t)VM_KERNEL_ADDRPERM(kernsp)));
		*error = 0;
		return kernsp;
	}

	/* no SP found */
	switch (currsp->policy) {
	case IPSEC_POLICY_BYPASS:
		ipseclog((LOG_ERR, "ipsec6_getpolicybysock: "
		    "Illegal policy for non-priviliged defined %d\n",
		    currsp->policy));
		*error = EINVAL;
		return NULL;

	case IPSEC_POLICY_ENTRUST:
		lck_mtx_lock(sadb_mutex);
		if (ip6_def_policy.policy != IPSEC_POLICY_DISCARD
		    && ip6_def_policy.policy != IPSEC_POLICY_NONE) {
			ipseclog((LOG_INFO,
			    "fixed system default policy: %d->%d\n",
			    ip6_def_policy.policy, IPSEC_POLICY_NONE));
			ip6_def_policy.policy = IPSEC_POLICY_NONE;
		}
		ip6_def_policy.refcnt++;
		lck_mtx_unlock(sadb_mutex);
		*error = 0;
		return &ip6_def_policy;

	case IPSEC_POLICY_IPSEC:
		lck_mtx_lock(sadb_mutex);
		currsp->refcnt++;
		lck_mtx_unlock(sadb_mutex);
		*error = 0;
		return currsp;

	default:
		ipseclog((LOG_ERR,
		    "ipsec6_policybysock: Invalid policy for PCB %d\n",
		    currsp->policy));
		*error = EINVAL;
		return NULL;
	}
	/* NOTREACHED */
}

/*
 * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet,
 * and return a pointer to SP.
 * `flag' means that packet is to be forwarded whether or not.
 *	flag = 1: forwad
 * OUT:	positive: a pointer to the entry for security policy leaf matched.
 *	NULL:	no apropreate SP found, the following value is set to error.
 *		0	: bypass
 *		EACCES	: discard packet.
 *		ENOENT	: ipsec_acquire() in progress, maybe.
 *		others	: error occurred.
 */
#ifndef IP_FORWARDING
#define IP_FORWARDING 1
#endif

struct secpolicy *
ipsec6_getpolicybyaddr(struct mbuf *m,
    u_int8_t dir,
    int flag,
    int *error)
{
	struct secpolicy *sp = NULL;

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);

	/* sanity check */
	if (m == NULL || error == NULL) {
		panic("ipsec6_getpolicybyaddr: NULL pointer was passed.\n");
	}

	{
		struct secpolicyindex spidx;

		bzero(&spidx, sizeof(spidx));

		/* make a index to look for a policy */
		*error = ipsec_setspidx_mbuf(&spidx, dir, AF_INET6, m,
		    (flag & IP_FORWARDING) ? 0 : 1);

		if (*error != 0) {
			return NULL;
		}

		sp = key_allocsp(&spidx, dir);
	}

	/* SP found */
	if (sp != NULL) {
		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
		    printf("DP ipsec6_getpolicybyaddr called "
		    "to allocate SP:0x%llx\n",
		    (uint64_t)VM_KERNEL_ADDRPERM(sp)));
		*error = 0;
		return sp;
	}

	/* no SP found */
	lck_mtx_lock(sadb_mutex);
	if (ip6_def_policy.policy != IPSEC_POLICY_DISCARD
	    && ip6_def_policy.policy != IPSEC_POLICY_NONE) {
		ipseclog((LOG_INFO, "fixed system default policy: %d->%d\n",
		    ip6_def_policy.policy, IPSEC_POLICY_NONE));
		ip6_def_policy.policy = IPSEC_POLICY_NONE;
	}
	ip6_def_policy.refcnt++;
	lck_mtx_unlock(sadb_mutex);
	*error = 0;
	return &ip6_def_policy;
}

/* Match with bound interface rather than src addr.
 * Unlike getpolicybyaddr, do not set the default policy.
 * Return 0 if should continue processing, or -1 if packet
 * should be dropped.
 */
int
ipsec6_getpolicybyinterface(struct mbuf *m,
    u_int8_t dir,
    int flag,
    struct ip6_out_args *ip6oap,
    int *noipsec,
    struct secpolicy **sp)
{
	struct secpolicyindex spidx;
	int error = 0;

	if (ipsec_bypass != 0) {
		return 0;
	}

	/* Sanity check */
	if (m == NULL || sp == NULL || noipsec == NULL || ip6oap == NULL) {
		panic("ipsec6_getpolicybyinterface: NULL pointer was passed.\n");
	}

	*noipsec = 0;

	if (ip6oap->ip6oa_boundif == IFSCOPE_NONE) {
		return 0;
	}

	KERNEL_DEBUG(DBG_FNC_GETPOL_ADDR | DBG_FUNC_START, 0, 0, 0, 0, 0);
	bzero(&spidx, sizeof(spidx));

	/* make a index to look for a policy */
	error = ipsec_setspidx_interface(&spidx, dir, m, (flag & IP_FORWARDING) ? 0 : 1,
	    ip6oap->ip6oa_boundif, 6);

	if (error != 0) {
		KERNEL_DEBUG(DBG_FNC_GETPOL_ADDR | DBG_FUNC_END, 1, error, 0, 0, 0);
		return 0;
	}

	*sp = key_allocsp(&spidx, dir);

	/* Return SP, whether NULL or not */
	if (*sp != NULL && (*sp)->policy == IPSEC_POLICY_IPSEC) {
		if ((*sp)->ipsec_if == NULL) {
			/* Invalid to capture on an interface without redirect */
			key_freesp(*sp, KEY_SADB_UNLOCKED);
			*sp = NULL;
			return -1;
		} else if ((*sp)->disabled) {
			/* Disabled policies go in the clear */
			key_freesp(*sp, KEY_SADB_UNLOCKED);
			*sp = NULL;
			*noipsec = 1; /* Avoid later IPsec check */
		} else {
			/* If policy is enabled, redirect to ipsec interface */
			ip6oap->ip6oa_boundif = (*sp)->ipsec_if->if_index;
		}
	}

	KERNEL_DEBUG(DBG_FNC_GETPOL_ADDR | DBG_FUNC_END, 2, *error, 0, 0, 0);

	return 0;
}

/*
 * set IP address into spidx from mbuf.
 * When Forwarding packet and ICMP echo reply, this function is used.
 *
 * IN:	get the followings from mbuf.
 *	protocol family, src, dst, next protocol
 * OUT:
 *	0:	success.
 *	other:	failure, and set errno.
 */
static int
ipsec_setspidx_mbuf(
	struct secpolicyindex *spidx,
	u_int8_t dir,
	__unused u_int family,
	struct mbuf *m,
	int needport)
{
	int error;

	/* sanity check */
	if (spidx == NULL || m == NULL) {
		panic("ipsec_setspidx_mbuf: NULL pointer was passed.\n");
	}

	bzero(spidx, sizeof(*spidx));

	error = ipsec_setspidx(m, spidx, needport, 0);
	if (error) {
		goto bad;
	}
	spidx->dir = dir;

	return 0;

bad:
	/* XXX initialize */
	bzero(spidx, sizeof(*spidx));
	return EINVAL;
}

static int
ipsec_setspidx_interface(
	struct secpolicyindex *spidx,
	u_int8_t dir,
	struct mbuf *m,
	int needport,
	int ifindex,
	int ip_version)
{
	int error;

	/* sanity check */
	if (spidx == NULL || m == NULL) {
		panic("ipsec_setspidx_interface: NULL pointer was passed.\n");
	}

	bzero(spidx, sizeof(*spidx));

	error = ipsec_setspidx(m, spidx, needport, ip_version);
	if (error) {
		goto bad;
	}
	spidx->dir = dir;

	if (ifindex != 0) {
		ifnet_head_lock_shared();
		spidx->internal_if = ifindex2ifnet[ifindex];
		ifnet_head_done();
	} else {
		spidx->internal_if = NULL;
	}

	return 0;

bad:
	return EINVAL;
}

static int
ipsec4_setspidx_inpcb(struct mbuf *m, struct inpcb *pcb)
{
	struct secpolicyindex *spidx;
	int error;

	if (ipsec_bypass != 0) {
		return 0;
	}

	/* sanity check */
	if (pcb == NULL) {
		panic("ipsec4_setspidx_inpcb: no PCB found.\n");
	}
	if (pcb->inp_sp == NULL) {
		panic("ipsec4_setspidx_inpcb: no inp_sp found.\n");
	}
	if (pcb->inp_sp->sp_out == NULL || pcb->inp_sp->sp_in == NULL) {
		panic("ipsec4_setspidx_inpcb: no sp_in/out found.\n");
	}

	bzero(&pcb->inp_sp->sp_in->spidx, sizeof(*spidx));
	bzero(&pcb->inp_sp->sp_out->spidx, sizeof(*spidx));

	spidx = &pcb->inp_sp->sp_in->spidx;
	error = ipsec_setspidx(m, spidx, 1, 0);
	if (error) {
		goto bad;
	}
	spidx->dir = IPSEC_DIR_INBOUND;

	spidx = &pcb->inp_sp->sp_out->spidx;
	error = ipsec_setspidx(m, spidx, 1, 0);
	if (error) {
		goto bad;
	}
	spidx->dir = IPSEC_DIR_OUTBOUND;

	return 0;

bad:
	bzero(&pcb->inp_sp->sp_in->spidx, sizeof(*spidx));
	bzero(&pcb->inp_sp->sp_out->spidx, sizeof(*spidx));
	return error;
}

static int
ipsec6_setspidx_in6pcb(struct mbuf *m, struct in6pcb *pcb)
{
	struct secpolicyindex *spidx;
	int error;

	/* sanity check */
	if (pcb == NULL) {
		panic("ipsec6_setspidx_in6pcb: no PCB found.\n");
	}
	if (pcb->in6p_sp == NULL) {
		panic("ipsec6_setspidx_in6pcb: no in6p_sp found.\n");
	}
	if (pcb->in6p_sp->sp_out == NULL || pcb->in6p_sp->sp_in == NULL) {
		panic("ipsec6_setspidx_in6pcb: no sp_in/out found.\n");
	}

	bzero(&pcb->in6p_sp->sp_in->spidx, sizeof(*spidx));
	bzero(&pcb->in6p_sp->sp_out->spidx, sizeof(*spidx));

	spidx = &pcb->in6p_sp->sp_in->spidx;
	error = ipsec_setspidx(m, spidx, 1, 0);
	if (error) {
		goto bad;
	}
	spidx->dir = IPSEC_DIR_INBOUND;

	spidx = &pcb->in6p_sp->sp_out->spidx;
	error = ipsec_setspidx(m, spidx, 1, 0);
	if (error) {
		goto bad;
	}
	spidx->dir = IPSEC_DIR_OUTBOUND;

	return 0;

bad:
	bzero(&pcb->in6p_sp->sp_in->spidx, sizeof(*spidx));
	bzero(&pcb->in6p_sp->sp_out->spidx, sizeof(*spidx));
	return error;
}

/*
 * configure security policy index (src/dst/proto/sport/dport)
 * by looking at the content of mbuf.
 * the caller is responsible for error recovery (like clearing up spidx).
 */
static int
ipsec_setspidx(struct mbuf *m,
    struct secpolicyindex *spidx,
    int needport,
    int force_ip_version)
{
	struct ip *ip = NULL;
	struct ip ipbuf;
	u_int v;
	struct mbuf *n;
	int len;
	int error;

	if (m == NULL) {
		panic("ipsec_setspidx: m == 0 passed.\n");
	}

	/*
	 * validate m->m_pkthdr.len.  we see incorrect length if we
	 * mistakenly call this function with inconsistent mbuf chain
	 * (like 4.4BSD tcp/udp processing).  XXX should we panic here?
	 */
	len = 0;
	for (n = m; n; n = n->m_next) {
		len += n->m_len;
	}
	if (m->m_pkthdr.len != len) {
		KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
		    printf("ipsec_setspidx: "
		    "total of m_len(%d) != pkthdr.len(%d), "
		    "ignored.\n",
		    len, m->m_pkthdr.len));
		return EINVAL;
	}

	if (m->m_pkthdr.len < sizeof(struct ip)) {
		KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
		    printf("ipsec_setspidx: "
		    "pkthdr.len(%d) < sizeof(struct ip), ignored.\n",
		    m->m_pkthdr.len));
		return EINVAL;
	}

	if (m->m_len >= sizeof(*ip)) {
		ip = mtod(m, struct ip *);
	} else {
		m_copydata(m, 0, sizeof(ipbuf), (caddr_t)&ipbuf);
		ip = &ipbuf;
	}

	if (force_ip_version) {
		v = force_ip_version;
	} else {
#ifdef _IP_VHL
		v = _IP_VHL_V(ip->ip_vhl);
#else
		v = ip->ip_v;
#endif
	}
	switch (v) {
	case 4:
		error = ipsec4_setspidx_ipaddr(m, spidx);
		if (error) {
			return error;
		}
		ipsec4_get_ulp(m, spidx, needport);
		return 0;
	case 6:
		if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
			KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
			    printf("ipsec_setspidx: "
			    "pkthdr.len(%d) < sizeof(struct ip6_hdr), "
			    "ignored.\n", m->m_pkthdr.len));
			return EINVAL;
		}
		error = ipsec6_setspidx_ipaddr(m, spidx);
		if (error) {
			return error;
		}
		ipsec6_get_ulp(m, spidx, needport);
		return 0;
	default:
		KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
		    printf("ipsec_setspidx: "
		    "unknown IP version %u, ignored.\n", v));
		return EINVAL;
	}
}

static void
ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
{
	struct ip ip;
	struct ip6_ext ip6e;
	u_int8_t nxt;
	int off;
	struct tcphdr th;
	struct udphdr uh;

	/* sanity check */
	if (m == NULL) {
		panic("ipsec4_get_ulp: NULL pointer was passed.\n");
	}
	if (m->m_pkthdr.len < sizeof(ip)) {
		panic("ipsec4_get_ulp: too short\n");
	}

	/* set default */
	spidx->ul_proto = IPSEC_ULPROTO_ANY;
	((struct sockaddr_in *)&spidx->src)->sin_port = IPSEC_PORT_ANY;
	((struct sockaddr_in *)&spidx->dst)->sin_port = IPSEC_PORT_ANY;

	m_copydata(m, 0, sizeof(ip), (caddr_t)&ip);
	/* ip_input() flips it into host endian XXX need more checking */
	if (ip.ip_off & (IP_MF | IP_OFFMASK)) {
		return;
	}

	nxt = ip.ip_p;
#ifdef _IP_VHL
	off = _IP_VHL_HL(ip->ip_vhl) << 2;
#else
	off = ip.ip_hl << 2;
#endif
	while (off < m->m_pkthdr.len) {
		switch (nxt) {
		case IPPROTO_TCP:
			spidx->ul_proto = nxt;
			if (!needport) {
				return;
			}
			if (off + sizeof(struct tcphdr) > m->m_pkthdr.len) {
				return;
			}
			m_copydata(m, off, sizeof(th), (caddr_t)&th);
			((struct sockaddr_in *)&spidx->src)->sin_port =
			    th.th_sport;
			((struct sockaddr_in *)&spidx->dst)->sin_port =
			    th.th_dport;
			return;
		case IPPROTO_UDP:
			spidx->ul_proto = nxt;
			if (!needport) {
				return;
			}
			if (off + sizeof(struct udphdr) > m->m_pkthdr.len) {
				return;
			}
			m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
			((struct sockaddr_in *)&spidx->src)->sin_port =
			    uh.uh_sport;
			((struct sockaddr_in *)&spidx->dst)->sin_port =
			    uh.uh_dport;
			return;
		case IPPROTO_AH:
			if (off + sizeof(ip6e) > m->m_pkthdr.len) {
				return;
			}
			m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
			off += (ip6e.ip6e_len + 2) << 2;
			nxt = ip6e.ip6e_nxt;
			break;
		case IPPROTO_ICMP:
		default:
			/* XXX intermediate headers??? */
			spidx->ul_proto = nxt;
			return;
		}
	}
}

/* assumes that m is sane */
static int
ipsec4_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
{
	struct ip *ip = NULL;
	struct ip ipbuf;
	struct sockaddr_in *sin;

	if (m->m_len >= sizeof(*ip)) {
		ip = mtod(m, struct ip *);
	} else {
		m_copydata(m, 0, sizeof(ipbuf), (caddr_t)&ipbuf);
		ip = &ipbuf;
	}

	sin = (struct sockaddr_in *)&spidx->src;
	bzero(sin, sizeof(*sin));
	sin->sin_family = AF_INET;
	sin->sin_len = sizeof(struct sockaddr_in);
	bcopy(&ip->ip_src, &sin->sin_addr, sizeof(ip->ip_src));
	spidx->prefs = sizeof(struct in_addr) << 3;

	sin = (struct sockaddr_in *)&spidx->dst;
	bzero(sin, sizeof(*sin));
	sin->sin_family = AF_INET;
	sin->sin_len = sizeof(struct sockaddr_in);
	bcopy(&ip->ip_dst, &sin->sin_addr, sizeof(ip->ip_dst));
	spidx->prefd = sizeof(struct in_addr) << 3;

	return 0;
}

static void
ipsec6_get_ulp(struct mbuf *m,
    struct secpolicyindex *spidx,
    int needport)
{
	int off, nxt;
	struct tcphdr th;
	struct udphdr uh;

	/* sanity check */
	if (m == NULL) {
		panic("ipsec6_get_ulp: NULL pointer was passed.\n");
	}

	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
	    printf("ipsec6_get_ulp:\n"); kdebug_mbuf(m));

	/* set default */
	spidx->ul_proto = IPSEC_ULPROTO_ANY;
	((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
	((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;

	nxt = -1;
	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
	if (off < 0 || m->m_pkthdr.len < off) {
		return;
	}

	VERIFY(nxt <= UINT8_MAX);
	switch (nxt) {
	case IPPROTO_TCP:
		spidx->ul_proto = (u_int8_t)nxt;
		if (!needport) {
			break;
		}
		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len) {
			break;
		}
		m_copydata(m, off, sizeof(th), (caddr_t)&th);
		((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
		break;
	case IPPROTO_UDP:
		spidx->ul_proto = (u_int8_t)nxt;
		if (!needport) {
			break;
		}
		if (off + sizeof(struct udphdr) > m->m_pkthdr.len) {
			break;
		}
		m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
		((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
		break;
	case IPPROTO_ICMPV6:
	default:
		/* XXX intermediate headers??? */
		spidx->ul_proto = (u_int8_t)nxt;
		break;
	}
}

/* assumes that m is sane */
static int
ipsec6_setspidx_ipaddr(struct mbuf *m,
    struct secpolicyindex *spidx)
{
	struct ip6_hdr *ip6 = NULL;
	struct ip6_hdr ip6buf;
	struct sockaddr_in6 *sin6;

	if (m->m_len >= sizeof(*ip6)) {
		ip6 = mtod(m, struct ip6_hdr *);
	} else {
		m_copydata(m, 0, sizeof(ip6buf), (caddr_t)&ip6buf);
		ip6 = &ip6buf;
	}

	sin6 = (struct sockaddr_in6 *)&spidx->src;
	bzero(sin6, sizeof(*sin6));
	sin6->sin6_family = AF_INET6;
	sin6->sin6_len = sizeof(struct sockaddr_in6);
	bcopy(&ip6->ip6_src, &sin6->sin6_addr, sizeof(ip6->ip6_src));
	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
		sin6->sin6_addr.s6_addr16[1] = 0;
		sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
	}
	spidx->prefs = sizeof(struct in6_addr) << 3;

	sin6 = (struct sockaddr_in6 *)&spidx->dst;
	bzero(sin6, sizeof(*sin6));
	sin6->sin6_family = AF_INET6;
	sin6->sin6_len = sizeof(struct sockaddr_in6);
	bcopy(&ip6->ip6_dst, &sin6->sin6_addr, sizeof(ip6->ip6_dst));
	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
		sin6->sin6_addr.s6_addr16[1] = 0;
		sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
	}
	spidx->prefd = sizeof(struct in6_addr) << 3;

	return 0;
}

static struct inpcbpolicy *
ipsec_newpcbpolicy(void)
{
	struct inpcbpolicy *p;

	p = (struct inpcbpolicy *)_MALLOC(sizeof(*p), M_SECA, M_WAITOK);
	return p;
}

static void
ipsec_delpcbpolicy(struct inpcbpolicy *p)
{
	FREE(p, M_SECA);
}

/* initialize policy in PCB */
int
ipsec_init_policy(struct socket *so,
    struct inpcbpolicy **pcb_sp)
{
	struct inpcbpolicy *new;

	/* sanity check. */
	if (so == NULL || pcb_sp == NULL) {
		panic("ipsec_init_policy: NULL pointer was passed.\n");
	}

	new = ipsec_newpcbpolicy();
	if (new == NULL) {
		ipseclog((LOG_DEBUG, "ipsec_init_policy: No more memory.\n"));
		return ENOBUFS;
	}
	bzero(new, sizeof(*new));

#ifdef __APPLE__
	if (kauth_cred_issuser(so->so_cred))
#else
	if (so->so_cred != 0 && !suser(so->so_cred->pc_ucred, NULL))
#endif
	{ new->priv = 1;} else {
		new->priv = 0;
	}

	if ((new->sp_in = key_newsp()) == NULL) {
		ipsec_delpcbpolicy(new);
		return ENOBUFS;
	}
	new->sp_in->state = IPSEC_SPSTATE_ALIVE;
	new->sp_in->policy = IPSEC_POLICY_ENTRUST;

	if ((new->sp_out = key_newsp()) == NULL) {
		key_freesp(new->sp_in, KEY_SADB_UNLOCKED);
		ipsec_delpcbpolicy(new);
		return ENOBUFS;
	}
	new->sp_out->state = IPSEC_SPSTATE_ALIVE;
	new->sp_out->policy = IPSEC_POLICY_ENTRUST;

	*pcb_sp = new;

	return 0;
}

/* copy old ipsec policy into new */
int
ipsec_copy_policy(struct inpcbpolicy *old,
    struct inpcbpolicy *new)
{
	struct secpolicy *sp;

	if (ipsec_bypass != 0) {
		return 0;
	}

	sp = ipsec_deepcopy_policy(old->sp_in);
	if (sp) {
		key_freesp(new->sp_in, KEY_SADB_UNLOCKED);
		new->sp_in = sp;
	} else {
		return ENOBUFS;
	}

	sp = ipsec_deepcopy_policy(old->sp_out);
	if (sp) {
		key_freesp(new->sp_out, KEY_SADB_UNLOCKED);
		new->sp_out = sp;
	} else {
		return ENOBUFS;
	}

	new->priv = old->priv;

	return 0;
}

/* deep-copy a policy in PCB */
static struct secpolicy *
ipsec_deepcopy_policy(struct secpolicy *src)
{
	struct ipsecrequest *newchain = NULL;
	struct ipsecrequest *p;
	struct ipsecrequest **q;
	struct ipsecrequest *r;
	struct secpolicy *dst;

	if (src == NULL) {
		return NULL;
	}
	dst = key_newsp();
	if (dst == NULL) {
		return NULL;
	}

	/*
	 * deep-copy IPsec request chain.  This is required since struct
	 * ipsecrequest is not reference counted.
	 */
	q = &newchain;
	for (p = src->req; p; p = p->next) {
		*q = (struct ipsecrequest *)_MALLOC(sizeof(struct ipsecrequest),
		    M_SECA, M_WAITOK | M_ZERO);
		if (*q == NULL) {
			goto fail;
		}
		(*q)->next = NULL;

		(*q)->saidx.proto = p->saidx.proto;
		(*q)->saidx.mode = p->saidx.mode;
		(*q)->level = p->level;
		(*q)->saidx.reqid = p->saidx.reqid;

		bcopy(&p->saidx.src, &(*q)->saidx.src, sizeof((*q)->saidx.src));
		bcopy(&p->saidx.dst, &(*q)->saidx.dst, sizeof((*q)->saidx.dst));

		(*q)->sp = dst;

		q = &((*q)->next);
	}

	dst->req = newchain;
	dst->state = src->state;
	dst->policy = src->policy;
	/* do not touch the refcnt fields */

	return dst;

fail:
	for (p = newchain; p; p = r) {
		r = p->next;
		FREE(p, M_SECA);
		p = NULL;
	}
	key_freesp(dst, KEY_SADB_UNLOCKED);
	return NULL;
}

/* set policy and ipsec request if present. */
static int
ipsec_set_policy(struct secpolicy **pcb_sp,
    __unused int optname,
    caddr_t request,
    size_t len,
    int priv)
{
	struct sadb_x_policy *xpl;
	struct secpolicy *newsp = NULL;
	int error;

	/* sanity check. */
	if (pcb_sp == NULL || *pcb_sp == NULL || request == NULL) {
		return EINVAL;
	}
	if (len < sizeof(*xpl)) {
		return EINVAL;
	}
	xpl = (struct sadb_x_policy *)(void *)request;

	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
	    printf("ipsec_set_policy: passed policy\n");
	    kdebug_sadb_x_policy((struct sadb_ext *)xpl));

	/* check policy type */
	/* ipsec_set_policy() accepts IPSEC, ENTRUST and BYPASS. */
	if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD
	    || xpl->sadb_x_policy_type == IPSEC_POLICY_NONE) {
		return EINVAL;
	}

	/* check privileged socket */
	if (priv == 0 && xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
		return EACCES;
	}

	/* allocation new SP entry */
	if ((newsp = key_msg2sp(xpl, len, &error)) == NULL) {
		return error;
	}

	newsp->state = IPSEC_SPSTATE_ALIVE;

	/* clear old SP and set new SP */
	key_freesp(*pcb_sp, KEY_SADB_UNLOCKED);
	*pcb_sp = newsp;
	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
	    printf("ipsec_set_policy: new policy\n");
	    kdebug_secpolicy(newsp));

	return 0;
}

int
ipsec4_set_policy(struct inpcb *inp,
    int optname,
    caddr_t request,
    size_t len,
    int priv)
{
	struct sadb_x_policy *xpl;
	struct secpolicy **pcb_sp;
	int     error = 0;
	struct sadb_x_policy xpl_aligned_buf;
	u_int8_t             *xpl_unaligned;

	/* sanity check. */
	if (inp == NULL || request == NULL) {
		return EINVAL;
	}
	if (len < sizeof(*xpl)) {
		return EINVAL;
	}
	xpl = (struct sadb_x_policy *)(void *)request;

	/* This is a new mbuf allocated by soopt_getm() */
	if (IPSEC_IS_P2ALIGNED(xpl)) {
		xpl_unaligned = NULL;
	} else {
		xpl_unaligned = (__typeof__(xpl_unaligned))xpl;
		memcpy(&xpl_aligned_buf, xpl, sizeof(xpl_aligned_buf));
		xpl = (__typeof__(xpl)) & xpl_aligned_buf;
	}

	if (inp->inp_sp == NULL) {
		error = ipsec_init_policy(inp->inp_socket, &inp->inp_sp);
		if (error) {
			return error;
		}
	}

	/* select direction */
	switch (xpl->sadb_x_policy_dir) {
	case IPSEC_DIR_INBOUND:
		pcb_sp = &inp->inp_sp->sp_in;
		break;
	case IPSEC_DIR_OUTBOUND:
		pcb_sp = &inp->inp_sp->sp_out;
		break;
	default:
		ipseclog((LOG_ERR, "ipsec4_set_policy: invalid direction=%u\n",
		    xpl->sadb_x_policy_dir));
		return EINVAL;
	}

	/* turn bypass off */
	if (ipsec_bypass != 0) {
		ipsec_bypass = 0;
	}

	return ipsec_set_policy(pcb_sp, optname, request, len, priv);
}

/* delete policy in PCB */
int
ipsec4_delete_pcbpolicy(struct inpcb *inp)
{
	/* sanity check. */
	if (inp == NULL) {
		panic("ipsec4_delete_pcbpolicy: NULL pointer was passed.\n");
	}

	if (inp->inp_sp == NULL) {
		return 0;
	}

	if (inp->inp_sp->sp_in != NULL) {
		key_freesp(inp->inp_sp->sp_in, KEY_SADB_UNLOCKED);
		inp->inp_sp->sp_in = NULL;
	}

	if (inp->inp_sp->sp_out != NULL) {
		key_freesp(inp->inp_sp->sp_out, KEY_SADB_UNLOCKED);
		inp->inp_sp->sp_out = NULL;
	}

	ipsec_delpcbpolicy(inp->inp_sp);
	inp->inp_sp = NULL;

	return 0;
}

int
ipsec6_set_policy(struct in6pcb *in6p,
    int optname,
    caddr_t request,
    size_t len,
    int priv)
{
	struct sadb_x_policy *xpl;
	struct secpolicy **pcb_sp;
	int error = 0;
	struct sadb_x_policy xpl_aligned_buf;
	u_int8_t *xpl_unaligned;

	/* sanity check. */
	if (in6p == NULL || request == NULL) {
		return EINVAL;
	}
	if (len < sizeof(*xpl)) {
		return EINVAL;
	}
	xpl = (struct sadb_x_policy *)(void *)request;

	/* This is a new mbuf allocated by soopt_getm() */
	if (IPSEC_IS_P2ALIGNED(xpl)) {
		xpl_unaligned = NULL;
	} else {
		xpl_unaligned = (__typeof__(xpl_unaligned))xpl;
		memcpy(&xpl_aligned_buf, xpl, sizeof(xpl_aligned_buf));
		xpl = (__typeof__(xpl)) & xpl_aligned_buf;
	}

	if (in6p->in6p_sp == NULL) {
		error = ipsec_init_policy(in6p->inp_socket, &in6p->in6p_sp);
		if (error) {
			return error;
		}
	}

	/* select direction */
	switch (xpl->sadb_x_policy_dir) {
	case IPSEC_DIR_INBOUND:
		pcb_sp = &in6p->in6p_sp->sp_in;
		break;
	case IPSEC_DIR_OUTBOUND:
		pcb_sp = &in6p->in6p_sp->sp_out;
		break;
	default:
		ipseclog((LOG_ERR, "ipsec6_set_policy: invalid direction=%u\n",
		    xpl->sadb_x_policy_dir));
		return EINVAL;
	}

	return ipsec_set_policy(pcb_sp, optname, request, len, priv);
}

int
ipsec6_delete_pcbpolicy(struct in6pcb *in6p)
{
	/* sanity check. */
	if (in6p == NULL) {
		panic("ipsec6_delete_pcbpolicy: NULL pointer was passed.\n");
	}

	if (in6p->in6p_sp == NULL) {
		return 0;
	}

	if (in6p->in6p_sp->sp_in != NULL) {
		key_freesp(in6p->in6p_sp->sp_in, KEY_SADB_UNLOCKED);
		in6p->in6p_sp->sp_in = NULL;
	}

	if (in6p->in6p_sp->sp_out != NULL) {
		key_freesp(in6p->in6p_sp->sp_out, KEY_SADB_UNLOCKED);
		in6p->in6p_sp->sp_out = NULL;
	}

	ipsec_delpcbpolicy(in6p->in6p_sp);
	in6p->in6p_sp = NULL;

	return 0;
}

/*
 * return current level.
 * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
 */
u_int
ipsec_get_reqlevel(struct ipsecrequest *isr)
{
	u_int level = 0;
	u_int esp_trans_deflev = 0, esp_net_deflev = 0, ah_trans_deflev = 0, ah_net_deflev = 0;

	/* sanity check */
	if (isr == NULL || isr->sp == NULL) {
		panic("ipsec_get_reqlevel: NULL pointer is passed.\n");
	}
	if (((struct sockaddr *)&isr->sp->spidx.src)->sa_family
	    != ((struct sockaddr *)&isr->sp->spidx.dst)->sa_family) {
		panic("ipsec_get_reqlevel: family mismatched.\n");
	}

/* XXX note that we have ipseclog() expanded here - code sync issue */
#define IPSEC_CHECK_DEFAULT(lev) \
	(((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE            \
	                && (lev) != IPSEC_LEVEL_UNIQUE)                       \
	        ? (ipsec_debug                                                \
	                ? log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
	                        (lev), IPSEC_LEVEL_REQUIRE)                   \
	                : (void)0),                                                                       \
	                (lev) = IPSEC_LEVEL_REQUIRE,                          \
	                (lev)                                                 \
	        : (lev))

	/* set default level */
	switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
	case AF_INET:
		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_trans_deflev);
		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_net_deflev);
		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_trans_deflev);
		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_net_deflev);
		break;
	case AF_INET6:
		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_trans_deflev);
		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_net_deflev);
		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_trans_deflev);
		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_net_deflev);
		break;
	default:
		panic("key_get_reqlevel: Unknown family. %d\n",
		    ((struct sockaddr *)&isr->sp->spidx.src)->sa_family);
	}

#undef IPSEC_CHECK_DEFAULT

	/* set level */
	switch (isr->level) {
	case IPSEC_LEVEL_DEFAULT:
		switch (isr->saidx.proto) {
		case IPPROTO_ESP:
			if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
				level = esp_net_deflev;
			} else {
				level = esp_trans_deflev;
			}
			break;
		case IPPROTO_AH:
			if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
				level = ah_net_deflev;
			} else {
				level = ah_trans_deflev;
			}
			break;
		case IPPROTO_IPCOMP:
			ipseclog((LOG_ERR, "ipsec_get_reqlevel: "
			    "still got IPCOMP - exiting\n"));
			break;
		default:
			panic("ipsec_get_reqlevel: "
			    "Illegal protocol defined %u\n",
			    isr->saidx.proto);
		}
		break;

	case IPSEC_LEVEL_USE:
	case IPSEC_LEVEL_REQUIRE:
		level = isr->level;
		break;
	case IPSEC_LEVEL_UNIQUE:
		level = IPSEC_LEVEL_REQUIRE;
		break;

	default:
		panic("ipsec_get_reqlevel: Illegal IPsec level %u\n",
		    isr->level);
	}

	return level;
}

/*
 * Check AH/ESP integrity.
 * OUT:
 *	0: valid
 *	1: invalid
 */
static int
ipsec_in_reject(struct secpolicy *sp, struct mbuf *m)
{
	struct ipsecrequest *isr;
	u_int level;
	int need_auth, need_conf, need_icv;

	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
	    printf("ipsec_in_reject: using SP\n");
	    kdebug_secpolicy(sp));

	/* check policy */
	switch (sp->policy) {
	case IPSEC_POLICY_DISCARD:
	case IPSEC_POLICY_GENERATE:
		return 1;
	case IPSEC_POLICY_BYPASS:
	case IPSEC_POLICY_NONE:
		return 0;

	case IPSEC_POLICY_IPSEC:
		break;

	case IPSEC_POLICY_ENTRUST:
	default:
		panic("ipsec_hdrsiz: Invalid policy found. %d\n", sp->policy);
	}

	need_auth = 0;
	need_conf = 0;
	need_icv = 0;

	/* XXX should compare policy against ipsec header history */

	for (isr = sp->req; isr != NULL; isr = isr->next) {
		/* get current level */
		level = ipsec_get_reqlevel(isr);

		switch (isr->saidx.proto) {
		case IPPROTO_ESP:
			if (level == IPSEC_LEVEL_REQUIRE) {
				need_conf++;

#if 0
				/* this won't work with multiple input threads - isr->sav would change
				 * with every packet and is not necessarily related to the current packet
				 * being processed.  If ESP processing is required - the esp code should
				 * make sure that the integrity check is present and correct.  I don't see
				 * why it would be necessary to check for the presence of the integrity
				 * check value here.  I think this is just wrong.
				 * isr->sav has been removed.
				 * %%%%%% this needs to be re-worked at some point but I think the code below can
				 * be ignored for now.
				 */
				if (isr->sav != NULL
				    && isr->sav->flags == SADB_X_EXT_NONE
				    && isr->sav->alg_auth != SADB_AALG_NONE) {
					need_icv++;
				}
#endif
			}
			break;
		case IPPROTO_AH:
			if (level == IPSEC_LEVEL_REQUIRE) {
				need_auth++;
				need_icv++;
			}
			break;
		case IPPROTO_IPCOMP:
			/*
			 * we don't really care, as IPcomp document says that
			 * we shouldn't compress small packets, IPComp policy
			 * should always be treated as being in "use" level.
			 */
			break;
		}
	}

	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
	    printf("ipsec_in_reject: auth:%d conf:%d icv:%d m_flags:%x\n",
	    need_auth, need_conf, need_icv, m->m_flags));

	if ((need_conf && !(m->m_flags & M_DECRYPTED))
	    || (!need_auth && need_icv && !(m->m_flags & M_AUTHIPDGM))
	    || (need_auth && !(m->m_flags & M_AUTHIPHDR))) {
		return 1;
	}

	return 0;
}

/*
 * Check AH/ESP integrity.
 * This function is called from tcp_input(), udp_input(),
 * and {ah,esp}4_input for tunnel mode
 */
int
ipsec4_in_reject_so(struct mbuf *m, struct socket *so)
{
	struct secpolicy *sp = NULL;
	int error;
	int result;

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
	/* sanity check */
	if (m == NULL) {
		return 0;       /* XXX should be panic ? */
	}
	/* get SP for this packet.
	 * When we are called from ip_forward(), we call
	 * ipsec4_getpolicybyaddr() with IP_FORWARDING flag.
	 */
	if (so == NULL) {
		sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
	} else {
		sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_INBOUND, 0, &error);
	}

	if (sp == NULL) {
		return 0;       /* XXX should be panic ?
		                 * -> No, there may be error. */
	}
	result = ipsec_in_reject(sp, m);
	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
	    printf("DP ipsec4_in_reject_so call free SP:0x%llx\n",
	    (uint64_t)VM_KERNEL_ADDRPERM(sp)));
	key_freesp(sp, KEY_SADB_UNLOCKED);

	return result;
}

int
ipsec4_in_reject(struct mbuf *m, struct inpcb *inp)
{
	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
	if (inp == NULL) {
		return ipsec4_in_reject_so(m, NULL);
	}
	if (inp->inp_socket) {
		return ipsec4_in_reject_so(m, inp->inp_socket);
	} else {
		panic("ipsec4_in_reject: invalid inpcb/socket");
	}

	/* NOTREACHED */
	return 0;
}

/*
 * Check AH/ESP integrity.
 * This function is called from tcp6_input(), udp6_input(),
 * and {ah,esp}6_input for tunnel mode
 */
int
ipsec6_in_reject_so(struct mbuf *m, struct socket *so)
{
	struct secpolicy *sp = NULL;
	int error;
	int result;

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
	/* sanity check */
	if (m == NULL) {
		return 0;       /* XXX should be panic ? */
	}
	/* get SP for this packet.
	 * When we are called from ip_forward(), we call
	 * ipsec6_getpolicybyaddr() with IP_FORWARDING flag.
	 */
	if (so == NULL) {
		sp = ipsec6_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
	} else {
		sp = ipsec6_getpolicybyaddr(m, IPSEC_DIR_INBOUND, 0, &error);
	}

	if (sp == NULL) {
		return 0;       /* XXX should be panic ? */
	}
	result = ipsec_in_reject(sp, m);
	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
	    printf("DP ipsec6_in_reject_so call free SP:0x%llx\n",
	    (uint64_t)VM_KERNEL_ADDRPERM(sp)));
	key_freesp(sp, KEY_SADB_UNLOCKED);

	return result;
}

int
ipsec6_in_reject(struct mbuf *m, struct in6pcb *in6p)
{
	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
	if (in6p == NULL) {
		return ipsec6_in_reject_so(m, NULL);
	}
	if (in6p->in6p_socket) {
		return ipsec6_in_reject_so(m, in6p->in6p_socket);
	} else {
		panic("ipsec6_in_reject: invalid in6p/socket");
	}

	/* NOTREACHED */
	return 0;
}

/*
 * compute the byte size to be occupied by IPsec header.
 * in case it is tunneled, it includes the size of outer IP header.
 * NOTE: SP passed is free in this function.
 */
size_t
ipsec_hdrsiz(struct secpolicy *sp)
{
	struct ipsecrequest *isr;
	size_t siz, clen;

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
	    printf("ipsec_hdrsiz: using SP\n");
	    kdebug_secpolicy(sp));

	/* check policy */
	switch (sp->policy) {
	case IPSEC_POLICY_DISCARD:
	case IPSEC_POLICY_GENERATE:
	case IPSEC_POLICY_BYPASS:
	case IPSEC_POLICY_NONE:
		return 0;

	case IPSEC_POLICY_IPSEC:
		break;

	case IPSEC_POLICY_ENTRUST:
	default:
		panic("ipsec_hdrsiz: Invalid policy found. %d\n", sp->policy);
	}

	siz = 0;

	for (isr = sp->req; isr != NULL; isr = isr->next) {
		clen = 0;

		switch (isr->saidx.proto) {
		case IPPROTO_ESP:
#if IPSEC_ESP
			clen = esp_hdrsiz(isr);
#else
			clen = 0;       /*XXX*/
#endif
			break;
		case IPPROTO_AH:
			clen = ah_hdrsiz(isr);
			break;
		default:
			ipseclog((LOG_ERR, "ipsec_hdrsiz: "
			    "unknown protocol %u\n",
			    isr->saidx.proto));
			break;
		}

		if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
			switch (((struct sockaddr *)&isr->saidx.dst)->sa_family) {
			case AF_INET:
				clen += sizeof(struct ip);
				break;
			case AF_INET6:
				clen += sizeof(struct ip6_hdr);
				break;
			default:
				ipseclog((LOG_ERR, "ipsec_hdrsiz: "
				    "unknown AF %d in IPsec tunnel SA\n",
				    ((struct sockaddr *)&isr->saidx.dst)->sa_family));
				break;
			}
		}
		siz += clen;
	}

	return siz;
}

/* This function is called from ip_forward() and ipsec4_hdrsize_tcp(). */
size_t
ipsec4_hdrsiz(struct mbuf *m, u_int8_t dir, struct inpcb *inp)
{
	struct secpolicy *sp = NULL;
	int error;
	size_t size;

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
	/* sanity check */
	if (m == NULL) {
		return 0;       /* XXX should be panic ? */
	}
	if (inp != NULL && inp->inp_socket == NULL) {
		panic("ipsec4_hdrsize: why is socket NULL but there is PCB.");
	}

	/* get SP for this packet.
	 * When we are called from ip_forward(), we call
	 * ipsec4_getpolicybyaddr() with IP_FORWARDING flag.
	 */
	if (inp == NULL) {
		sp = ipsec4_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
	} else {
		sp = ipsec4_getpolicybyaddr(m, dir, 0, &error);
	}

	if (sp == NULL) {
		return 0;       /* XXX should be panic ? */
	}
	size = ipsec_hdrsiz(sp);
	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
	    printf("DP ipsec4_hdrsiz call free SP:0x%llx\n",
	    (uint64_t)VM_KERNEL_ADDRPERM(sp)));
	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
	    printf("ipsec4_hdrsiz: size:%lu.\n", (u_int32_t)size));
	key_freesp(sp, KEY_SADB_UNLOCKED);

	return size;
}

/* This function is called from ipsec6_hdrsize_tcp(),
 * and maybe from ip6_forward.()
 */
size_t
ipsec6_hdrsiz(struct mbuf *m, u_int8_t dir, struct in6pcb *in6p)
{
	struct secpolicy *sp = NULL;
	int error;
	size_t size;

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
	/* sanity check */
	if (m == NULL) {
		return 0;       /* XXX shoud be panic ? */
	}
	if (in6p != NULL && in6p->in6p_socket == NULL) {
		panic("ipsec6_hdrsize: why is socket NULL but there is PCB.");
	}

	/* get SP for this packet */
	/* XXX Is it right to call with IP_FORWARDING. */
	if (in6p == NULL) {
		sp = ipsec6_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
	} else {
		sp = ipsec6_getpolicybyaddr(m, dir, 0, &error);
	}

	if (sp == NULL) {
		return 0;
	}
	size = ipsec_hdrsiz(sp);
	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
	    printf("DP ipsec6_hdrsiz call free SP:0x%llx\n",
	    (uint64_t)VM_KERNEL_ADDRPERM(sp)));
	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
	    printf("ipsec6_hdrsiz: size:%lu.\n", (u_int32_t)size));
	key_freesp(sp, KEY_SADB_UNLOCKED);

	return size;
}

/*
 * encapsulate for ipsec tunnel.
 * ip->ip_src must be fixed later on.
 */
int
ipsec4_encapsulate(struct mbuf *m, struct secasvar *sav)
{
	struct ip *oip;
	struct ip *ip;
	size_t plen;
	u_int32_t hlen;

	/* can't tunnel between different AFs */
	if (((struct sockaddr *)&sav->sah->saidx.src)->sa_family
	    != ((struct sockaddr *)&sav->sah->saidx.dst)->sa_family
	    || ((struct sockaddr *)&sav->sah->saidx.src)->sa_family != AF_INET) {
		m_freem(m);
		return EINVAL;
	}

	if (m->m_len < sizeof(*ip)) {
		panic("ipsec4_encapsulate: assumption failed (first mbuf length)");
	}

	ip = mtod(m, struct ip *);
#ifdef _IP_VHL
	hlen = _IP_VHL_HL(ip->ip_vhl) << 2;
#else
	hlen = ip->ip_hl << 2;
#endif

	if (m->m_len != hlen) {
		panic("ipsec4_encapsulate: assumption failed (first mbuf length)");
	}

	/* generate header checksum */
	ip->ip_sum = 0;
#ifdef _IP_VHL
	ip->ip_sum = in_cksum(m, hlen);
#else
	ip->ip_sum = in_cksum(m, hlen);
#endif

	plen = m->m_pkthdr.len;

	/*
	 * grow the mbuf to accomodate the new IPv4 header.
	 * NOTE: IPv4 options will never be copied.
	 */
	if (M_LEADINGSPACE(m->m_next) < hlen) {
		struct mbuf *n;
		MGET(n, M_DONTWAIT, MT_DATA);
		if (!n) {
			m_freem(m);
			return ENOBUFS;
		}
		n->m_len = hlen;
		n->m_next = m->m_next;
		m->m_next = n;
		m->m_pkthdr.len += hlen;
		oip = mtod(n, struct ip *);
	} else {
		m->m_next->m_len += hlen;
		m->m_next->m_data -= hlen;
		m->m_pkthdr.len += hlen;
		oip = mtod(m->m_next, struct ip *);
	}
	ip = mtod(m, struct ip *);
	ovbcopy((caddr_t)ip, (caddr_t)oip, hlen);
	m->m_len = sizeof(struct ip);
	m->m_pkthdr.len -= (hlen - sizeof(struct ip));

	/* construct new IPv4 header. see RFC 2401 5.1.2.1 */
	/* ECN consideration. */
	ip_ecn_ingress(ip4_ipsec_ecn, &ip->ip_tos, &oip->ip_tos);
#ifdef _IP_VHL
	ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
#else
	ip->ip_hl = sizeof(struct ip) >> 2;
#endif
	ip->ip_off &= htons(~IP_OFFMASK);
	ip->ip_off &= htons(~IP_MF);
	switch (ip4_ipsec_dfbit) {
	case 0: /* clear DF bit */
		ip->ip_off &= htons(~IP_DF);
		break;
	case 1: /* set DF bit */
		ip->ip_off |= htons(IP_DF);
		break;
	default:        /* copy DF bit */
		break;
	}
	ip->ip_p = IPPROTO_IPIP;
	if (plen + sizeof(struct ip) < IP_MAXPACKET) {
		ip->ip_len = htons((u_int16_t)(plen + sizeof(struct ip)));
	} else {
		ipseclog((LOG_ERR, "IPv4 ipsec: size exceeds limit: "
		    "leave ip_len as is (invalid packet)\n"));
	}
	if (rfc6864 && IP_OFF_IS_ATOMIC(ntohs(ip->ip_off))) {
		ip->ip_id = 0;
	} else {
		ip->ip_id = ip_randomid();
	}
	bcopy(&((struct sockaddr_in *)&sav->sah->saidx.src)->sin_addr,
	    &ip->ip_src, sizeof(ip->ip_src));
	bcopy(&((struct sockaddr_in *)&sav->sah->saidx.dst)->sin_addr,
	    &ip->ip_dst, sizeof(ip->ip_dst));
	ip->ip_ttl = IPDEFTTL;

	/* XXX Should ip_src be updated later ? */

	return 0;
}


int
ipsec6_encapsulate(struct mbuf *m, struct secasvar *sav)
{
	struct ip6_hdr *oip6;
	struct ip6_hdr *ip6;
	size_t plen;

	/* can't tunnel between different AFs */
	if (((struct sockaddr *)&sav->sah->saidx.src)->sa_family
	    != ((struct sockaddr *)&sav->sah->saidx.dst)->sa_family
	    || ((struct sockaddr *)&sav->sah->saidx.src)->sa_family != AF_INET6) {
		m_freem(m);
		return EINVAL;
	}

	plen = m->m_pkthdr.len;

	/*
	 * grow the mbuf to accomodate the new IPv6 header.
	 */
	if (m->m_len != sizeof(struct ip6_hdr)) {
		panic("ipsec6_encapsulate: assumption failed (first mbuf length)");
	}
	if (M_LEADINGSPACE(m->m_next) < sizeof(struct ip6_hdr)) {
		struct mbuf *n;
		MGET(n, M_DONTWAIT, MT_DATA);
		if (!n) {
			m_freem(m);
			return ENOBUFS;
		}
		n->m_len = sizeof(struct ip6_hdr);
		n->m_next = m->m_next;
		m->m_next = n;
		m->m_pkthdr.len += sizeof(struct ip6_hdr);
		oip6 = mtod(n, struct ip6_hdr *);
	} else {
		m->m_next->m_len += sizeof(struct ip6_hdr);
		m->m_next->m_data -= sizeof(struct ip6_hdr);
		m->m_pkthdr.len += sizeof(struct ip6_hdr);
		oip6 = mtod(m->m_next, struct ip6_hdr *);
	}
	ip6 = mtod(m, struct ip6_hdr *);
	ovbcopy((caddr_t)ip6, (caddr_t)oip6, sizeof(struct ip6_hdr));

	/* Fake link-local scope-class addresses */
	if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_src)) {
		oip6->ip6_src.s6_addr16[1] = 0;
	}
	if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_dst)) {
		oip6->ip6_dst.s6_addr16[1] = 0;
	}

	/* construct new IPv6 header. see RFC 2401 5.1.2.2 */
	/* ECN consideration. */
	ip6_ecn_ingress(ip6_ipsec_ecn, &ip6->ip6_flow, &oip6->ip6_flow);
	if (plen < IPV6_MAXPACKET - sizeof(struct ip6_hdr)) {
		ip6->ip6_plen = htons((u_int16_t)plen);
	} else {
		/* ip6->ip6_plen will be updated in ip6_output() */
	}
	ip6->ip6_nxt = IPPROTO_IPV6;
	bcopy(&((struct sockaddr_in6 *)&sav->sah->saidx.src)->sin6_addr,
	    &ip6->ip6_src, sizeof(ip6->ip6_src));
	bcopy(&((struct sockaddr_in6 *)&sav->sah->saidx.dst)->sin6_addr,
	    &ip6->ip6_dst, sizeof(ip6->ip6_dst));
	ip6->ip6_hlim = IPV6_DEFHLIM;

	/* XXX Should ip6_src be updated later ? */

	return 0;
}

static int
ipsec64_encapsulate(struct mbuf *m, struct secasvar *sav)
{
	struct ip6_hdr *ip6, *ip6i;
	struct ip *ip;
	size_t plen;
	u_int8_t hlim;

	/* tunneling over IPv4 */
	if (((struct sockaddr *)&sav->sah->saidx.src)->sa_family
	    != ((struct sockaddr *)&sav->sah->saidx.dst)->sa_family
	    || ((struct sockaddr *)&sav->sah->saidx.src)->sa_family != AF_INET) {
		m_freem(m);
		return EINVAL;
	}

	plen = m->m_pkthdr.len;
	ip6 = mtod(m, struct ip6_hdr *);
	hlim = ip6->ip6_hlim;
	/*
	 * grow the mbuf to accomodate the new IPv4 header.
	 */
	if (m->m_len != sizeof(struct ip6_hdr)) {
		panic("ipsec6_encapsulate: assumption failed (first mbuf length)");
	}
	if (M_LEADINGSPACE(m->m_next) < sizeof(struct ip6_hdr)) {
		struct mbuf *n;
		MGET(n, M_DONTWAIT, MT_DATA);
		if (!n) {
			m_freem(m);
			return ENOBUFS;
		}
		n->m_len = sizeof(struct ip6_hdr);
		n->m_next = m->m_next;
		m->m_next = n;
		m->m_pkthdr.len += sizeof(struct ip);
		ip6i = mtod(n, struct ip6_hdr *);
	} else {
		m->m_next->m_len += sizeof(struct ip6_hdr);
		m->m_next->m_data -= sizeof(struct ip6_hdr);
		m->m_pkthdr.len += sizeof(struct ip);
		ip6i = mtod(m->m_next, struct ip6_hdr *);
	}

	bcopy(ip6, ip6i, sizeof(struct ip6_hdr));
	ip = mtod(m, struct ip *);
	m->m_len = sizeof(struct ip);
	/*
	 * Fill in some of the IPv4 fields - we don't need all of them
	 * because the rest will be filled in by ip_output
	 */
	ip->ip_v = IPVERSION;
	ip->ip_hl = sizeof(struct ip) >> 2;
	ip->ip_id = 0;
	ip->ip_sum = 0;
	ip->ip_tos = 0;
	ip->ip_off = 0;
	ip->ip_ttl = hlim;
	ip->ip_p = IPPROTO_IPV6;

	/* construct new IPv4 header. see RFC 2401 5.1.2.1 */
	/* ECN consideration. */
	ip64_ecn_ingress(ip4_ipsec_ecn, &ip->ip_tos, &ip6->ip6_flow);

	if (plen + sizeof(struct ip) < IP_MAXPACKET) {
		ip->ip_len = htons((u_int16_t)(plen + sizeof(struct ip)));
	} else {
		ip->ip_len = htons((u_int16_t)plen);
		ipseclog((LOG_ERR, "IPv4 ipsec: size exceeds limit: "
		    "leave ip_len as is (invalid packet)\n"));
	}
	bcopy(&((struct sockaddr_in *)&sav->sah->saidx.src)->sin_addr,
	    &ip->ip_src, sizeof(ip->ip_src));
	bcopy(&((struct sockaddr_in *)&sav->sah->saidx.dst)->sin_addr,
	    &ip->ip_dst, sizeof(ip->ip_dst));

	return 0;
}

int
ipsec6_update_routecache_and_output(
	struct ipsec_output_state *state,
	struct secasvar *sav)
{
	struct sockaddr_in6* dst6;
	struct route_in6 *ro6;
	struct ip6_hdr *ip6;
	errno_t error = 0;

	int plen;
	struct ip6_out_args ip6oa;
	struct route_in6 ro6_new;
	struct flowadv *adv = NULL;

	if (!state->m) {
		return EINVAL;
	}
	ip6 = mtod(state->m, struct ip6_hdr *);

	// grab sadb_mutex, before updating sah's route cache
	lck_mtx_lock(sadb_mutex);
	ro6 = &sav->sah->sa_route;
	dst6 = (struct sockaddr_in6 *)(void *)&ro6->ro_dst;
	if (ro6->ro_rt) {
		RT_LOCK(ro6->ro_rt);
	}
	if (ROUTE_UNUSABLE(ro6) ||
	    !IN6_ARE_ADDR_EQUAL(&dst6->sin6_addr, &ip6->ip6_dst)) {
		if (ro6->ro_rt != NULL) {
			RT_UNLOCK(ro6->ro_rt);
		}
		ROUTE_RELEASE(ro6);
	}
	if (ro6->ro_rt == 0) {
		bzero(dst6, sizeof(*dst6));
		dst6->sin6_family = AF_INET6;
		dst6->sin6_len = sizeof(*dst6);
		dst6->sin6_addr = ip6->ip6_dst;
		rtalloc_scoped((struct route *)ro6, sav->sah->outgoing_if);
		if (ro6->ro_rt) {
			RT_LOCK(ro6->ro_rt);
		}
	}
	if (ro6->ro_rt == 0) {
		ip6stat.ip6s_noroute++;
		IPSEC_STAT_INCREMENT(ipsec6stat.out_noroute);
		error = EHOSTUNREACH;
		// release sadb_mutex, after updating sah's route cache
		lck_mtx_unlock(sadb_mutex);
		return error;
	}

	/*
	 * adjust state->dst if tunnel endpoint is offlink
	 *
	 * XXX: caching rt_gateway value in the state is
	 * not really good, since it may point elsewhere
	 * when the gateway gets modified to a larger
	 * sockaddr via rt_setgate().  This is currently
	 * addressed by SA_SIZE roundup in that routine.
	 */
	if (ro6->ro_rt->rt_flags & RTF_GATEWAY) {
		dst6 = (struct sockaddr_in6 *)(void *)ro6->ro_rt->rt_gateway;
	}
	RT_UNLOCK(ro6->ro_rt);
	ROUTE_RELEASE(&state->ro);
	route_copyout((struct route *)&state->ro, (struct route *)ro6, sizeof(struct route_in6));
	state->dst = (struct sockaddr *)dst6;
	state->tunneled = 6;
	// release sadb_mutex, after updating sah's route cache
	lck_mtx_unlock(sadb_mutex);

	state->m = ipsec6_splithdr(state->m);
	if (!state->m) {
		IPSEC_STAT_INCREMENT(ipsec6stat.out_nomem);
		error = ENOMEM;
		return error;
	}

	ip6 = mtod(state->m, struct ip6_hdr *);
	switch (sav->sah->saidx.proto) {
	case IPPROTO_ESP:
#if IPSEC_ESP
		error = esp6_output(state->m, &ip6->ip6_nxt, state->m->m_next, sav);
#else
		m_freem(state->m);
		error = EINVAL;
#endif
		break;
	case IPPROTO_AH:
		error = ah6_output(state->m, &ip6->ip6_nxt, state->m->m_next, sav);
		break;
	default:
		ipseclog((LOG_ERR, "%s: unknown ipsec protocol %d\n", __FUNCTION__, sav->sah->saidx.proto));
		m_freem(state->m);
		IPSEC_STAT_INCREMENT(ipsec6stat.out_inval);
		error = EINVAL;
		break;
	}
	if (error) {
		// If error, packet already freed by above output routines
		state->m = NULL;
		return error;
	}

	plen = state->m->m_pkthdr.len - sizeof(struct ip6_hdr);
	if (plen > IPV6_MAXPACKET) {
		ipseclog((LOG_ERR, "%s: IPsec with IPv6 jumbogram is not supported\n", __FUNCTION__));
		IPSEC_STAT_INCREMENT(ipsec6stat.out_inval);
		error = EINVAL;/*XXX*/
		return error;
	}
	ip6 = mtod(state->m, struct ip6_hdr *);
	ip6->ip6_plen = htons((u_int16_t)plen);

	ipsec_set_pkthdr_for_interface(sav->sah->ipsec_if, state->m, AF_INET6);
	ipsec_set_ip6oa_for_interface(sav->sah->ipsec_if, &ip6oa);

	/* Increment statistics */
	ifnet_stat_increment_out(sav->sah->ipsec_if, 1, (u_int32_t)mbuf_pkthdr_len(state->m), 0);

	/* Send to ip6_output */
	bzero(&ro6_new, sizeof(ro6_new));
	bzero(&ip6oa, sizeof(ip6oa));
	ip6oa.ip6oa_flowadv.code = 0;
	ip6oa.ip6oa_flags = IP6OAF_SELECT_SRCIF | IP6OAF_BOUND_SRCADDR;
	if (state->outgoing_if) {
		ip6oa.ip6oa_boundif = state->outgoing_if;
		ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
	}

	adv = &ip6oa.ip6oa_flowadv;
	(void) ip6_output(state->m, NULL, &ro6_new, IPV6_OUTARGS, NULL, NULL, &ip6oa);
	state->m = NULL;

	if (adv->code == FADV_FLOW_CONTROLLED || adv->code == FADV_SUSPENDED) {
		error = ENOBUFS;
		ifnet_disable_output(sav->sah->ipsec_if);
		return error;
	}

	return 0;
}

int
ipsec46_encapsulate(struct ipsec_output_state *state, struct secasvar *sav)
{
	struct mbuf *m;
	struct ip6_hdr *ip6;
	struct ip *oip;
	struct ip *ip;
	size_t plen;
	u_int32_t hlen;

	m = state->m;
	if (!m) {
		return EINVAL;
	}

	/* can't tunnel between different AFs */
	if (((struct sockaddr *)&sav->sah->saidx.src)->sa_family
	    != ((struct sockaddr *)&sav->sah->saidx.dst)->sa_family
	    || ((struct sockaddr *)&sav->sah->saidx.src)->sa_family != AF_INET6) {
		m_freem(m);
		return EINVAL;
	}

	if (m->m_len < sizeof(*ip)) {
		panic("ipsec46_encapsulate: assumption failed (first mbuf length)");
		return EINVAL;
	}

	ip = mtod(m, struct ip *);
#ifdef _IP_VHL
	hlen = _IP_VHL_HL(ip->ip_vhl) << 2;
#else
	hlen = ip->ip_hl << 2;
#endif

	if (m->m_len != hlen) {
		panic("ipsec46_encapsulate: assumption failed (first mbuf length)");
		return EINVAL;
	}

	/* generate header checksum */
	ip->ip_sum = 0;
#ifdef _IP_VHL
	ip->ip_sum = in_cksum(m, hlen);
#else
	ip->ip_sum = in_cksum(m, hlen);
#endif

	plen = m->m_pkthdr.len; // save original IPv4 packet len, this will be ipv6 payload len

	/*
	 * First move the IPv4 header to the second mbuf in the chain
	 */
	if (M_LEADINGSPACE(m->m_next) < hlen) {
		struct mbuf *n;
		MGET(n, M_DONTWAIT, MT_DATA);
		if (!n) {
			m_freem(m);
			return ENOBUFS;
		}
		n->m_len = hlen;
		n->m_next = m->m_next;
		m->m_next = n;
		m->m_pkthdr.len += sizeof(struct ip6_hdr);
		oip = mtod(n, struct ip *);
	} else {
		m->m_next->m_len += hlen;
		m->m_next->m_data -= hlen;
		m->m_pkthdr.len += sizeof(struct ip6_hdr);
		oip = mtod(m->m_next, struct ip *);
	}
	ip = mtod(m, struct ip *);
	ovbcopy((caddr_t)ip, (caddr_t)oip, hlen);

	/*
	 * Grow the first mbuf to accomodate the new IPv6 header.
	 */
	if (M_LEADINGSPACE(m) < sizeof(struct ip6_hdr) - hlen) {
		struct mbuf *n;
		MGETHDR(n, M_DONTWAIT, MT_HEADER);
		if (!n) {
			m_freem(m);
			return ENOBUFS;
		}
		M_COPY_PKTHDR(n, m);
		MH_ALIGN(n, sizeof(struct ip6_hdr));
		n->m_len = sizeof(struct ip6_hdr);
		n->m_next = m->m_next;
		m->m_next = NULL;
		m_freem(m);
		state->m = n;
		m = state->m;
	} else {
		m->m_len += (sizeof(struct ip6_hdr) - hlen);
		m->m_data -= (sizeof(struct ip6_hdr) - hlen);
	}
	ip6 = mtod(m, struct ip6_hdr *);
	ip6->ip6_flow = 0;
	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
	ip6->ip6_vfc |= IPV6_VERSION;

	/* construct new IPv6 header. see RFC 2401 5.1.2.2 */
	/* ECN consideration. */
	ip46_ecn_ingress(ip6_ipsec_ecn, &ip6->ip6_flow, &ip->ip_tos);
	if (plen < IPV6_MAXPACKET - sizeof(struct ip6_hdr)) {
		ip6->ip6_plen = htons((u_int16_t)plen);
	} else {
		/* ip6->ip6_plen will be updated in ip6_output() */
	}

	ip6->ip6_nxt = IPPROTO_IPV4;
	ip6->ip6_hlim = IPV6_DEFHLIM;

	bcopy(&((struct sockaddr_in6 *)&sav->sah->saidx.src)->sin6_addr,
	    &ip6->ip6_src, sizeof(ip6->ip6_src));
	bcopy(&((struct sockaddr_in6 *)&sav->sah->saidx.dst)->sin6_addr,
	    &ip6->ip6_dst, sizeof(ip6->ip6_dst));

	return 0;
}

/*
 * Check the variable replay window.
 * ipsec_chkreplay() performs replay check before ICV verification.
 * ipsec_updatereplay() updates replay bitmap.  This must be called after
 * ICV verification (it also performs replay check, which is usually done
 * beforehand).
 * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
 *
 * based on RFC 2401.
 */
int
ipsec_chkreplay(u_int32_t seq, struct secasvar *sav, u_int8_t replay_index)
{
	const struct secreplay *replay;
	u_int32_t diff;
	size_t fr;
	size_t wsizeb;       /* constant: bits of window size */
	size_t frlast;       /* constant: last frame */


	/* sanity check */
	if (sav == NULL) {
		panic("ipsec_chkreplay: NULL pointer was passed.\n");
	}

	lck_mtx_lock(sadb_mutex);
	replay = sav->replay[replay_index];

	if (replay->wsize == 0) {
		lck_mtx_unlock(sadb_mutex);
		return 1;       /* no need to check replay. */
	}

	/* constant */
	frlast = replay->wsize - 1;
	wsizeb = replay->wsize << 3;

	/* sequence number of 0 is invalid */
	if (seq == 0) {
		lck_mtx_unlock(sadb_mutex);
		return 0;
	}

	/* first time is always okay */
	if (replay->count == 0) {
		lck_mtx_unlock(sadb_mutex);
		return 1;
	}

	if (seq > replay->lastseq) {
		/* larger sequences are okay */
		lck_mtx_unlock(sadb_mutex);
		return 1;
	} else {
		/* seq is equal or less than lastseq. */
		diff = replay->lastseq - seq;

		/* over range to check, i.e. too old or wrapped */
		if (diff >= wsizeb) {
			lck_mtx_unlock(sadb_mutex);
			return 0;
		}

		fr = frlast - diff / 8;

		/* this packet already seen ? */
		if ((replay->bitmap)[fr] & (1 << (diff % 8))) {
			lck_mtx_unlock(sadb_mutex);
			return 0;
		}

		/* out of order but good */
		lck_mtx_unlock(sadb_mutex);
		return 1;
	}
}

/*
 * check replay counter whether to update or not.
 * OUT:	0:	OK
 *	1:	NG
 */
int
ipsec_updatereplay(u_int32_t seq, struct secasvar *sav, u_int8_t replay_index)
{
	struct secreplay *replay;
	u_int32_t diff;
	size_t fr;
	size_t wsizeb;       /* constant: bits of window size */
	size_t frlast;             /* constant: last frame */

	/* sanity check */
	if (sav == NULL) {
		panic("ipsec_chkreplay: NULL pointer was passed.\n");
	}

	lck_mtx_lock(sadb_mutex);
	replay = sav->replay[replay_index];

	if (replay->wsize == 0) {
		goto ok;        /* no need to check replay. */
	}
	/* constant */
	frlast = replay->wsize - 1;
	wsizeb = replay->wsize << 3;

	/* sequence number of 0 is invalid */
	if (seq == 0) {
		lck_mtx_unlock(sadb_mutex);
		return 1;
	}

	/* first time */
	if (replay->count == 0) {
		replay->lastseq = seq;
		bzero(replay->bitmap, replay->wsize);
		(replay->bitmap)[frlast] = 1;
		goto ok;
	}

	if (seq > replay->lastseq) {
		/* seq is larger than lastseq. */
		diff = seq - replay->lastseq;

		/* new larger sequence number */
		if (diff < wsizeb) {
			/* In window */
			/* set bit for this packet */
			vshiftl((unsigned char *) replay->bitmap, diff, replay->wsize);
			(replay->bitmap)[frlast] |= 1;
		} else {
			/* this packet has a "way larger" */
			bzero(replay->bitmap, replay->wsize);
			(replay->bitmap)[frlast] = 1;
		}
		replay->lastseq = seq;

		/* larger is good */
	} else {
		/* seq is equal or less than lastseq. */
		diff = replay->lastseq - seq;

		/* over range to check, i.e. too old or wrapped */
		if (diff >= wsizeb) {
			lck_mtx_unlock(sadb_mutex);
			return 1;
		}

		fr = frlast - diff / 8;

		/* this packet already seen ? */
		if ((replay->bitmap)[fr] & (1 << (diff % 8))) {
			lck_mtx_unlock(sadb_mutex);
			return 1;
		}

		/* mark as seen */
		(replay->bitmap)[fr] |= (1 << (diff % 8));

		/* out of order but good */
	}

ok:
	if (replay->count == ~0) {
		/* set overflow flag */
		replay->overflow++;

		/* don't increment, no more packets accepted */
		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
			lck_mtx_unlock(sadb_mutex);
			return 1;
		}

		ipseclog((LOG_WARNING, "replay counter made %d cycle. %s\n",
		    replay->overflow, ipsec_logsastr(sav)));
	}

	replay->count++;

	lck_mtx_unlock(sadb_mutex);
	return 0;
}

/*
 * shift variable length buffer to left.
 * IN:	bitmap: pointer to the buffer
 *      nbit:	the number of to shift.
 *	wsize:	buffer size (bytes).
 */
static void
vshiftl(unsigned char *bitmap, int nbit, size_t wsize)
{
	size_t i;
	int s, j;
	unsigned char over;

	for (j = 0; j < nbit; j += 8) {
		s = (nbit - j < 8) ? (nbit - j): 8;
		bitmap[0] <<= s;
		for (i = 1; i < wsize; i++) {
			over = (bitmap[i] >> (8 - s));
			bitmap[i] <<= s;
			bitmap[i - 1] |= over;
		}
	}

	return;
}

const char *
ipsec4_logpacketstr(struct ip *ip, u_int32_t spi)
{
	static char buf[256] __attribute__((aligned(4)));
	char *p;
	u_int8_t *s, *d;

	s = (u_int8_t *)(&ip->ip_src);
	d = (u_int8_t *)(&ip->ip_dst);

	p = buf;
	snprintf(buf, sizeof(buf), "packet(SPI=%u ", (u_int32_t)ntohl(spi));
	while (p && *p) {
		p++;
	}
	snprintf(p, sizeof(buf) - (p - buf), "src=%u.%u.%u.%u",
	    s[0], s[1], s[2], s[3]);
	while (p && *p) {
		p++;
	}
	snprintf(p, sizeof(buf) - (p - buf), " dst=%u.%u.%u.%u",
	    d[0], d[1], d[2], d[3]);
	while (p && *p) {
		p++;
	}
	snprintf(p, sizeof(buf) - (p - buf), ")");

	return buf;
}

const char *
ipsec6_logpacketstr(struct ip6_hdr *ip6, u_int32_t spi)
{
	static char buf[256] __attribute__((aligned(4)));
	char *p;

	p = buf;
	snprintf(buf, sizeof(buf), "packet(SPI=%u ", (u_int32_t)ntohl(spi));
	while (p && *p) {
		p++;
	}
	snprintf(p, sizeof(buf) - (p - buf), "src=%s",
	    ip6_sprintf(&ip6->ip6_src));
	while (p && *p) {
		p++;
	}
	snprintf(p, sizeof(buf) - (p - buf), " dst=%s",
	    ip6_sprintf(&ip6->ip6_dst));
	while (p && *p) {
		p++;
	}
	snprintf(p, sizeof(buf) - (p - buf), ")");

	return buf;
}

const char *
ipsec_logsastr(struct secasvar *sav)
{
	static char buf[256] __attribute__((aligned(4)));
	char *p;
	struct secasindex *saidx = &sav->sah->saidx;

	/* validity check */
	if (((struct sockaddr *)&sav->sah->saidx.src)->sa_family
	    != ((struct sockaddr *)&sav->sah->saidx.dst)->sa_family) {
		panic("ipsec_logsastr: family mismatched.\n");
	}

	p = buf;
	snprintf(buf, sizeof(buf), "SA(SPI=%u ", (u_int32_t)ntohl(sav->spi));
	while (p && *p) {
		p++;
	}
	if (((struct sockaddr *)&saidx->src)->sa_family == AF_INET) {
		u_int8_t *s, *d;
		s = (u_int8_t *)&((struct sockaddr_in *)&saidx->src)->sin_addr;
		d = (u_int8_t *)&((struct sockaddr_in *)&saidx->dst)->sin_addr;
		snprintf(p, sizeof(buf) - (p - buf),
		    "src=%d.%d.%d.%d dst=%d.%d.%d.%d",
		    s[0], s[1], s[2], s[3], d[0], d[1], d[2], d[3]);
	} else if (((struct sockaddr *)&saidx->src)->sa_family == AF_INET6) {
		snprintf(p, sizeof(buf) - (p - buf),
		    "src=%s",
		    ip6_sprintf(&((struct sockaddr_in6 *)&saidx->src)->sin6_addr));
		while (p && *p) {
			p++;
		}
		snprintf(p, sizeof(buf) - (p - buf),
		    " dst=%s",
		    ip6_sprintf(&((struct sockaddr_in6 *)&saidx->dst)->sin6_addr));
	}
	while (p && *p) {
		p++;
	}
	snprintf(p, sizeof(buf) - (p - buf), ")");

	return buf;
}

void
ipsec_dumpmbuf(struct mbuf *m)
{
	int totlen;
	int i;
	u_char *p;

	totlen = 0;
	printf("---\n");
	while (m) {
		p = mtod(m, u_char *);
		for (i = 0; i < m->m_len; i++) {
			printf("%02x ", p[i]);
			totlen++;
			if (totlen % 16 == 0) {
				printf("\n");
			}
		}
		m = m->m_next;
	}
	if (totlen % 16 != 0) {
		printf("\n");
	}
	printf("---\n");
}

#if INET
/*
 * IPsec output logic for IPv4.
 */
static int
ipsec4_output_internal(struct ipsec_output_state *state, struct secasvar *sav)
{
	struct ip *ip = NULL;
	int error = 0;
	struct sockaddr_in *dst4;
	struct route *ro4;

	/* validity check */
	if (sav == NULL || sav->sah == NULL) {
		error = EINVAL;
		goto bad;
	}

	/*
	 * If there is no valid SA, we give up to process any
	 * more.  In such a case, the SA's status is changed
	 * from DYING to DEAD after allocating.  If a packet
	 * send to the receiver by dead SA, the receiver can
	 * not decode a packet because SA has been dead.
	 */
	if (sav->state != SADB_SASTATE_MATURE
	    && sav->state != SADB_SASTATE_DYING) {
		IPSEC_STAT_INCREMENT(ipsecstat.out_nosa);
		error = EINVAL;
		goto bad;
	}

	state->outgoing_if = sav->sah->outgoing_if;

	/*
	 * There may be the case that SA status will be changed when
	 * we are refering to one. So calling splsoftnet().
	 */

	if (sav->sah->saidx.mode == IPSEC_MODE_TUNNEL) {
		/*
		 * build IPsec tunnel.
		 */
		state->m = ipsec4_splithdr(state->m);
		if (!state->m) {
			error = ENOMEM;
			goto bad;
		}

		if (((struct sockaddr *)&sav->sah->saidx.src)->sa_family == AF_INET6) {
			error = ipsec46_encapsulate(state, sav);
			if (error) {
				// packet already freed by encapsulation error handling
				state->m = NULL;
				return error;
			}

			error = ipsec6_update_routecache_and_output(state, sav);
			return error;
		} else if (((struct sockaddr *)&sav->sah->saidx.src)->sa_family == AF_INET) {
			error = ipsec4_encapsulate(state->m, sav);
			if (error) {
				state->m = NULL;
				goto bad;
			}
			ip = mtod(state->m, struct ip *);

			// grab sadb_mutex, before updating sah's route cache
			lck_mtx_lock(sadb_mutex);
			ro4 = (struct route *)&sav->sah->sa_route;
			dst4 = (struct sockaddr_in *)(void *)&ro4->ro_dst;
			if (ro4->ro_rt != NULL) {
				RT_LOCK(ro4->ro_rt);
			}
			if (ROUTE_UNUSABLE(ro4) ||
			    dst4->sin_addr.s_addr != ip->ip_dst.s_addr) {
				if (ro4->ro_rt != NULL) {
					RT_UNLOCK(ro4->ro_rt);
				}
				ROUTE_RELEASE(ro4);
			}
			if (ro4->ro_rt == 0) {
				dst4->sin_family = AF_INET;
				dst4->sin_len = sizeof(*dst4);
				dst4->sin_addr = ip->ip_dst;
				rtalloc_scoped(ro4, sav->sah->outgoing_if);
				if (ro4->ro_rt == 0) {
					OSAddAtomic(1, &ipstat.ips_noroute);
					error = EHOSTUNREACH;
					// release sadb_mutex, after updating sah's route cache
					lck_mtx_unlock(sadb_mutex);
					goto bad;
				}
				RT_LOCK(ro4->ro_rt);
			}

			/*
			 * adjust state->dst if tunnel endpoint is offlink
			 *
			 * XXX: caching rt_gateway value in the state is
			 * not really good, since it may point elsewhere
			 * when the gateway gets modified to a larger
			 * sockaddr via rt_setgate().  This is currently
			 * addressed by SA_SIZE roundup in that routine.
			 */
			if (ro4->ro_rt->rt_flags & RTF_GATEWAY) {
				dst4 = (struct sockaddr_in *)(void *)ro4->ro_rt->rt_gateway;
			}
			RT_UNLOCK(ro4->ro_rt);
			ROUTE_RELEASE(&state->ro);
			route_copyout((struct route *)&state->ro, ro4, sizeof(struct route));
			state->dst = (struct sockaddr *)dst4;
			state->tunneled = 4;
			// release sadb_mutex, after updating sah's route cache
			lck_mtx_unlock(sadb_mutex);
		} else {
			ipseclog((LOG_ERR, "%s: family mismatched between inner and outer spi=%u\n",
			    __FUNCTION__, (u_int32_t)ntohl(sav->spi)));
			error = EAFNOSUPPORT;
			goto bad;
		}
	}

	state->m = ipsec4_splithdr(state->m);
	if (!state->m) {
		error = ENOMEM;
		goto bad;
	}
	switch (sav->sah->saidx.proto) {
	case IPPROTO_ESP:
#if IPSEC_ESP
		if ((error = esp4_output(state->m, sav)) != 0) {
			state->m = NULL;
			goto bad;
		}
		break;
#else
		m_freem(state->m);
		state->m = NULL;
		error = EINVAL;
		goto bad;
#endif
	case IPPROTO_AH:
		if ((error = ah4_output(state->m, sav)) != 0) {
			state->m = NULL;
			goto bad;
		}
		break;
	default:
		ipseclog((LOG_ERR,
		    "ipsec4_output: unknown ipsec protocol %d\n",
		    sav->sah->saidx.proto));
		m_freem(state->m);
		state->m = NULL;
		error = EPROTONOSUPPORT;
		goto bad;
	}

	if (state->m == 0) {
		error = ENOMEM;
		goto bad;
	}

	return 0;

bad:
	return error;
}

int
ipsec4_interface_output(struct ipsec_output_state *state, ifnet_t interface)
{
	int error = 0;
	struct secasvar *sav = NULL;

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);

	if (state == NULL) {
		panic("state == NULL in ipsec4_output");
	}
	if (state->m == NULL) {
		panic("state->m == NULL in ipsec4_output");
	}
	if (state->dst == NULL) {
		panic("state->dst == NULL in ipsec4_output");
	}

	struct ip *ip = mtod(state->m, struct ip *);

	struct sockaddr_in src = {};
	src.sin_family = AF_INET;
	src.sin_len = sizeof(src);
	memcpy(&src.sin_addr, &ip->ip_src, sizeof(src.sin_addr));

	struct sockaddr_in dst = {};
	dst.sin_family = AF_INET;
	dst.sin_len = sizeof(dst);
	memcpy(&dst.sin_addr, &ip->ip_dst, sizeof(dst.sin_addr));

	sav = key_alloc_outbound_sav_for_interface(interface, AF_INET,
	    (struct sockaddr *)&src,
	    (struct sockaddr *)&dst);
	if (sav == NULL) {
		goto bad;
	}

	if ((error = ipsec4_output_internal(state, sav)) != 0) {
		goto bad;
	}

	KERNEL_DEBUG(DBG_FNC_IPSEC_OUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
	if (sav) {
		key_freesav(sav, KEY_SADB_UNLOCKED);
	}
	return 0;

bad:
	if (sav) {
		key_freesav(sav, KEY_SADB_UNLOCKED);
	}
	m_freem(state->m);
	state->m = NULL;
	KERNEL_DEBUG(DBG_FNC_IPSEC_OUT | DBG_FUNC_END, error, 0, 0, 0, 0);
	return error;
}

int
ipsec4_output(struct ipsec_output_state *state, struct secpolicy *sp, __unused int flags)
{
	struct ip *ip = NULL;
	struct ipsecrequest *isr = NULL;
	struct secasindex saidx;
	struct secasvar *sav = NULL;
	int error = 0;
	struct sockaddr_in *sin;

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);

	if (!state) {
		panic("state == NULL in ipsec4_output");
	}
	if (!state->m) {
		panic("state->m == NULL in ipsec4_output");
	}
	if (!state->dst) {
		panic("state->dst == NULL in ipsec4_output");
	}

	KERNEL_DEBUG(DBG_FNC_IPSEC_OUT | DBG_FUNC_START, 0, 0, 0, 0, 0);

	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
	    printf("ipsec4_output: applied SP\n");
	    kdebug_secpolicy(sp));

	for (isr = sp->req; isr != NULL; isr = isr->next) {
		/* make SA index for search proper SA */
		ip = mtod(state->m, struct ip *);
		bcopy(&isr->saidx, &saidx, sizeof(saidx));
		saidx.mode = isr->saidx.mode;
		saidx.reqid = isr->saidx.reqid;
		sin = (struct sockaddr_in *)&saidx.src;
		if (sin->sin_len == 0) {
			sin->sin_len = sizeof(*sin);
			sin->sin_family = AF_INET;
			sin->sin_port = IPSEC_PORT_ANY;
			bcopy(&ip->ip_src, &sin->sin_addr,
			    sizeof(sin->sin_addr));
		}
		sin = (struct sockaddr_in *)&saidx.dst;
		if (sin->sin_len == 0) {
			sin->sin_len = sizeof(*sin);
			sin->sin_family = AF_INET;
			sin->sin_port = IPSEC_PORT_ANY;
			/*
			 * Get port from packet if upper layer is UDP and nat traversal
			 * is enabled and transport mode.
			 */

			if ((esp_udp_encap_port & 0xFFFF) != 0 &&
			    isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
				if (ip->ip_p == IPPROTO_UDP) {
					struct udphdr  *udp;
					u_int32_t hlen;
#ifdef _IP_VHL
					hlen = IP_VHL_HL(ip->ip_vhl) << 2;
#else
					hlen = ip->ip_hl << 2;
#endif
					if (state->m->m_len < hlen + sizeof(struct udphdr)) {
						state->m = m_pullup(state->m, hlen + sizeof(struct udphdr));
						if (!state->m) {
							ipseclog((LOG_DEBUG, "IPv4 output: can't pullup UDP header\n"));
							IPSEC_STAT_INCREMENT(ipsecstat.in_inval);
							goto bad;
						}
						ip = mtod(state->m, struct ip *);
					}
					udp = (struct udphdr *)(void *)(((u_int8_t *)ip) + hlen);
					sin->sin_port = udp->uh_dport;
				}
			}

			bcopy(&ip->ip_dst, &sin->sin_addr,
			    sizeof(sin->sin_addr));
		}

		if ((error = key_checkrequest(isr, &saidx, &sav)) != 0) {
			/*
			 * IPsec processing is required, but no SA found.
			 * I assume that key_acquire() had been called
			 * to get/establish the SA. Here I discard
			 * this packet because it is responsibility for
			 * upper layer to retransmit the packet.
			 */
			IPSEC_STAT_INCREMENT(ipsecstat.out_nosa);
			goto bad;
		}

		/* validity check */
		if (sav == NULL) {
			switch (ipsec_get_reqlevel(isr)) {
			case IPSEC_LEVEL_USE:
				continue;
			case IPSEC_LEVEL_REQUIRE:
				/* must be not reached here. */
				panic("ipsec4_output: no SA found, but required.");
			}
		}

		if ((error = ipsec4_output_internal(state, sav)) != 0) {
			goto bad;
		}
	}

	KERNEL_DEBUG(DBG_FNC_IPSEC_OUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
	if (sav) {
		key_freesav(sav, KEY_SADB_UNLOCKED);
	}
	return 0;

bad:
	if (sav) {
		key_freesav(sav, KEY_SADB_UNLOCKED);
	}
	m_freem(state->m);
	state->m = NULL;
	KERNEL_DEBUG(DBG_FNC_IPSEC_OUT | DBG_FUNC_END, error, 0, 0, 0, 0);
	return error;
}

#endif

/*
 * IPsec output logic for IPv6, transport mode.
 */
static int
ipsec6_output_trans_internal(
	struct ipsec_output_state *state,
	struct secasvar *sav,
	u_char *nexthdrp,
	struct mbuf *mprev)
{
	struct ip6_hdr *ip6;
	size_t plen;
	int error = 0;

	/* validity check */
	if (sav == NULL || sav->sah == NULL) {
		error = EINVAL;
		goto bad;
	}

	/*
	 * If there is no valid SA, we give up to process.
	 * see same place at ipsec4_output().
	 */
	if (sav->state != SADB_SASTATE_MATURE
	    && sav->state != SADB_SASTATE_DYING) {
		IPSEC_STAT_INCREMENT(ipsec6stat.out_nosa);
		error = EINVAL;
		goto bad;
	}

	state->outgoing_if = sav->sah->outgoing_if;

	switch (sav->sah->saidx.proto) {
	case IPPROTO_ESP:
#if IPSEC_ESP
		error = esp6_output(state->m, nexthdrp, mprev->m_next, sav);
#else
		m_freem(state->m);
		error = EINVAL;
#endif
		break;
	case IPPROTO_AH:
		error = ah6_output(state->m, nexthdrp, mprev->m_next, sav);
		break;
	default:
		ipseclog((LOG_ERR, "ipsec6_output_trans: "
		    "unknown ipsec protocol %d\n", sav->sah->saidx.proto));
		m_freem(state->m);
		IPSEC_STAT_INCREMENT(ipsec6stat.out_inval);
		error = EPROTONOSUPPORT;
		break;
	}
	if (error) {
		state->m = NULL;
		goto bad;
	}
	plen = state->m->m_pkthdr.len - sizeof(struct ip6_hdr);
	if (plen > IPV6_MAXPACKET) {
		ipseclog((LOG_ERR, "ipsec6_output_trans: "
		    "IPsec with IPv6 jumbogram is not supported\n"));
		IPSEC_STAT_INCREMENT(ipsec6stat.out_inval);
		error = EINVAL; /*XXX*/
		goto bad;
	}
	ip6 = mtod(state->m, struct ip6_hdr *);
	ip6->ip6_plen = htons((u_int16_t)plen);

	return 0;
bad:
	return error;
}

int
ipsec6_output_trans(
	struct ipsec_output_state *state,
	u_char *nexthdrp,
	struct mbuf *mprev,
	struct secpolicy *sp,
	__unused int flags,
	int *tun)
{
	struct ip6_hdr *ip6;
	struct ipsecrequest *isr = NULL;
	struct secasindex saidx;
	int error = 0;
	struct sockaddr_in6 *sin6;
	struct secasvar *sav = NULL;

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);

	if (!state) {
		panic("state == NULL in ipsec6_output_trans");
	}
	if (!state->m) {
		panic("state->m == NULL in ipsec6_output_trans");
	}
	if (!nexthdrp) {
		panic("nexthdrp == NULL in ipsec6_output_trans");
	}
	if (!mprev) {
		panic("mprev == NULL in ipsec6_output_trans");
	}
	if (!sp) {
		panic("sp == NULL in ipsec6_output_trans");
	}
	if (!tun) {
		panic("tun == NULL in ipsec6_output_trans");
	}

	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
	    printf("ipsec6_output_trans: applyed SP\n");
	    kdebug_secpolicy(sp));

	*tun = 0;
	for (isr = sp->req; isr; isr = isr->next) {
		if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
			/* the rest will be handled by ipsec6_output_tunnel() */
			break;
		}

		/* make SA index for search proper SA */
		ip6 = mtod(state->m, struct ip6_hdr *);
		bcopy(&isr->saidx, &saidx, sizeof(saidx));
		saidx.mode = isr->saidx.mode;
		saidx.reqid = isr->saidx.reqid;
		sin6 = (struct sockaddr_in6 *)&saidx.src;
		if (sin6->sin6_len == 0) {
			sin6->sin6_len = sizeof(*sin6);
			sin6->sin6_family = AF_INET6;
			sin6->sin6_port = IPSEC_PORT_ANY;
			bcopy(&ip6->ip6_src, &sin6->sin6_addr,
			    sizeof(ip6->ip6_src));
			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
				/* fix scope id for comparing SPD */
				sin6->sin6_addr.s6_addr16[1] = 0;
				sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
			}
		}
		sin6 = (struct sockaddr_in6 *)&saidx.dst;
		if (sin6->sin6_len == 0) {
			sin6->sin6_len = sizeof(*sin6);
			sin6->sin6_family = AF_INET6;
			sin6->sin6_port = IPSEC_PORT_ANY;
			bcopy(&ip6->ip6_dst, &sin6->sin6_addr,
			    sizeof(ip6->ip6_dst));
			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
				/* fix scope id for comparing SPD */
				sin6->sin6_addr.s6_addr16[1] = 0;
				sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
			}
		}

		if (key_checkrequest(isr, &saidx, &sav) == ENOENT) {
			/*
			 * IPsec processing is required, but no SA found.
			 * I assume that key_acquire() had been called
			 * to get/establish the SA. Here I discard
			 * this packet because it is responsibility for
			 * upper layer to retransmit the packet.
			 */
			IPSEC_STAT_INCREMENT(ipsec6stat.out_nosa);
			error = ENOENT;

			/*
			 * Notify the fact that the packet is discarded
			 * to ourselves. I believe this is better than
			 * just silently discarding. (jinmei@kame.net)
			 * XXX: should we restrict the error to TCP packets?
			 * XXX: should we directly notify sockets via
			 *      pfctlinputs?
			 */
			icmp6_error(state->m, ICMP6_DST_UNREACH,
			    ICMP6_DST_UNREACH_ADMIN, 0);
			state->m = NULL; /* icmp6_error freed the mbuf */
			goto bad;
		}

		/* validity check */
		if (sav == NULL) {
			switch (ipsec_get_reqlevel(isr)) {
			case IPSEC_LEVEL_USE:
				continue;
			case IPSEC_LEVEL_REQUIRE:
				/* must be not reached here. */
				panic("ipsec6_output_trans: no SA found, but required.");
			}
		}

		if ((error = ipsec6_output_trans_internal(state, sav, nexthdrp, mprev)) != 0) {
			goto bad;
		}
	}

	/* if we have more to go, we need a tunnel mode processing */
	if (isr != NULL) {
		*tun = 1;
	}

	if (sav) {
		key_freesav(sav, KEY_SADB_UNLOCKED);
	}
	return 0;

bad:
	if (sav) {
		key_freesav(sav, KEY_SADB_UNLOCKED);
	}
	m_freem(state->m);
	state->m = NULL;
	return error;
}

/*
 * IPsec output logic for IPv6, tunnel mode.
 */
static int
ipsec6_output_tunnel_internal(struct ipsec_output_state *state, struct secasvar *sav, int *must_be_last)
{
	struct ip6_hdr *ip6;
	struct sockaddr_in6* dst6;
	struct route_in6 *ro6;
	size_t plen;
	int error = 0;

	/* validity check */
	if (sav == NULL || sav->sah == NULL || sav->sah->saidx.mode != IPSEC_MODE_TUNNEL) {
		error = EINVAL;
		goto bad;
	}

	/*
	 * If there is no valid SA, we give up to process.
	 * see same place at ipsec4_output().
	 */
	if (sav->state != SADB_SASTATE_MATURE
	    && sav->state != SADB_SASTATE_DYING) {
		IPSEC_STAT_INCREMENT(ipsec6stat.out_nosa);
		error = EINVAL;
		goto bad;
	}

	state->outgoing_if = sav->sah->outgoing_if;

	if (sav->sah->saidx.mode == IPSEC_MODE_TUNNEL) {
		/*
		 * build IPsec tunnel.
		 */
		state->m = ipsec6_splithdr(state->m);
		if (!state->m) {
			IPSEC_STAT_INCREMENT(ipsec6stat.out_nomem);
			error = ENOMEM;
			goto bad;
		}

		if (((struct sockaddr *)&sav->sah->saidx.src)->sa_family == AF_INET6) {
			error = ipsec6_encapsulate(state->m, sav);
			if (error) {
				state->m = 0;
				goto bad;
			}
			ip6 = mtod(state->m, struct ip6_hdr *);
		} else if (((struct sockaddr *)&sav->sah->saidx.src)->sa_family == AF_INET) {
			struct ip *ip;
			struct sockaddr_in* dst4;
			struct route *ro4 = NULL;
			struct route  ro4_copy;
			struct ip_out_args ipoa;

			bzero(&ipoa, sizeof(ipoa));
			ipoa.ipoa_boundif = IFSCOPE_NONE;
			ipoa.ipoa_flags = IPOAF_SELECT_SRCIF;
			ipoa.ipoa_sotc = SO_TC_UNSPEC;
			ipoa.ipoa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;

			if (must_be_last) {
				*must_be_last = 1;
			}

			state->tunneled = 4; /* must not process any further in ip6_output */
			error = ipsec64_encapsulate(state->m, sav);
			if (error) {
				state->m = 0;
				goto bad;
			}
			/* Now we have an IPv4 packet */
			ip = mtod(state->m, struct ip *);

			// grab sadb_mutex, to update sah's route cache and get a local copy of it
			lck_mtx_lock(sadb_mutex);
			ro4 = (struct route *)&sav->sah->sa_route;
			dst4 = (struct sockaddr_in *)(void *)&ro4->ro_dst;
			if (ro4->ro_rt) {
				RT_LOCK(ro4->ro_rt);
			}
			if (ROUTE_UNUSABLE(ro4) ||
			    dst4->sin_addr.s_addr != ip->ip_dst.s_addr) {
				if (ro4->ro_rt != NULL) {
					RT_UNLOCK(ro4->ro_rt);
				}
				ROUTE_RELEASE(ro4);
			}
			if (ro4->ro_rt == NULL) {
				dst4->sin_family = AF_INET;
				dst4->sin_len = sizeof(*dst4);
				dst4->sin_addr = ip->ip_dst;
			} else {
				RT_UNLOCK(ro4->ro_rt);
			}
			route_copyout(&ro4_copy, ro4, sizeof(struct route));
			// release sadb_mutex, after updating sah's route cache and getting a local copy
			lck_mtx_unlock(sadb_mutex);
			state->m = ipsec4_splithdr(state->m);
			if (!state->m) {
				error = ENOMEM;
				ROUTE_RELEASE(&ro4_copy);
				goto bad;
			}
			switch (sav->sah->saidx.proto) {
			case IPPROTO_ESP:
#if IPSEC_ESP
				if ((error = esp4_output(state->m, sav)) != 0) {
					state->m = NULL;
					ROUTE_RELEASE(&ro4_copy);
					goto bad;
				}
				break;

#else
				m_freem(state->m);
				state->m = NULL;
				error = EINVAL;
				ROUTE_RELEASE(&ro4_copy);
				goto bad;
#endif
			case IPPROTO_AH:
				if ((error = ah4_output(state->m, sav)) != 0) {
					state->m = NULL;
					ROUTE_RELEASE(&ro4_copy);
					goto bad;
				}
				break;
			default:
				ipseclog((LOG_ERR,
				    "ipsec4_output: unknown ipsec protocol %d\n",
				    sav->sah->saidx.proto));
				m_freem(state->m);
				state->m = NULL;
				error = EPROTONOSUPPORT;
				ROUTE_RELEASE(&ro4_copy);
				goto bad;
			}

			if (state->m == 0) {
				error = ENOMEM;
				ROUTE_RELEASE(&ro4_copy);
				goto bad;
			}
			ipsec_set_pkthdr_for_interface(sav->sah->ipsec_if, state->m, AF_INET);
			ipsec_set_ipoa_for_interface(sav->sah->ipsec_if, &ipoa);

			ip = mtod(state->m, struct ip *);
			ip->ip_len = ntohs(ip->ip_len);  /* flip len field before calling ip_output */
			error = ip_output(state->m, NULL, &ro4_copy, IP_OUTARGS, NULL, &ipoa);
			state->m = NULL;
			// grab sadb_mutex, to synchronize the sah's route cache with the local copy
			lck_mtx_lock(sadb_mutex);
			route_copyin(&ro4_copy, ro4, sizeof(struct route));
			lck_mtx_unlock(sadb_mutex);
			if (error != 0) {
				goto bad;
			}
			goto done;
		} else {
			ipseclog((LOG_ERR, "ipsec6_output_tunnel: "
			    "unsupported inner family, spi=%u\n",
			    (u_int32_t)ntohl(sav->spi)));
			IPSEC_STAT_INCREMENT(ipsec6stat.out_inval);
			error = EAFNOSUPPORT;
			goto bad;
		}

		// grab sadb_mutex, before updating sah's route cache
		lck_mtx_lock(sadb_mutex);
		ro6 = &sav->sah->sa_route;
		dst6 = (struct sockaddr_in6 *)(void *)&ro6->ro_dst;
		if (ro6->ro_rt) {
			RT_LOCK(ro6->ro_rt);
		}
		if (ROUTE_UNUSABLE(ro6) ||
		    !IN6_ARE_ADDR_EQUAL(&dst6->sin6_addr, &ip6->ip6_dst)) {
			if (ro6->ro_rt != NULL) {
				RT_UNLOCK(ro6->ro_rt);
			}
			ROUTE_RELEASE(ro6);
		}
		if (ro6->ro_rt == 0) {
			bzero(dst6, sizeof(*dst6));
			dst6->sin6_family = AF_INET6;
			dst6->sin6_len = sizeof(*dst6);
			dst6->sin6_addr = ip6->ip6_dst;
			rtalloc_scoped((struct route *)ro6, sav->sah->outgoing_if);
			if (ro6->ro_rt) {
				RT_LOCK(ro6->ro_rt);
			}
		}
		if (ro6->ro_rt == 0) {
			ip6stat.ip6s_noroute++;
			IPSEC_STAT_INCREMENT(ipsec6stat.out_noroute);
			error = EHOSTUNREACH;
			// release sadb_mutex, after updating sah's route cache
			lck_mtx_unlock(sadb_mutex);
			goto bad;
		}

		/*
		 * adjust state->dst if tunnel endpoint is offlink
		 *
		 * XXX: caching rt_gateway value in the state is
		 * not really good, since it may point elsewhere
		 * when the gateway gets modified to a larger
		 * sockaddr via rt_setgate().  This is currently
		 * addressed by SA_SIZE roundup in that routine.
		 */
		if (ro6->ro_rt->rt_flags & RTF_GATEWAY) {
			dst6 = (struct sockaddr_in6 *)(void *)ro6->ro_rt->rt_gateway;
		}
		RT_UNLOCK(ro6->ro_rt);
		ROUTE_RELEASE(&state->ro);
		route_copyout((struct route *)&state->ro, (struct route *)ro6, sizeof(struct route_in6));
		state->dst = (struct sockaddr *)dst6;
		state->tunneled = 6;
		// release sadb_mutex, after updating sah's route cache
		lck_mtx_unlock(sadb_mutex);
	}

	state->m = ipsec6_splithdr(state->m);
	if (!state->m) {
		IPSEC_STAT_INCREMENT(ipsec6stat.out_nomem);
		error = ENOMEM;
		goto bad;
	}
	ip6 = mtod(state->m, struct ip6_hdr *);
	switch (sav->sah->saidx.proto) {
	case IPPROTO_ESP:
#if IPSEC_ESP
		error = esp6_output(state->m, &ip6->ip6_nxt, state->m->m_next, sav);
#else
		m_freem(state->m);
		error = EINVAL;
#endif
		break;
	case IPPROTO_AH:
		error = ah6_output(state->m, &ip6->ip6_nxt, state->m->m_next, sav);
		break;
	default:
		ipseclog((LOG_ERR, "ipsec6_output_tunnel: "
		    "unknown ipsec protocol %d\n", sav->sah->saidx.proto));
		m_freem(state->m);
		IPSEC_STAT_INCREMENT(ipsec6stat.out_inval);
		error = EINVAL;
		break;
	}
	if (error) {
		state->m = NULL;
		goto bad;
	}
	plen = state->m->m_pkthdr.len - sizeof(struct ip6_hdr);
	if (plen > IPV6_MAXPACKET) {
		ipseclog((LOG_ERR, "ipsec6_output_tunnel: "
		    "IPsec with IPv6 jumbogram is not supported\n"));
		IPSEC_STAT_INCREMENT(ipsec6stat.out_inval);
		error = EINVAL; /*XXX*/
		goto bad;
	}
	ip6 = mtod(state->m, struct ip6_hdr *);
	ip6->ip6_plen = htons((u_int16_t)plen);
done:
	return 0;

bad:
	return error;
}

int
ipsec6_output_tunnel(
	struct ipsec_output_state *state,
	struct secpolicy *sp,
	__unused int flags)
{
	struct ip6_hdr *ip6;
	struct ipsecrequest *isr = NULL;
	struct secasindex saidx;
	struct secasvar *sav = NULL;
	int error = 0;

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);

	if (!state) {
		panic("state == NULL in ipsec6_output_tunnel");
	}
	if (!state->m) {
		panic("state->m == NULL in ipsec6_output_tunnel");
	}
	if (!sp) {
		panic("sp == NULL in ipsec6_output_tunnel");
	}

	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
	    printf("ipsec6_output_tunnel: applyed SP\n");
	    kdebug_secpolicy(sp));

	/*
	 * transport mode ipsec (before the 1st tunnel mode) is already
	 * processed by ipsec6_output_trans().
	 */
	for (isr = sp->req; isr; isr = isr->next) {
		if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
			break;
		}
	}

	for (/* already initialized */; isr; isr = isr->next) {
		if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
			/* When tunnel mode, SA peers must be specified. */
			bcopy(&isr->saidx, &saidx, sizeof(saidx));
		} else {
			/* make SA index to look for a proper SA */
			struct sockaddr_in6 *sin6;

			bzero(&saidx, sizeof(saidx));
			saidx.proto = isr->saidx.proto;
			saidx.mode = isr->saidx.mode;
			saidx.reqid = isr->saidx.reqid;

			ip6 = mtod(state->m, struct ip6_hdr *);
			sin6 = (struct sockaddr_in6 *)&saidx.src;
			if (sin6->sin6_len == 0) {
				sin6->sin6_len = sizeof(*sin6);
				sin6->sin6_family = AF_INET6;
				sin6->sin6_port = IPSEC_PORT_ANY;
				bcopy(&ip6->ip6_src, &sin6->sin6_addr,
				    sizeof(ip6->ip6_src));
				if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
					/* fix scope id for comparing SPD */
					sin6->sin6_addr.s6_addr16[1] = 0;
					sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
				}
			}
			sin6 = (struct sockaddr_in6 *)&saidx.dst;
			if (sin6->sin6_len == 0) {
				sin6->sin6_len = sizeof(*sin6);
				sin6->sin6_family = AF_INET6;
				sin6->sin6_port = IPSEC_PORT_ANY;
				bcopy(&ip6->ip6_dst, &sin6->sin6_addr,
				    sizeof(ip6->ip6_dst));
				if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
					/* fix scope id for comparing SPD */
					sin6->sin6_addr.s6_addr16[1] = 0;
					sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
				}
			}
		}

		if (key_checkrequest(isr, &saidx, &sav) == ENOENT) {
			/*
			 * IPsec processing is required, but no SA found.
			 * I assume that key_acquire() had been called
			 * to get/establish the SA. Here I discard
			 * this packet because it is responsibility for
			 * upper layer to retransmit the packet.
			 */
			IPSEC_STAT_INCREMENT(ipsec6stat.out_nosa);
			error = ENOENT;
			goto bad;
		}

		/* validity check */
		if (sav == NULL) {
			switch (ipsec_get_reqlevel(isr)) {
			case IPSEC_LEVEL_USE:
				continue;
			case IPSEC_LEVEL_REQUIRE:
				/* must be not reached here. */
				panic("ipsec6_output_tunnel: no SA found, but required.");
			}
		}

		/*
		 * If there is no valid SA, we give up to process.
		 * see same place at ipsec4_output().
		 */
		if (sav->state != SADB_SASTATE_MATURE
		    && sav->state != SADB_SASTATE_DYING) {
			IPSEC_STAT_INCREMENT(ipsec6stat.out_nosa);
			error = EINVAL;
			goto bad;
		}

		int must_be_last = 0;

		if ((error = ipsec6_output_tunnel_internal(state, sav, &must_be_last)) != 0) {
			goto bad;
		}

		if (must_be_last && isr->next) {
			ipseclog((LOG_ERR, "ipsec6_output_tunnel: "
			    "IPv4 must be outer layer, spi=%u\n",
			    (u_int32_t)ntohl(sav->spi)));
			error = EINVAL;
			goto bad;
		}
	}

	if (sav) {
		key_freesav(sav, KEY_SADB_UNLOCKED);
	}
	return 0;

bad:
	if (sav) {
		key_freesav(sav, KEY_SADB_UNLOCKED);
	}
	if (state->m) {
		m_freem(state->m);
	}
	state->m = NULL;
	return error;
}

int
ipsec6_interface_output(struct ipsec_output_state *state, ifnet_t interface, u_char *nexthdrp, struct mbuf *mprev)
{
	int error = 0;
	struct secasvar *sav = NULL;

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);

	if (state == NULL) {
		panic("state == NULL in ipsec6_output");
	}
	if (state->m == NULL) {
		panic("state->m == NULL in ipsec6_output");
	}
	if (nexthdrp == NULL) {
		panic("nexthdrp == NULL in ipsec6_output");
	}
	if (mprev == NULL) {
		panic("mprev == NULL in ipsec6_output");
	}

	struct ip6_hdr *ip6 = mtod(state->m, struct ip6_hdr *);

	struct sockaddr_in6 src = {};
	src.sin6_family = AF_INET6;
	src.sin6_len = sizeof(src);
	memcpy(&src.sin6_addr, &ip6->ip6_src, sizeof(src.sin6_addr));

	struct sockaddr_in6 dst = {};
	dst.sin6_family = AF_INET6;
	dst.sin6_len = sizeof(dst);
	memcpy(&dst.sin6_addr, &ip6->ip6_dst, sizeof(dst.sin6_addr));

	sav = key_alloc_outbound_sav_for_interface(interface, AF_INET6,
	    (struct sockaddr *)&src,
	    (struct sockaddr *)&dst);
	if (sav == NULL) {
		goto bad;
	}

	if (sav->sah && sav->sah->saidx.mode == IPSEC_MODE_TUNNEL) {
		if ((error = ipsec6_output_tunnel_internal(state, sav, NULL)) != 0) {
			goto bad;
		}
	} else {
		if ((error = ipsec6_output_trans_internal(state, sav, nexthdrp, mprev)) != 0) {
			goto bad;
		}
	}

	if (sav) {
		key_freesav(sav, KEY_SADB_UNLOCKED);
	}
	return 0;

bad:
	if (sav) {
		key_freesav(sav, KEY_SADB_UNLOCKED);
	}
	m_freem(state->m);
	state->m = NULL;
	return error;
}

#if INET
/*
 * Chop IP header and option off from the payload.
 */
struct mbuf *
ipsec4_splithdr(struct mbuf *m)
{
	struct mbuf *mh;
	struct ip *ip;
	int hlen;

	if (m->m_len < sizeof(struct ip)) {
		panic("ipsec4_splithdr: first mbuf too short, m_len %d, pkt_len %d, m_flag %x", m->m_len, m->m_pkthdr.len, m->m_flags);
	}
	ip = mtod(m, struct ip *);
#ifdef _IP_VHL
	hlen = _IP_VHL_HL(ip->ip_vhl) << 2;
#else
	hlen = ip->ip_hl << 2;
#endif
	if (m->m_len > hlen) {
		MGETHDR(mh, M_DONTWAIT, MT_HEADER);     /* MAC-OK */
		if (!mh) {
			m_freem(m);
			return NULL;
		}
		M_COPY_PKTHDR(mh, m);
		MH_ALIGN(mh, hlen);
		m->m_flags &= ~M_PKTHDR;
		m_mchtype(m, MT_DATA);
		m->m_len -= hlen;
		m->m_data += hlen;
		mh->m_next = m;
		m = mh;
		m->m_len = hlen;
		bcopy((caddr_t)ip, mtod(m, caddr_t), hlen);
	} else if (m->m_len < hlen) {
		m = m_pullup(m, hlen);
		if (!m) {
			return NULL;
		}
	}
	return m;
}
#endif

struct mbuf *
ipsec6_splithdr(struct mbuf *m)
{
	struct mbuf *mh;
	struct ip6_hdr *ip6;
	int hlen;

	if (m->m_len < sizeof(struct ip6_hdr)) {
		panic("ipsec6_splithdr: first mbuf too short");
	}
	ip6 = mtod(m, struct ip6_hdr *);
	hlen = sizeof(struct ip6_hdr);
	if (m->m_len > hlen) {
		MGETHDR(mh, M_DONTWAIT, MT_HEADER);     /* MAC-OK */
		if (!mh) {
			m_freem(m);
			return NULL;
		}
		M_COPY_PKTHDR(mh, m);
		MH_ALIGN(mh, hlen);
		m->m_flags &= ~M_PKTHDR;
		m_mchtype(m, MT_DATA);
		m->m_len -= hlen;
		m->m_data += hlen;
		mh->m_next = m;
		m = mh;
		m->m_len = hlen;
		bcopy((caddr_t)ip6, mtod(m, caddr_t), hlen);
	} else if (m->m_len < hlen) {
		m = m_pullup(m, hlen);
		if (!m) {
			return NULL;
		}
	}
	return m;
}

/* validate inbound IPsec tunnel packet. */
int
ipsec4_tunnel_validate(
	struct mbuf *m,         /* no pullup permitted, m->m_len >= ip */
	int off,
	u_int nxt0,
	struct secasvar *sav,
	sa_family_t *ifamily)
{
	u_int8_t nxt = nxt0 & 0xff;
	struct sockaddr_in *sin;
	struct sockaddr_in osrc, odst, i4src, i4dst;
	struct sockaddr_in6 i6src, i6dst;
	int hlen;
	struct secpolicy *sp;
	struct ip *oip;

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);

#if DIAGNOSTIC
	if (m->m_len < sizeof(struct ip)) {
		panic("too short mbuf on ipsec4_tunnel_validate");
	}
#endif
	if (nxt != IPPROTO_IPV4 && nxt != IPPROTO_IPV6) {
		return 0;
	}
	if (m->m_pkthdr.len < off + sizeof(struct ip)) {
		return 0;
	}
	/* do not decapsulate if the SA is for transport mode only */
	if (sav->sah->saidx.mode == IPSEC_MODE_TRANSPORT) {
		return 0;
	}

	oip = mtod(m, struct ip *);
#ifdef _IP_VHL
	hlen = _IP_VHL_HL(oip->ip_vhl) << 2;
#else
	hlen = oip->ip_hl << 2;
#endif
	if (hlen != sizeof(struct ip)) {
		return 0;
	}

	sin = (struct sockaddr_in *)&sav->sah->saidx.dst;
	if (sin->sin_family != AF_INET) {
		return 0;
	}
	if (bcmp(&oip->ip_dst, &sin->sin_addr, sizeof(oip->ip_dst)) != 0) {
		return 0;
	}

	if (sav->sah->ipsec_if != NULL) {
		// the ipsec interface SAs don't have a policies.
		if (nxt == IPPROTO_IPV4) {
			*ifamily = AF_INET;
		} else if (nxt == IPPROTO_IPV6) {
			*ifamily = AF_INET6;
		} else {
			return 0;
		}
		return 1;
	}

	/* XXX slow */
	bzero(&osrc, sizeof(osrc));
	bzero(&odst, sizeof(odst));
	osrc.sin_family = odst.sin_family = AF_INET;
	osrc.sin_len = odst.sin_len = sizeof(struct sockaddr_in);
	osrc.sin_addr = oip->ip_src;
	odst.sin_addr = oip->ip_dst;
	/*
	 * RFC2401 5.2.1 (b): (assume that we are using tunnel mode)
	 * - if the inner destination is multicast address, there can be
	 *   multiple permissible inner source address.  implementation
	 *   may want to skip verification of inner source address against
	 *   SPD selector.
	 * - if the inner protocol is ICMP, the packet may be an error report
	 *   from routers on the other side of the VPN cloud (R in the
	 *   following diagram).  in this case, we cannot verify inner source
	 *   address against SPD selector.
	 *	me -- gw === gw -- R -- you
	 *
	 * we consider the first bullet to be users responsibility on SPD entry
	 * configuration (if you need to encrypt multicast traffic, set
	 * the source range of SPD selector to 0.0.0.0/0, or have explicit
	 * address ranges for possible senders).
	 * the second bullet is not taken care of (yet).
	 *
	 * therefore, we do not do anything special about inner source.
	 */
	if (nxt == IPPROTO_IPV4) {
		bzero(&i4src, sizeof(struct sockaddr_in));
		bzero(&i4dst, sizeof(struct sockaddr_in));
		i4src.sin_family = i4dst.sin_family = *ifamily = AF_INET;
		i4src.sin_len = i4dst.sin_len = sizeof(struct sockaddr_in);
		m_copydata(m, off + offsetof(struct ip, ip_src), sizeof(i4src.sin_addr),
		    (caddr_t)&i4src.sin_addr);
		m_copydata(m, off + offsetof(struct ip, ip_dst), sizeof(i4dst.sin_addr),
		    (caddr_t)&i4dst.sin_addr);
		sp = key_gettunnel((struct sockaddr *)&osrc, (struct sockaddr *)&odst,
		    (struct sockaddr *)&i4src, (struct sockaddr *)&i4dst);
	} else if (nxt == IPPROTO_IPV6) {
		bzero(&i6src, sizeof(struct sockaddr_in6));
		bzero(&i6dst, sizeof(struct sockaddr_in6));
		i6src.sin6_family = i6dst.sin6_family = *ifamily = AF_INET6;
		i6src.sin6_len = i6dst.sin6_len = sizeof(struct sockaddr_in6);
		m_copydata(m, off + offsetof(struct ip6_hdr, ip6_src), sizeof(i6src.sin6_addr),
		    (caddr_t)&i6src.sin6_addr);
		m_copydata(m, off + offsetof(struct ip6_hdr, ip6_dst), sizeof(i6dst.sin6_addr),
		    (caddr_t)&i6dst.sin6_addr);
		sp = key_gettunnel((struct sockaddr *)&osrc, (struct sockaddr *)&odst,
		    (struct sockaddr *)&i6src, (struct sockaddr *)&i6dst);
	} else {
		return 0;       /* unsupported family */
	}
	if (!sp) {
		return 0;
	}

	key_freesp(sp, KEY_SADB_UNLOCKED);

	return 1;
}

/* validate inbound IPsec tunnel packet. */
int
ipsec6_tunnel_validate(
	struct mbuf *m,         /* no pullup permitted, m->m_len >= ip */
	int off,
	u_int nxt0,
	struct secasvar *sav,
	sa_family_t *ifamily)
{
	u_int8_t nxt = nxt0 & 0xff;
	struct sockaddr_in6 *sin6;
	struct sockaddr_in i4src, i4dst;
	struct sockaddr_in6 osrc, odst, i6src, i6dst;
	struct secpolicy *sp;
	struct ip6_hdr *oip6;

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);

#if DIAGNOSTIC
	if (m->m_len < sizeof(struct ip6_hdr)) {
		panic("too short mbuf on ipsec6_tunnel_validate");
	}
#endif
	if (nxt == IPPROTO_IPV4) {
		if (m->m_pkthdr.len < off + sizeof(struct ip)) {
			ipseclog((LOG_NOTICE, "ipsec6_tunnel_validate pkthdr %d off %d ip6hdr %zu", m->m_pkthdr.len, off, sizeof(struct ip6_hdr)));
			return 0;
		}
	} else if (nxt == IPPROTO_IPV6) {
		if (m->m_pkthdr.len < off + sizeof(struct ip6_hdr)) {
			ipseclog((LOG_NOTICE, "ipsec6_tunnel_validate pkthdr %d off %d ip6hdr %zu", m->m_pkthdr.len, off, sizeof(struct ip6_hdr)));
			return 0;
		}
	} else {
		ipseclog((LOG_NOTICE, "ipsec6_tunnel_validate invalid nxt(%u) protocol", nxt));
		return 0;
	}

	/* do not decapsulate if the SA is for transport mode only */
	if (sav->sah->saidx.mode == IPSEC_MODE_TRANSPORT) {
		return 0;
	}

	oip6 = mtod(m, struct ip6_hdr *);
	/* AF_INET should be supported, but at this moment we don't. */
	sin6 = (struct sockaddr_in6 *)&sav->sah->saidx.dst;
	if (sin6->sin6_family != AF_INET6) {
		return 0;
	}
	if (!IN6_ARE_ADDR_EQUAL(&oip6->ip6_dst, &sin6->sin6_addr)) {
		return 0;
	}

	if (sav->sah->ipsec_if != NULL) {
		// the ipsec interface SAs don't have a policies.
		if (nxt == IPPROTO_IPV4) {
			*ifamily = AF_INET;
		} else if (nxt == IPPROTO_IPV6) {
			*ifamily = AF_INET6;
		} else {
			return 0;
		}
		return 1;
	}

	/* XXX slow */
	bzero(&osrc, sizeof(osrc));
	bzero(&odst, sizeof(odst));
	osrc.sin6_family = odst.sin6_family = AF_INET6;
	osrc.sin6_len = odst.sin6_len = sizeof(struct sockaddr_in6);
	osrc.sin6_addr = oip6->ip6_src;
	odst.sin6_addr = oip6->ip6_dst;

	/*
	 * regarding to inner source address validation, see a long comment
	 * in ipsec4_tunnel_validate.
	 */

	if (nxt == IPPROTO_IPV4) {
		bzero(&i4src, sizeof(struct sockaddr_in));
		bzero(&i4dst, sizeof(struct sockaddr_in));
		i4src.sin_family = i4dst.sin_family = *ifamily = AF_INET;
		i4src.sin_len = i4dst.sin_len = sizeof(struct sockaddr_in);
		m_copydata(m, off + offsetof(struct ip, ip_src), sizeof(i4src.sin_addr),
		    (caddr_t)&i4src.sin_addr);
		m_copydata(m, off + offsetof(struct ip, ip_dst), sizeof(i4dst.sin_addr),
		    (caddr_t)&i4dst.sin_addr);
		sp = key_gettunnel((struct sockaddr *)&osrc, (struct sockaddr *)&odst,
		    (struct sockaddr *)&i4src, (struct sockaddr *)&i4dst);
	} else if (nxt == IPPROTO_IPV6) {
		bzero(&i6src, sizeof(struct sockaddr_in6));
		bzero(&i6dst, sizeof(struct sockaddr_in6));
		i6src.sin6_family = i6dst.sin6_family = *ifamily = AF_INET6;
		i6src.sin6_len = i6dst.sin6_len = sizeof(struct sockaddr_in6);
		m_copydata(m, off + offsetof(struct ip6_hdr, ip6_src), sizeof(i6src.sin6_addr),
		    (caddr_t)&i6src.sin6_addr);
		m_copydata(m, off + offsetof(struct ip6_hdr, ip6_dst), sizeof(i6dst.sin6_addr),
		    (caddr_t)&i6dst.sin6_addr);
		sp = key_gettunnel((struct sockaddr *)&osrc, (struct sockaddr *)&odst,
		    (struct sockaddr *)&i6src, (struct sockaddr *)&i6dst);
	} else {
		return 0;       /* unsupported family */
	}
	/*
	 * when there is no suitable inbound policy for the packet of the ipsec
	 * tunnel mode, the kernel never decapsulate the tunneled packet
	 * as the ipsec tunnel mode even when the system wide policy is "none".
	 * then the kernel leaves the generic tunnel module to process this
	 * packet.  if there is no rule of the generic tunnel, the packet
	 * is rejected and the statistics will be counted up.
	 */
	if (!sp) {
		return 0;
	}
	key_freesp(sp, KEY_SADB_UNLOCKED);

	return 1;
}

/*
 * Make a mbuf chain for encryption.
 * If the original mbuf chain contains a mbuf with a cluster,
 * allocate a new cluster and copy the data to the new cluster.
 * XXX: this hack is inefficient, but is necessary to handle cases
 * of TCP retransmission...
 */
struct mbuf *
ipsec_copypkt(struct mbuf *m)
{
	struct mbuf *n, **mpp, *mnew;

	for (n = m, mpp = &m; n; n = n->m_next) {
		if (n->m_flags & M_EXT) {
			/*
			 * Make a copy only if there are more than one references
			 * to the cluster.
			 * XXX: is this approach effective?
			 */
			if (
				m_get_ext_free(n) != NULL ||
				m_mclhasreference(n)
				) {
				int remain, copied;
				struct mbuf *mm;

				if (n->m_flags & M_PKTHDR) {
					MGETHDR(mnew, M_DONTWAIT, MT_HEADER); /* MAC-OK */
					if (mnew == NULL) {
						goto fail;
					}
					M_COPY_PKTHDR(mnew, n);
				} else {
					MGET(mnew, M_DONTWAIT, MT_DATA);
					if (mnew == NULL) {
						goto fail;
					}
				}
				mnew->m_len = 0;
				mm = mnew;

				/*
				 * Copy data. If we don't have enough space to
				 * store the whole data, allocate a cluster
				 * or additional mbufs.
				 * XXX: we don't use m_copyback(), since the
				 * function does not use clusters and thus is
				 * inefficient.
				 */
				remain = n->m_len;
				copied = 0;
				while (1) {
					int len;
					struct mbuf *mn;

					if (remain <= (mm->m_flags & M_PKTHDR ? MHLEN : MLEN)) {
						len = remain;
					} else { /* allocate a cluster */
						MCLGET(mm, M_DONTWAIT);
						if (!(mm->m_flags & M_EXT)) {
							m_free(mm);
							goto fail;
						}
						len = remain < MCLBYTES ?
						    remain : MCLBYTES;
					}

					bcopy(n->m_data + copied, mm->m_data,
					    len);

					copied += len;
					remain -= len;
					mm->m_len = len;

					if (remain <= 0) { /* completed? */
						break;
					}

					/* need another mbuf */
					MGETHDR(mn, M_DONTWAIT, MT_HEADER);     /* XXXMAC: tags copied next time in loop? */
					if (mn == NULL) {
						goto fail;
					}
					mn->m_pkthdr.rcvif = NULL;
					mm->m_next = mn;
					mm = mn;
				}

				/* adjust chain */
				mm->m_next = m_free(n);
				n = mm;
				*mpp = mnew;
				mpp = &n->m_next;

				continue;
			}
		}
		*mpp = n;
		mpp = &n->m_next;
	}

	return m;
fail:
	m_freem(m);
	return NULL;
}

/*
 * Tags are allocated as mbufs for now, since our minimum size is MLEN, we
 * should make use of up to that much space.
 */
#define IPSEC_TAG_HEADER \

struct ipsec_tag {
	struct socket                   *socket;
	u_int32_t                               history_count;
	struct ipsec_history    history[];
#if __arm__ && (__BIGGEST_ALIGNMENT__ > 4)
/* For the newer ARMv7k ABI where 64-bit types are 64-bit aligned, but pointers
 * are 32-bit:
 * Aligning to 64-bit since we case to m_tag which is 64-bit aligned.
 */
} __attribute__ ((aligned(8)));
#else
};
#endif

#define IPSEC_TAG_SIZE          (MLEN - sizeof(struct m_tag))
#define IPSEC_TAG_HDR_SIZE      (offsetof(struct ipsec_tag, history[0]))
#define IPSEC_HISTORY_MAX       ((IPSEC_TAG_SIZE - IPSEC_TAG_HDR_SIZE) / \
	                                                 sizeof(struct ipsec_history))

static struct ipsec_tag *
ipsec_addaux(
	struct mbuf *m)
{
	struct m_tag            *tag;

	/* Check if the tag already exists */
	tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_IPSEC, NULL);

	if (tag == NULL) {
		struct ipsec_tag        *itag;

		/* Allocate a tag */
		tag = m_tag_create(KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_IPSEC,
		    IPSEC_TAG_SIZE, M_DONTWAIT, m);

		if (tag) {
			itag = (struct ipsec_tag*)(tag + 1);
			itag->socket = 0;
			itag->history_count = 0;

			m_tag_prepend(m, tag);
		}
	}

	return tag ? (struct ipsec_tag*)(tag + 1) : NULL;
}

static struct ipsec_tag *
ipsec_findaux(
	struct mbuf *m)
{
	struct m_tag    *tag;

	tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_IPSEC, NULL);

	return tag ? (struct ipsec_tag*)(tag + 1) : NULL;
}

void
ipsec_delaux(
	struct mbuf *m)
{
	struct m_tag    *tag;

	tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_IPSEC, NULL);

	if (tag) {
		m_tag_delete(m, tag);
	}
}

/* if the aux buffer is unnecessary, nuke it. */
static void
ipsec_optaux(
	struct mbuf                     *m,
	struct ipsec_tag        *itag)
{
	if (itag && itag->socket == NULL && itag->history_count == 0) {
		m_tag_delete(m, ((struct m_tag*)itag) - 1);
	}
}

int
ipsec_setsocket(struct mbuf *m, struct socket *so)
{
	struct ipsec_tag        *tag;

	/* if so == NULL, don't insist on getting the aux mbuf */
	if (so) {
		tag = ipsec_addaux(m);
		if (!tag) {
			return ENOBUFS;
		}
	} else {
		tag = ipsec_findaux(m);
	}
	if (tag) {
		tag->socket = so;
		ipsec_optaux(m, tag);
	}
	return 0;
}

struct socket *
ipsec_getsocket(struct mbuf *m)
{
	struct ipsec_tag        *itag;

	itag = ipsec_findaux(m);
	if (itag) {
		return itag->socket;
	} else {
		return NULL;
	}
}

int
ipsec_addhist(
	struct mbuf *m,
	int proto,
	u_int32_t spi)
{
	struct ipsec_tag                *itag;
	struct ipsec_history    *p;
	itag = ipsec_addaux(m);
	if (!itag) {
		return ENOBUFS;
	}
	if (itag->history_count == IPSEC_HISTORY_MAX) {
		return ENOSPC;  /* XXX */
	}
	p = &itag->history[itag->history_count];
	itag->history_count++;

	bzero(p, sizeof(*p));
	p->ih_proto = proto;
	p->ih_spi = spi;

	return 0;
}

struct ipsec_history *
ipsec_gethist(
	struct mbuf *m,
	int *lenp)
{
	struct ipsec_tag        *itag;

	itag = ipsec_findaux(m);
	if (!itag) {
		return NULL;
	}
	if (itag->history_count == 0) {
		return NULL;
	}
	if (lenp) {
		*lenp = (int)(itag->history_count * sizeof(struct ipsec_history));
	}
	return itag->history;
}

void
ipsec_clearhist(
	struct mbuf *m)
{
	struct ipsec_tag        *itag;

	itag = ipsec_findaux(m);
	if (itag) {
		itag->history_count = 0;
	}
	ipsec_optaux(m, itag);
}

__private_extern__ boolean_t
ipsec_send_natt_keepalive(
	struct secasvar *sav)
{
	struct mbuf *m = NULL;
	int error = 0;
	int keepalive_interval = natt_keepalive_interval;

	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
	lck_mtx_lock(sadb_mutex);

	if (((esp_udp_encap_port & 0xFFFF) == 0 && sav->natt_encapsulated_src_port == 0) || sav->remote_ike_port == 0) {
		lck_mtx_unlock(sadb_mutex);
		return FALSE;
	}

	if (sav->natt_interval != 0) {
		keepalive_interval = (int)sav->natt_interval;
	}

	// natt timestamp may have changed... reverify
	if ((natt_now - sav->natt_last_activity) < keepalive_interval) {
		lck_mtx_unlock(sadb_mutex);
		return FALSE;
	}

	if (sav->flags & SADB_X_EXT_ESP_KEEPALIVE) {
		lck_mtx_unlock(sadb_mutex);
		return FALSE; // don't send these from the kernel
	}

	lck_mtx_unlock(sadb_mutex);

	m = m_gethdr(M_NOWAIT, MT_DATA);
	if (m == NULL) {
		return FALSE;
	}

	lck_mtx_lock(sadb_mutex);
	if (sav->sah->saidx.dst.ss_family == AF_INET) {
		struct ip_out_args ipoa = {};
		struct route ro = {};

		ipoa.ipoa_boundif = IFSCOPE_NONE;
		ipoa.ipoa_flags = IPOAF_SELECT_SRCIF;
		ipoa.ipoa_sotc = SO_TC_UNSPEC;
		ipoa.ipoa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;

		struct ip *ip = (__typeof__(ip))m_mtod(m);

		/*
		 * Type 2: a UDP packet complete with IP header.
		 * We must do this because UDP output requires
		 * an inpcb which we don't have. UDP packet
		 * contains one byte payload. The byte is set
		 * to 0xFF.
		 */
		struct udphdr *uh = (__typeof__(uh))(void *)((char *)m_mtod(m) + sizeof(*ip));
		m->m_len = sizeof(struct udpiphdr) + 1;
		bzero(m_mtod(m), m->m_len);
		m->m_pkthdr.len = m->m_len;

		ip->ip_len = (u_short)m->m_len;
		ip->ip_ttl = (u_char)ip_defttl;
		ip->ip_p = IPPROTO_UDP;
		if (sav->sah->dir != IPSEC_DIR_INBOUND) {
			ip->ip_src = ((struct sockaddr_in*)&sav->sah->saidx.src)->sin_addr;
			ip->ip_dst = ((struct sockaddr_in*)&sav->sah->saidx.dst)->sin_addr;
		} else {
			ip->ip_src = ((struct sockaddr_in*)&sav->sah->saidx.dst)->sin_addr;
			ip->ip_dst = ((struct sockaddr_in*)&sav->sah->saidx.src)->sin_addr;
		}
		if (sav->natt_encapsulated_src_port != 0) {
			uh->uh_sport = (u_short)sav->natt_encapsulated_src_port;
		} else {
			uh->uh_sport = htons((u_short)esp_udp_encap_port);
		}
		uh->uh_sport = htons((u_short)esp_udp_encap_port);
		uh->uh_dport = htons(sav->remote_ike_port);
		uh->uh_ulen = htons(1 + sizeof(*uh));
		uh->uh_sum = 0;
		*(u_int8_t*)((char*)m_mtod(m) + sizeof(*ip) + sizeof(*uh)) = 0xFF;

		if (ROUTE_UNUSABLE(&sav->sah->sa_route) ||
		    rt_key(sav->sah->sa_route.ro_rt)->sa_family != AF_INET) {
			ROUTE_RELEASE(&sav->sah->sa_route);
		}

		route_copyout(&ro, (struct route *)&sav->sah->sa_route, sizeof(struct route));
		lck_mtx_unlock(sadb_mutex);

		necp_mark_packet_as_keepalive(m, TRUE);
		error = ip_output(m, NULL, &ro, IP_OUTARGS | IP_NOIPSEC, NULL, &ipoa);

		lck_mtx_lock(sadb_mutex);
		route_copyin(&ro, (struct route *)&sav->sah->sa_route, sizeof(struct route));
	} else if (sav->sah->saidx.dst.ss_family == AF_INET6) {
		struct ip6_out_args ip6oa = {};
		struct route_in6 ro6 = {};

		ip6oa.ip6oa_flowadv.code = 0;
		ip6oa.ip6oa_flags = IP6OAF_SELECT_SRCIF | IP6OAF_BOUND_SRCADDR;
		if (sav->sah->outgoing_if) {
			ip6oa.ip6oa_boundif = sav->sah->outgoing_if;
			ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
		}

		struct ip6_hdr *ip6 = (__typeof__(ip6))m_mtod(m);

		/*
		 * Type 2: a UDP packet complete with IPv6 header.
		 * We must do this because UDP output requires
		 * an inpcb which we don't have. UDP packet
		 * contains one byte payload. The byte is set
		 * to 0xFF.
		 */
		struct udphdr *uh = (__typeof__(uh))(void *)((char *)m_mtod(m) + sizeof(*ip6));
		m->m_len = sizeof(struct udphdr) + sizeof(struct ip6_hdr) + 1;
		bzero(m_mtod(m), m->m_len);
		m->m_pkthdr.len = m->m_len;

		ip6->ip6_flow = 0;
		ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
		ip6->ip6_vfc |= IPV6_VERSION;
		ip6->ip6_nxt = IPPROTO_UDP;
		ip6->ip6_hlim = (u_int8_t)ip6_defhlim;
		ip6->ip6_plen = htons(sizeof(struct udphdr) + 1);
		if (sav->sah->dir != IPSEC_DIR_INBOUND) {
			ip6->ip6_src = ((struct sockaddr_in6 *)&sav->sah->saidx.src)->sin6_addr;
			ip6->ip6_dst = ((struct sockaddr_in6 *)&sav->sah->saidx.dst)->sin6_addr;
		} else {
			ip6->ip6_src = ((struct sockaddr_in6 *)&sav->sah->saidx.dst)->sin6_addr;
			ip6->ip6_dst = ((struct sockaddr_in6 *)&sav->sah->saidx.src)->sin6_addr;
		}

		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
			ip6->ip6_src.s6_addr16[1] = 0;
		}
		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
			ip6->ip6_dst.s6_addr16[1] = 0;
		}

		if (sav->natt_encapsulated_src_port != 0) {
			uh->uh_sport = (u_short)sav->natt_encapsulated_src_port;
		} else {
			uh->uh_sport = htons((u_short)esp_udp_encap_port);
		}
		uh->uh_dport = htons(sav->remote_ike_port);
		uh->uh_ulen = htons(1 + sizeof(*uh));
		*(u_int8_t*)((char*)m_mtod(m) + sizeof(*ip6) + sizeof(*uh)) = 0xFF;
		uh->uh_sum = in6_pseudo(&ip6->ip6_src, &ip6->ip6_dst, htonl(ntohs(uh->uh_ulen) + IPPROTO_UDP));
		m->m_pkthdr.csum_flags = (CSUM_UDPIPV6 | CSUM_ZERO_INVERT);
		m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);

		if (ROUTE_UNUSABLE(&sav->sah->sa_route) ||
		    rt_key(sav->sah->sa_route.ro_rt)->sa_family != AF_INET6) {
			ROUTE_RELEASE(&sav->sah->sa_route);
		}

		route_copyout((struct route *)&ro6, (struct route *)&sav->sah->sa_route, sizeof(struct route_in6));
		lck_mtx_unlock(sadb_mutex);

		necp_mark_packet_as_keepalive(m, TRUE);
		error = ip6_output(m, NULL, &ro6, IPV6_OUTARGS, NULL, NULL, &ip6oa);

		lck_mtx_lock(sadb_mutex);
		route_copyin((struct route *)&ro6, (struct route *)&sav->sah->sa_route, sizeof(struct route_in6));
	} else {
		ipseclog((LOG_ERR, "nat keepalive: invalid address family %u\n", sav->sah->saidx.dst.ss_family));
		lck_mtx_unlock(sadb_mutex);
		m_freem(m);
		return FALSE;
	}

	if (error == 0) {
		sav->natt_last_activity = natt_now;
		lck_mtx_unlock(sadb_mutex);
		return TRUE;
	}

	lck_mtx_unlock(sadb_mutex);
	return FALSE;
}

__private_extern__ bool
ipsec_fill_offload_frame(ifnet_t ifp,
    struct secasvar *sav,
    struct ifnet_keepalive_offload_frame *frame,
    size_t frame_data_offset)
{
	u_int8_t *data = NULL;
	struct ip *ip = NULL;
	struct udphdr *uh = NULL;

	if (sav == NULL || sav->sah == NULL || frame == NULL ||
	    (ifp != NULL && ifp->if_index != sav->sah->outgoing_if) ||
	    sav->sah->saidx.dst.ss_family != AF_INET ||
	    !(sav->flags & SADB_X_EXT_NATT) ||
	    !(sav->flags & SADB_X_EXT_NATT_KEEPALIVE) ||
	    !(sav->flags & SADB_X_EXT_NATT_KEEPALIVE_OFFLOAD) ||
	    sav->flags & SADB_X_EXT_ESP_KEEPALIVE ||
	    ((esp_udp_encap_port & 0xFFFF) == 0 && sav->natt_encapsulated_src_port == 0) ||
	    sav->remote_ike_port == 0 ||
	    (natt_keepalive_interval == 0 && sav->natt_interval == 0 && sav->natt_offload_interval == 0)) {
		/* SA is not eligible for keepalive offload on this interface */
		return FALSE;
	}

	if (frame_data_offset + sizeof(struct udpiphdr) + 1 >
	    IFNET_KEEPALIVE_OFFLOAD_FRAME_DATA_SIZE) {
		/* Not enough room in this data frame */
		return FALSE;
	}

	data = frame->data;
	ip = (__typeof__(ip))(void *)(data + frame_data_offset);
	uh = (__typeof__(uh))(void *)(data + frame_data_offset + sizeof(*ip));

	frame->length = (u_int8_t)(frame_data_offset + sizeof(struct udpiphdr) + 1);
	frame->type = IFNET_KEEPALIVE_OFFLOAD_FRAME_IPSEC;
	frame->ether_type = IFNET_KEEPALIVE_OFFLOAD_FRAME_ETHERTYPE_IPV4;

	bzero(data, IFNET_KEEPALIVE_OFFLOAD_FRAME_DATA_SIZE);

	ip->ip_v = IPVERSION;
	ip->ip_hl = sizeof(struct ip) >> 2;
	ip->ip_off &= htons(~IP_OFFMASK);
	ip->ip_off &= htons(~IP_MF);
	switch (ip4_ipsec_dfbit) {
	case 0:         /* clear DF bit */
		ip->ip_off &= htons(~IP_DF);
		break;
	case 1:         /* set DF bit */
		ip->ip_off |= htons(IP_DF);
		break;
	default:                /* copy DF bit */
		break;
	}
	ip->ip_len = htons(sizeof(struct udpiphdr) + 1);
	if (rfc6864 && IP_OFF_IS_ATOMIC(htons(ip->ip_off))) {
		ip->ip_id = 0;
	} else {
		ip->ip_id = ip_randomid();
	}
	ip->ip_ttl = (u_char)ip_defttl;
	ip->ip_p = IPPROTO_UDP;
	ip->ip_sum = 0;
	if (sav->sah->dir != IPSEC_DIR_INBOUND) {
		ip->ip_src = ((struct sockaddr_in*)&sav->sah->saidx.src)->sin_addr;
		ip->ip_dst = ((struct sockaddr_in*)&sav->sah->saidx.dst)->sin_addr;
	} else {
		ip->ip_src = ((struct sockaddr_in*)&sav->sah->saidx.dst)->sin_addr;
		ip->ip_dst = ((struct sockaddr_in*)&sav->sah->saidx.src)->sin_addr;
	}
	ip->ip_sum = in_cksum_hdr_opt(ip);
	/* Fill out the UDP header */
	if (sav->natt_encapsulated_src_port != 0) {
		uh->uh_sport = (u_short)sav->natt_encapsulated_src_port;
	} else {
		uh->uh_sport = htons((u_short)esp_udp_encap_port);
	}
	uh->uh_dport = htons(sav->remote_ike_port);
	uh->uh_ulen = htons(1 + sizeof(*uh));
	uh->uh_sum = 0;
	*(u_int8_t*)(data + frame_data_offset + sizeof(*ip) + sizeof(*uh)) = 0xFF;

	if (sav->natt_offload_interval != 0) {
		frame->interval = sav->natt_offload_interval;
	} else if (sav->natt_interval != 0) {
		frame->interval = sav->natt_interval;
	} else {
		frame->interval = (u_int16_t)natt_keepalive_interval;
	}
	return TRUE;
}

static int
sysctl_ipsec_wake_packet SYSCTL_HANDLER_ARGS
{
 #pragma unused(oidp, arg1, arg2)
	if (req->newptr != USER_ADDR_NULL) {
		ipseclog((LOG_ERR, "ipsec: invalid parameters"));
		return EINVAL;
	}

	struct proc *p = current_proc();
	if (p != NULL) {
		uid_t uid = kauth_cred_getuid(kauth_cred_get());
		if (uid != 0 && priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_IPSEC_WAKE_PACKET, 0) != 0) {
			ipseclog((LOG_ERR, "process does not hold necessary entitlement to get ipsec wake packet"));
			return EPERM;
		}

		int result = sysctl_io_opaque(req, &ipsec_wake_pkt, sizeof(ipsec_wake_pkt), NULL);

		ipseclog((LOG_NOTICE, "%s: uuid %s spi %u seq %u len %u result %d",
		    __func__,
		    ipsec_wake_pkt.wake_uuid,
		    ipsec_wake_pkt.wake_pkt_spi,
		    ipsec_wake_pkt.wake_pkt_seq,
		    ipsec_wake_pkt.wake_pkt_len,
		    result));

		return result;
	}

	return EINVAL;
}

SYSCTL_PROC(_net_link_generic_system, OID_AUTO, ipsec_wake_pkt, CTLTYPE_STRUCT | CTLFLAG_RD |
    CTLFLAG_LOCKED, 0, 0, &sysctl_ipsec_wake_packet, "S,ipsec wake packet", "");

void
ipsec_save_wake_packet(struct mbuf *wake_mbuf, u_int32_t spi, u_int32_t seq)
{
	if (wake_mbuf == NULL) {
		ipseclog((LOG_ERR, "ipsec: bad wake packet"));
		return;
	}

	lck_mtx_lock(sadb_mutex);
	if (__probable(!ipsec_save_wake_pkt)) {
		goto done;
	}

	u_int16_t max_len = (wake_mbuf->m_pkthdr.len > IPSEC_MAX_WAKE_PKT_LEN) ? IPSEC_MAX_WAKE_PKT_LEN : (u_int16_t)wake_mbuf->m_pkthdr.len;
	m_copydata(wake_mbuf, 0, max_len, (void *)ipsec_wake_pkt.wake_pkt);
	ipsec_wake_pkt.wake_pkt_len = max_len;

	ipsec_wake_pkt.wake_pkt_spi = spi;
	ipsec_wake_pkt.wake_pkt_seq = seq;

	ipseclog((LOG_NOTICE, "%s: uuid %s spi %u seq %u len %u",
	    __func__,
	    ipsec_wake_pkt.wake_uuid,
	    ipsec_wake_pkt.wake_pkt_spi,
	    ipsec_wake_pkt.wake_pkt_seq,
	    ipsec_wake_pkt.wake_pkt_len));

	struct kev_msg ev_msg;
	bzero(&ev_msg, sizeof(ev_msg));

	ev_msg.vendor_code      = KEV_VENDOR_APPLE;
	ev_msg.kev_class        = KEV_NETWORK_CLASS;
	ev_msg.kev_subclass     = KEV_IPSEC_SUBCLASS;
	ev_msg.event_code       = KEV_IPSEC_WAKE_PACKET;

	struct ipsec_wake_pkt_event_data event_data;
	strlcpy(event_data.wake_uuid, ipsec_wake_pkt.wake_uuid, sizeof(event_data.wake_uuid));
	ev_msg.dv[0].data_ptr           = &event_data;
	ev_msg.dv[0].data_length        = sizeof(event_data);

	int result = kev_post_msg(&ev_msg);
	if (result != 0) {
		os_log_error(OS_LOG_DEFAULT, "%s: kev_post_msg() failed with error %d for wake uuid %s",
		    __func__, result, ipsec_wake_pkt.wake_uuid);
	}

	ipsec_save_wake_pkt = false;
done:
	lck_mtx_unlock(sadb_mutex);
	return;
}

static void
ipsec_get_local_ports(void)
{
	errno_t error;
	ifnet_t *ifp_list;
	uint32_t count, i;
	static uint8_t port_bitmap[bitstr_size(IP_PORTRANGE_SIZE)];

	error = ifnet_list_get_all(IFNET_FAMILY_IPSEC, &ifp_list, &count);
	if (error != 0) {
		os_log_error(OS_LOG_DEFAULT, "%s: ifnet_list_get_all() failed %d",
		    __func__, error);
		return;
	}
	for (i = 0; i < count; i++) {
		ifnet_t ifp = ifp_list[i];

		/*
		 * Get all the TCP and UDP ports for IPv4 and IPv6
		 */
		error = ifnet_get_local_ports_extended(ifp, PF_UNSPEC,
		    IFNET_GET_LOCAL_PORTS_WILDCARDOK |
		    IFNET_GET_LOCAL_PORTS_NOWAKEUPOK |
		    IFNET_GET_LOCAL_PORTS_ANYTCPSTATEOK,
		    port_bitmap);
		if (error != 0) {
			os_log_error(OS_LOG_DEFAULT, "%s: ifnet_get_local_ports_extended(%s) failed %d",
			    __func__, if_name(ifp), error);
		}
	}
	ifnet_list_free(ifp_list);
}

static IOReturn
ipsec_sleep_wake_handler(void *target, void *refCon, UInt32 messageType,
    void *provider, void *messageArgument, vm_size_t argSize)
{
#pragma unused(target, refCon, provider, messageArgument, argSize)
	switch (messageType) {
	case kIOMessageSystemWillSleep:
	{
		ipsec_get_local_ports();
		ipsec_save_wake_pkt = false;
		memset(&ipsec_wake_pkt, 0, sizeof(ipsec_wake_pkt));
		IOPMCopySleepWakeUUIDKey(ipsec_wake_pkt.wake_uuid,
		    sizeof(ipsec_wake_pkt.wake_uuid));
		ipseclog((LOG_NOTICE,
		    "ipsec: system will sleep, uuid: %s", ipsec_wake_pkt.wake_uuid));
		break;
	}
	case kIOMessageSystemHasPoweredOn:
	{
		char wake_reason[128] = {0};
		size_t size = sizeof(wake_reason);
		if (kernel_sysctlbyname("kern.wakereason", wake_reason, &size, NULL, 0) == 0) {
			if (strnstr(wake_reason, "wlan", size) == 0 ||
			    strnstr(wake_reason, "WL.OutboxNotEmpty", size) == 0 ||
			    strnstr(wake_reason, "baseband", size) == 0 ||
			    strnstr(wake_reason, "bluetooth", size) == 0 ||
			    strnstr(wake_reason, "BT.OutboxNotEmpty", size) == 0) {
				ipsec_save_wake_pkt = true;
				ipseclog((LOG_NOTICE,
				    "ipsec: system has powered on, uuid: %s reason %s", ipsec_wake_pkt.wake_uuid, wake_reason));
			}
		}
		break;
	}
	default:
		break;
	}

	return IOPMAckImplied;
}

void
ipsec_monitor_sleep_wake(void)
{
	LCK_MTX_ASSERT(sadb_mutex, LCK_MTX_ASSERT_OWNED);

	if (sleep_wake_handle == NULL) {
		sleep_wake_handle = registerSleepWakeInterest(ipsec_sleep_wake_handler,
		    NULL, NULL);
		if (sleep_wake_handle != NULL) {
			ipseclog((LOG_INFO,
			    "ipsec: monitoring sleep wake"));
		}
	}
}