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
/*
 * Copyright (c) 2014-2024 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@
 */

#include <string.h>
#include <sys/systm.h>
#include <sys/types.h>
#include <sys/syslog.h>
#include <sys/queue.h>
#include <sys/malloc.h>
#include <sys/kernel.h>
#include <sys/kern_control.h>
#include <sys/mbuf.h>
#include <sys/kpi_mbuf.h>
#include <sys/sysctl.h>
#include <sys/priv.h>
#include <sys/kern_event.h>
#include <sys/sysproto.h>
#include <net/network_agent.h>
#include <net/if_var.h>
#include <net/necp.h>
#include <os/log.h>

u_int32_t netagent_debug = LOG_NOTICE; // 0=None, 1=Basic

SYSCTL_NODE(_net, OID_AUTO, netagent, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "NetworkAgent");
SYSCTL_INT(_net_netagent, OID_AUTO, debug, CTLFLAG_LOCKED | CTLFLAG_RW, &netagent_debug, 0, "");

static int netagent_registered_count = 0;
SYSCTL_INT(_net_netagent, OID_AUTO, registered_count, CTLFLAG_RD | CTLFLAG_LOCKED,
    &netagent_registered_count, 0, "");

static int netagent_active_count = 0;
SYSCTL_INT(_net_netagent, OID_AUTO, active_count, CTLFLAG_RD | CTLFLAG_LOCKED,
    &netagent_active_count, 0, "");

#define NETAGENTLOG(level, format, ...) do {                                             \
    if (level <= netagent_debug) {                                                       \
	if (level == LOG_ERR) {                                                          \
	    os_log_error(OS_LOG_DEFAULT, "%s: " format "\n", __FUNCTION__, __VA_ARGS__); \
	} else {                                                                         \
	    os_log(OS_LOG_DEFAULT, "%s: " format "\n", __FUNCTION__, __VA_ARGS__);       \
	}                                                                                \
    }                                                                                    \
} while (0)

#define NETAGENTLOG0(level, msg) do {                                                    \
    if (level <= netagent_debug) {                                                       \
	        if (level == LOG_ERR) {                                                          \
	    os_log_error(OS_LOG_DEFAULT, "%s: %s\n", __FUNCTION__, msg);                 \
	} else {                                                                         \
	    os_log(OS_LOG_DEFAULT, "%s: %s\n", __FUNCTION__, msg);                       \
	}                                                                                \
    }                                                                                    \
} while (0)

#if __has_ptrcheck
static inline
__attribute__((always_inline)) __pure
uint8_t * __bidi_indexable
netagent_get_data(const struct netagent *agent)
{
	if (agent == NULL) {
		return NULL;
	}

	return __unsafe_forge_bidi_indexable(uint8_t *, agent->netagent_data, agent->netagent_data_size);
}
#else
#define netagent_get_data(agent) ((agent)->netagent_data)
#endif

#if __has_ptrcheck
static inline
__attribute__((always_inline)) __pure
uint8_t * __bidi_indexable
netagent_group_message_get_members(const struct netagent_client_group_message *msg, size_t members_length)
{
	if (msg == NULL) {
		return NULL;
	}

	return __unsafe_forge_bidi_indexable(uint8_t *, msg->group_members, members_length);
}
#else
#define netagent_group_message_get_members(msg, members_length) ((msg)->group_members)
#endif

#if __has_ptrcheck
static inline
__attribute__((always_inline)) __pure
uint8_t * __bidi_indexable
netagent_assign_message_get_necp_result(const struct netagent_assign_nexus_message *msg, size_t result_length)
{
	if (msg == NULL) {
		return NULL;
	}

	return __unsafe_forge_bidi_indexable(uint8_t *, msg->assign_necp_results, result_length);
}
#else
#define netagent_assign_message_get_necp_result(msg, result_length) ((msg)->assign_necp_results)
#endif

struct netagent_client {
	LIST_ENTRY(netagent_client) client_chain;
	uuid_t client_id;
	uuid_t client_proc_uuid;
	pid_t client_pid;
};

LIST_HEAD(netagent_client_list_s, netagent_client);

struct netagent_token {
	TAILQ_ENTRY(netagent_token) token_chain;
	u_int32_t token_length;
	u_int8_t *  __indexable token_bytes;
};

TAILQ_HEAD(netagent_token_list_s, netagent_token);

#define NETAGENT_MAX_CLIENT_ERROR_COUNT 32

struct netagent_registration {
	LIST_ENTRY(netagent_registration) global_chain;
	TAILQ_ENTRY(netagent_registration) session_chain;
	lck_rw_t agent_lock;
	u_int32_t control_unit;
	netagent_event_f event_handler;
	void *event_context;
	u_int32_t generation;
	u_int64_t use_count;
	u_int64_t need_tokens_event_deadline;
	u_int32_t token_count;
	u_int32_t token_low_water;
	int32_t last_client_error;
	u_int32_t client_error_count;
	u_int8_t allow_multiple_registrations;
	u_int8_t __pad_bytes[2];
	struct netagent_token_list_s token_list;
	struct netagent_client_list_s pending_triggers_list;
	size_t netagent_alloc_size;
	struct netagent *netagent __sized_by(netagent_alloc_size);
};

struct netagent_session {
	u_int32_t control_unit; // A control unit of 0 indicates an agent owned by the kernel
	lck_mtx_t session_lock;
	TAILQ_HEAD(_netagent_registration_list, netagent_registration) registrations;

	netagent_event_f event_handler;
	void *event_context;
	bool allow_multiple_registrations;
};

typedef enum {
	kNetagentErrorDomainPOSIX                       = 0,
	kNetagentErrorDomainUserDefined         = 1,
} netagent_error_domain_t;

static LIST_HEAD(_netagent_list, netagent_registration) shared_netagent_list =
    LIST_HEAD_INITIALIZER(master_netagent_list);

// Protected by netagent_list_lock
static u_int32_t g_next_generation = 1;

static kern_ctl_ref     netagent_kctlref;
static u_int32_t        netagent_family;
static LCK_GRP_DECLARE(netagent_mtx_grp, NETAGENT_CONTROL_NAME);
static LCK_RW_DECLARE(netagent_list_lock, &netagent_mtx_grp);

#define NETAGENT_LIST_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&netagent_list_lock)
#define NETAGENT_LIST_LOCK_SHARED() lck_rw_lock_shared(&netagent_list_lock)
#define NETAGENT_LIST_UNLOCK() lck_rw_done(&netagent_list_lock)
#define NETAGENT_LIST_ASSERT_LOCKED() LCK_RW_ASSERT(&netagent_list_lock, LCK_RW_ASSERT_HELD)

#define NETAGENT_SESSION_LOCK(session) lck_mtx_lock(&session->session_lock)
#define NETAGENT_SESSION_UNLOCK(session) lck_mtx_unlock(&session->session_lock)
#define NETAGENT_SESSION_ASSERT_LOCKED(session) LCK_MTX_ASSERT(&session->session_lock, LCK_MTX_ASSERT_OWNED)

#define NETAGENT_LOCK_EXCLUSIVE(registration) lck_rw_lock_exclusive(&registration->agent_lock)
#define NETAGENT_LOCK_SHARED(registration) lck_rw_lock_shared(&registration->agent_lock)
#define NETAGENT_LOCK_SHARED_TO_EXCLUSIVE(registration) lck_rw_lock_shared_to_exclusive(&registration->agent_lock)
#define NETAGENT_UNLOCK(registration) lck_rw_done(&registration->agent_lock)
#define NETAGENT_ASSERT_LOCKED(registration) LCK_RW_ASSERT(&registration->agent_lock, LCK_RW_ASSERT_HELD)

// Locking Notes

// Precedence, where 1 is the first lock that must be taken
// 1. NETAGENT_LIST_LOCK - protects shared_netagent_list
// 2. NETAGENT_SESSION_LOCK - protects the session->registrations list
// 3. NETAGENT_LOCK -> protects values in a registration

static errno_t netagent_register_control(void);
static errno_t netagent_ctl_connect(kern_ctl_ref kctlref, struct sockaddr_ctl *sac,
    void **unitinfo);
static errno_t netagent_ctl_disconnect(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo);
static errno_t netagent_ctl_send(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo,
    mbuf_t m, int flags);
static void netagent_ctl_rcvd(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int flags);
static errno_t netagent_ctl_getopt(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo,
    int opt, void * __sized_by(*len)data, size_t *len);
static errno_t netagent_ctl_setopt(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo,
    int opt, void * __sized_by(len)data, size_t len);

static int netagent_send_ctl_data(u_int32_t control_unit,
    u_int8_t *__sized_by(buffer_size)buffer, size_t buffer_size);

static struct netagent_session *netagent_create_session(u_int32_t control_unit);
static void netagent_delete_session(struct netagent_session *session);

// Register
static void netagent_handle_register_message(struct netagent_session *session, u_int32_t message_id,
    size_t payload_length, mbuf_t packet, size_t offset);
static errno_t netagent_handle_register_setopt(struct netagent_session *session, u_int8_t *payload,
    size_t payload_length);

// Unregister
static void netagent_handle_unregister_message(struct netagent_session *session, u_int32_t message_id,
    size_t payload_length, mbuf_t packet, size_t offset);
static errno_t netagent_handle_unregister_setopt(struct netagent_session *session, u_int8_t * __sized_by(payload_length)payload,
    size_t payload_length);
static errno_t netagent_handle_unregister_all_setopt(struct netagent_session *session, u_int8_t * __sized_by(payload_length)payload,
    size_t payload_length);

// Update
static void netagent_handle_update_message(struct netagent_session *session, u_int32_t message_id,
    size_t payload_length, mbuf_t packet, size_t offset);
static errno_t netagent_handle_update_setopt(struct netagent_session *session, u_int8_t *payload,
    size_t payload_length);

// Assign nexus
static void netagent_handle_assign_nexus_message(struct netagent_session *session, u_int32_t message_id,
    size_t payload_length, mbuf_t packet, size_t offset);
static errno_t netagent_handle_assign_nexus_setopt(struct netagent_session *session, u_int8_t * __sized_by(payload_length)payload,
    size_t payload_length);

// Assign group
static errno_t netagent_handle_assign_group_setopt(struct netagent_session *session, u_int8_t * __sized_by(payload_length)payload,
    size_t payload_length);

// Set/get assert count
static errno_t netagent_handle_use_count_setopt(struct netagent_session *session, u_int8_t * __sized_by(payload_length)payload, size_t payload_length);
static errno_t netagent_handle_use_count_getopt(struct netagent_session *session, u_int8_t * __sized_by(*buffer_length)buffer, size_t *buffer_length);

// Manage tokens
static errno_t netagent_handle_add_token_setopt(struct netagent_session *session, u_int8_t * __sized_by(token_length)token, size_t token_length);
static errno_t netagent_handle_flush_tokens_setopt(struct netagent_session *session, u_int8_t * __sized_by(payload_length)payload, size_t payload_length);
static errno_t netagent_handle_token_count_getopt(struct netagent_session *session, u_int8_t * __sized_by(*buffer_length)buffer, size_t *buffer_length);
static errno_t netagent_handle_token_low_water_setopt(struct netagent_session *session, u_int8_t * __sized_by(buffer_length)buffer, size_t buffer_length);
static errno_t netagent_handle_token_low_water_getopt(struct netagent_session *session, u_int8_t * __sized_by(*buffer_length)buffer, size_t *buffer_length);

// Client error
static errno_t netagent_handle_reset_client_error_setopt(struct netagent_session *session, u_int8_t * __sized_by(payload_length)payload, size_t payload_length);

// Enable session mode
static errno_t netagent_handle_enable_session_mode_setopt(struct netagent_session *session, u_int8_t *payload, size_t payload_length);

// Requires list lock being held
static struct netagent_registration *netagent_find_agent_with_uuid_and_lock(uuid_t uuid, bool exclusively, bool ignore_lock);

// Requires session lock being held
static struct netagent_registration *
netagent_session_find_agent_with_uuid_and_lock(struct netagent_session *session, uuid_t uuid, bool exclusively, bool ignore_lock);

// Requires session lock being held, and single agent only
static struct netagent_registration *
netagent_session_access_agent_with_lock(struct netagent_session *session, bool exclusively, bool ignore_lock);

errno_t
netagent_init(void)
{
	return netagent_register_control();
}

static errno_t
netagent_register_control(void)
{
	struct kern_ctl_reg     kern_ctl;
	errno_t                 result = 0;

	// Find a unique value for our interface family
	result = mbuf_tag_id_find(NETAGENT_CONTROL_NAME, &netagent_family);
	if (result != 0) {
		NETAGENTLOG(LOG_ERR, "mbuf_tag_id_find_internal failed: %d", result);
		return result;
	}

	bzero(&kern_ctl, sizeof(kern_ctl));
	strlcpy(kern_ctl.ctl_name, NETAGENT_CONTROL_NAME, sizeof(kern_ctl.ctl_name));
	kern_ctl.ctl_name[sizeof(kern_ctl.ctl_name) - 1] = 0;
	kern_ctl.ctl_flags = CTL_FLAG_PRIVILEGED; // Require root
	kern_ctl.ctl_sendsize = 64 * 1024;
	kern_ctl.ctl_recvsize = 64 * 1024;
	kern_ctl.ctl_connect = netagent_ctl_connect;
	kern_ctl.ctl_disconnect = netagent_ctl_disconnect;
	kern_ctl.ctl_send = netagent_ctl_send;
	kern_ctl.ctl_rcvd = netagent_ctl_rcvd;
	kern_ctl.ctl_setopt = netagent_ctl_setopt;
	kern_ctl.ctl_getopt = netagent_ctl_getopt;

	result = ctl_register(&kern_ctl, &netagent_kctlref);
	if (result != 0) {
		NETAGENTLOG(LOG_ERR, "ctl_register failed: %d", result);
		return result;
	}

	return 0;
}

static errno_t
netagent_ctl_connect(kern_ctl_ref kctlref, struct sockaddr_ctl *sac, void **unitinfo)
{
#pragma unused(kctlref)
	*unitinfo = netagent_create_session(sac->sc_unit);
	if (*unitinfo == NULL) {
		// Could not allocate session
		return ENOBUFS;
	}

	return 0;
}

static errno_t
netagent_ctl_disconnect(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo)
{
#pragma unused(kctlref, unit)
	struct netagent_session *session = (struct netagent_session *)unitinfo;
	if (session != NULL) {
		netagent_delete_session(session);
	}

	return 0;
}

// Kernel events
static void
netagent_post_event(uuid_t agent_uuid, u_int32_t event_code, bool update_necp, bool should_update_immediately)
{
	if (update_necp) {
		necp_update_all_clients_immediately_if_needed(should_update_immediately);
	}

	struct kev_msg ev_msg;
	memset(&ev_msg, 0, sizeof(ev_msg));

	struct kev_netagent_data event_data;

	ev_msg.vendor_code      = KEV_VENDOR_APPLE;
	ev_msg.kev_class        = KEV_NETWORK_CLASS;
	ev_msg.kev_subclass     = KEV_NETAGENT_SUBCLASS;
	ev_msg.event_code       = event_code;

	uuid_copy(event_data.netagent_uuid, agent_uuid);
	ev_msg.dv[0].data_ptr    = &event_data;
	ev_msg.dv[0].data_length = sizeof(event_data);

	kev_post_msg(&ev_msg);
}

// Message handling
static u_int8_t * __indexable
netagent_buffer_write_message_header(u_int8_t * __sized_by(sizeof(struct netagent_message_header) + payload_length)buffer, u_int8_t message_type, u_int8_t flags, u_int32_t message_id, u_int32_t error, size_t payload_length)
{
	memset(buffer, 0, sizeof(struct netagent_message_header));
	((struct netagent_message_header *)(void *)buffer)->message_type = message_type;
	((struct netagent_message_header *)(void *)buffer)->message_flags = flags;
	((struct netagent_message_header *)(void *)buffer)->message_id = message_id;
	((struct netagent_message_header *)(void *)buffer)->message_error = error;
	((struct netagent_message_header *)(void *)buffer)->message_payload_length = (u_int32_t)payload_length;
	return payload_length ? buffer + sizeof(struct netagent_message_header) : NULL;
}

static u_int8_t * __indexable
netagent_buffer_write_session_message_header(u_int8_t * __sized_by(sizeof(struct netagent_session_message_header) + payload_length)buffer, u_int8_t message_type, u_int8_t flags, u_int32_t message_id, u_int32_t error, uuid_t message_agent_id, size_t payload_length)
{
	memset(buffer, 0, sizeof(struct netagent_session_message_header));
	((struct netagent_session_message_header *)(void *)buffer)->message_type = message_type;
	((struct netagent_session_message_header *)(void *)buffer)->message_flags = flags;
	((struct netagent_session_message_header *)(void *)buffer)->message_id = message_id;
	((struct netagent_session_message_header *)(void *)buffer)->message_error = error;
	uuid_copy(((struct netagent_session_message_header *)(void *)buffer)->message_agent_id, message_agent_id);
	((struct netagent_session_message_header *)(void *)buffer)->message_payload_length = (u_int32_t)payload_length;
	return payload_length ? buffer + sizeof(struct netagent_session_message_header) : NULL;
}

static int
netagent_send_ctl_data(u_int32_t control_unit, u_int8_t *__sized_by(buffer_size) buffer, size_t buffer_size)
{
	if (netagent_kctlref == NULL || control_unit == 0 || buffer == NULL || buffer_size == 0) {
		return EINVAL;
	}

	return ctl_enqueuedata(netagent_kctlref, control_unit, buffer, buffer_size, CTL_DATA_EOR);
}

static int
netagent_send_trigger(struct netagent_registration *registration, struct proc *p, u_int32_t flags, u_int8_t trigger_type)
{
	int error = 0;
	struct netagent_trigger_message *trigger_message = NULL;
	const bool session_mode = registration->allow_multiple_registrations;
	const size_t header_size = (session_mode ? sizeof(struct netagent_session_message_header) : sizeof(struct netagent_message_header));
	u_int8_t *trigger = NULL;
	size_t trigger_size = header_size + sizeof(struct netagent_trigger_message);
	trigger = (u_int8_t *)kalloc_data(trigger_size, Z_WAITOK);
	if (trigger == NULL) {
		return ENOMEM;
	}

	if (session_mode) {
		(void)netagent_buffer_write_session_message_header(trigger, trigger_type, 0, 0, 0, registration->netagent->netagent_uuid, sizeof(struct netagent_trigger_message));
	} else {
		(void)netagent_buffer_write_message_header(trigger, trigger_type, 0, 0, 0, sizeof(struct netagent_trigger_message));
	}

	trigger_message = (struct netagent_trigger_message *)(void *)(trigger + header_size);
	trigger_message->trigger_flags = flags;
	if (p != NULL) {
		trigger_message->trigger_pid = proc_pid(p);
		proc_getexecutableuuid(p, trigger_message->trigger_proc_uuid, sizeof(trigger_message->trigger_proc_uuid));
	} else {
		trigger_message->trigger_pid = 0;
		uuid_clear(trigger_message->trigger_proc_uuid);
	}

	if ((error = netagent_send_ctl_data(registration->control_unit, trigger, trigger_size))) {
		NETAGENTLOG(LOG_ERR, "Failed to send trigger message on control unit %d", registration->control_unit);
	}

	kfree_data(trigger, trigger_size);
	return error;
}

static int
netagent_send_client_message(struct netagent_registration *registration, uuid_t client_id, u_int8_t message_type)
{
	int error = 0;
	struct netagent_client_message *client_message = NULL;
	const bool session_mode = registration->allow_multiple_registrations;
	const size_t header_size = (session_mode ? sizeof(struct netagent_session_message_header) : sizeof(struct netagent_message_header));
	u_int8_t *message = NULL;
	size_t message_size = header_size + sizeof(struct netagent_client_message);

	message = (u_int8_t *)kalloc_data(message_size, Z_WAITOK);
	if (message == NULL) {
		return ENOMEM;
	}

	if (session_mode) {
		(void)netagent_buffer_write_session_message_header(message, message_type, 0, 0, 0, registration->netagent->netagent_uuid, sizeof(struct netagent_client_message));
	} else {
		(void)netagent_buffer_write_message_header(message, message_type, 0, 0, 0, sizeof(struct netagent_client_message));
	}

	client_message = (struct netagent_client_message *)(void *)(message + header_size);
	uuid_copy(client_message->client_id, client_id);

	if ((error = netagent_send_ctl_data(registration->control_unit, message, message_size))) {
		NETAGENTLOG(LOG_ERR, "Failed to send client message %d on control unit %d", message_type, registration->control_unit);
	}

	kfree_data(message, message_size);
	return error;
}

static int
netagent_send_error_message(struct netagent_registration *registration, uuid_t client_id, u_int8_t message_type, int32_t error_code)
{
	int error = 0;
	struct netagent_client_error_message *client_message = NULL;
	const bool session_mode = registration->allow_multiple_registrations;
	const size_t header_size = (session_mode ? sizeof(struct netagent_session_message_header) : sizeof(struct netagent_message_header));
	u_int8_t *message = NULL;
	size_t message_size = header_size + sizeof(struct netagent_client_error_message);

	message = (u_int8_t *)kalloc_data(message_size, Z_WAITOK);
	if (message == NULL) {
		return ENOMEM;
	}

	if (session_mode) {
		(void)netagent_buffer_write_session_message_header(message, message_type, 0, 0, 0, registration->netagent->netagent_uuid, sizeof(struct netagent_client_error_message));
	} else {
		(void)netagent_buffer_write_message_header(message, message_type, 0, 0, 0, sizeof(struct netagent_client_error_message));
	}

	client_message = (struct netagent_client_error_message *)(void *)(message + header_size);
	uuid_copy(client_message->client_id, client_id);
	client_message->error_code = error_code;

	if ((error = netagent_send_ctl_data(registration->control_unit, message, message_size))) {
		NETAGENTLOG(LOG_ERR, "Failed to send client message %d on control unit %d", message_type, registration->control_unit);
	}

	kfree_data(message, message_size);
	return error;
}

static int
netagent_send_group_message(struct netagent_registration *registration, uuid_t client_id, u_int8_t message_type, struct necp_client_group_members *group_members)
{
	int error = 0;
	struct netagent_client_group_message * __single client_message = NULL;
	const bool session_mode = registration->allow_multiple_registrations;
	const size_t header_size = (session_mode ? sizeof(struct netagent_session_message_header) : sizeof(struct netagent_message_header));
	u_int8_t *message = NULL;
	size_t message_size = header_size + sizeof(struct netagent_client_group_message) + group_members->group_members_length;

	message = (u_int8_t *)kalloc_data(message_size, Z_WAITOK);
	if (message == NULL) {
		return ENOMEM;
	}

	if (session_mode) {
		(void)netagent_buffer_write_session_message_header(message, message_type, 0, 0, 0, registration->netagent->netagent_uuid, sizeof(struct netagent_client_group_message) + group_members->group_members_length);
	} else {
		(void)netagent_buffer_write_message_header(message, message_type, 0, 0, 0, sizeof(struct netagent_client_group_message) + group_members->group_members_length);
	}

	client_message = (struct netagent_client_group_message *)(void *)(message + header_size);
	uuid_copy(client_message->client_id, client_id);
	memcpy(netagent_group_message_get_members(client_message, group_members->group_members_length), group_members->group_members, group_members->group_members_length);

	if ((error = netagent_send_ctl_data(registration->control_unit, message, message_size))) {
		NETAGENTLOG(LOG_ERR, "Failed to send client group message %d on control unit %d", message_type, registration->control_unit);
	}

	kfree_data(message, message_size);
	return error;
}

static int
netagent_send_tokens_needed(struct netagent_registration *registration)
{
	const u_int8_t message_type = NETAGENT_MESSAGE_TYPE_TOKENS_NEEDED;
	int error = 0;
	u_int8_t *message = NULL;
	const bool session_mode = registration->allow_multiple_registrations;
	const size_t header_size = (session_mode ? sizeof(struct netagent_session_message_header) : sizeof(struct netagent_message_header));
	size_t message_size = header_size;

	message = (u_int8_t *)kalloc_data(message_size, Z_WAITOK);
	if (message == NULL) {
		return ENOMEM;
	}

	if (session_mode) {
		(void)netagent_buffer_write_session_message_header(message, message_type, 0, 0, 0, registration->netagent->netagent_uuid, 0);
	} else {
		(void)netagent_buffer_write_message_header(message, message_type, 0, 0, 0, 0);
	}

	if ((error = netagent_send_ctl_data(registration->control_unit, message, message_size))) {
		NETAGENTLOG(LOG_ERR, "Failed to send client tokens needed message on control unit %d", registration->control_unit);
	}

	kfree_data(message, message_size);
	return error;
}

static int
netagent_send_success_response(struct netagent_session *session, u_int8_t message_type, u_int32_t message_id)
{
	int error = 0;
	u_int8_t *response = NULL;
	size_t response_size = sizeof(struct netagent_message_header);

	response = (u_int8_t *)kalloc_data(response_size, Z_WAITOK);
	if (response == NULL) {
		return ENOMEM;
	}
	(void)netagent_buffer_write_message_header(response, message_type, NETAGENT_MESSAGE_FLAGS_RESPONSE, message_id, 0, 0);

	if ((error = netagent_send_ctl_data(session->control_unit, response, response_size))) {
		NETAGENTLOG0(LOG_ERR, "Failed to send response");
	}

	kfree_data(response, response_size);
	return error;
}

static errno_t
netagent_send_error_response(struct netagent_session *session, u_int8_t message_type,
    u_int32_t message_id, u_int32_t error_code)
{
	int error = 0;
	u_int8_t *response = NULL;
	size_t response_size = sizeof(struct netagent_message_header);

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Got a NULL session");
		return EINVAL;
	}

	response = (u_int8_t *)kalloc_data(response_size, Z_WAITOK);
	if (response == NULL) {
		return ENOMEM;
	}
	(void)netagent_buffer_write_message_header(response, message_type, NETAGENT_MESSAGE_FLAGS_RESPONSE,
	    message_id, error_code, 0);

	if ((error = netagent_send_ctl_data(session->control_unit, response, response_size))) {
		NETAGENTLOG0(LOG_ERR, "Failed to send response");
	}

	kfree_data(response, response_size);
	return error;
}

static errno_t
netagent_ctl_send(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, mbuf_t packet, int flags)
{
#pragma unused(kctlref, unit, flags)
	struct netagent_session *session = (struct netagent_session *)unitinfo;
	struct netagent_message_header header;
	int error = 0;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Got a NULL session");
		error = EINVAL;
		goto done;
	}

	if (mbuf_pkthdr_len(packet) < sizeof(header)) {
		NETAGENTLOG(LOG_ERR, "Got a bad packet, length (%lu) < sizeof header (%lu)",
		    mbuf_pkthdr_len(packet), sizeof(header));
		error = EINVAL;
		goto done;
	}

	error = mbuf_copydata(packet, 0, sizeof(header), &header);
	if (error) {
		NETAGENTLOG(LOG_ERR, "mbuf_copydata failed for the header: %d", error);
		error = ENOBUFS;
		goto done;
	}

	switch (header.message_type) {
	case NETAGENT_MESSAGE_TYPE_REGISTER: {
		netagent_handle_register_message(session, header.message_id, header.message_payload_length,
		    packet, sizeof(header));
		break;
	}
	case NETAGENT_MESSAGE_TYPE_UNREGISTER: {
		netagent_handle_unregister_message(session, header.message_id, header.message_payload_length,
		    packet, sizeof(header));
		break;
	}
	case NETAGENT_MESSAGE_TYPE_UPDATE: {
		netagent_handle_update_message(session, header.message_id, header.message_payload_length,
		    packet, sizeof(header));
		break;
	}
	case NETAGENT_MESSAGE_TYPE_GET: {
		NETAGENTLOG0(LOG_ERR, "NETAGENT_MESSAGE_TYPE_GET no longer supported");
		break;
	}
	case NETAGENT_MESSAGE_TYPE_ASSERT: {
		NETAGENTLOG0(LOG_ERR, "NETAGENT_MESSAGE_TYPE_ASSERT no longer supported");
		break;
	}
	case NETAGENT_MESSAGE_TYPE_UNASSERT: {
		NETAGENTLOG0(LOG_ERR, "NETAGENT_MESSAGE_TYPE_UNASSERT no longer supported");
		break;
	}
	case NETAGENT_MESSAGE_TYPE_ASSIGN_NEXUS: {
		netagent_handle_assign_nexus_message(session, header.message_id, header.message_payload_length,
		    packet, sizeof(header));
		break;
	}
	default: {
		NETAGENTLOG(LOG_ERR, "Received unknown message type %d", header.message_type);
		netagent_send_error_response(session, header.message_type, header.message_id,
		    NETAGENT_MESSAGE_ERROR_UNKNOWN_TYPE);
		break;
	}
	}

done:
	mbuf_freem(packet);
	return error;
}

static void
netagent_ctl_rcvd(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int flags)
{
#pragma unused(kctlref, unit, unitinfo, flags)
	return;
}

static errno_t
netagent_ctl_getopt(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int opt,
    void * __sized_by(*len)data, size_t *len)
{
#pragma unused(kctlref, unit)
	struct netagent_session *session = (struct netagent_session *)unitinfo;
	errno_t error;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Received a NULL session");
		error = EINVAL;
		goto done;
	}

	switch (opt) {
	case NETAGENT_OPTION_TYPE_USE_COUNT: {
		NETAGENTLOG0(LOG_DEBUG, "Request to get use count");
		error = netagent_handle_use_count_getopt(session, data, len);
		break;
	}
	case NETAGENT_OPTION_TYPE_TOKEN_COUNT: {
		NETAGENTLOG0(LOG_DEBUG, "Request to get token count");
		error = netagent_handle_token_count_getopt(session, data, len);
		break;
	}
	case NETAGENT_OPTION_TYPE_TOKEN_LOW_WATER: {
		NETAGENTLOG0(LOG_DEBUG, "Request to get token low water mark");
		error = netagent_handle_token_low_water_getopt(session, data, len);
		break;
	}
	default:
		NETAGENTLOG0(LOG_ERR, "Received unknown option");
		error = ENOPROTOOPT;
		break;
	}

done:
	return error;
}

static errno_t
netagent_ctl_setopt(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int opt,
    void * __sized_by(len)data, size_t len)
{
#pragma unused(kctlref, unit)
	struct netagent_session *session = (struct netagent_session *)unitinfo;
	errno_t error;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Received a NULL session");
		error = EINVAL;
		goto done;
	}

	switch (opt) {
	case NETAGENT_OPTION_TYPE_REGISTER: {
		NETAGENTLOG0(LOG_DEBUG, "Request for registration");
		error = netagent_handle_register_setopt(session, data, len);
		break;
	}
	case NETAGENT_OPTION_TYPE_UPDATE: {
		NETAGENTLOG0(LOG_DEBUG, "Request for update");
		error = netagent_handle_update_setopt(session, data, len);
		break;
	}
	case NETAGENT_OPTION_TYPE_UNREGISTER: {
		NETAGENTLOG0(LOG_DEBUG, "Request for unregistration");
		error = netagent_handle_unregister_setopt(session, data, len);
		break;
	}
	case NETAGENT_OPTION_TYPE_ASSIGN_NEXUS: {
		NETAGENTLOG0(LOG_DEBUG, "Request for assigning nexus");
		error = netagent_handle_assign_nexus_setopt(session, data, len);
		break;
	}
	case NETAGENT_MESSAGE_TYPE_ASSIGN_GROUP_MEMBERS: {
		NETAGENTLOG0(LOG_DEBUG, "Request for assigning group members");
		error = netagent_handle_assign_group_setopt(session, data, len);
		break;
	}
	case NETAGENT_OPTION_TYPE_USE_COUNT: {
		NETAGENTLOG0(LOG_DEBUG, "Request to set use count");
		error = netagent_handle_use_count_setopt(session, data, len);
		break;
	}
	case NETAGENT_OPTION_TYPE_ADD_TOKEN: {
		NETAGENTLOG0(LOG_DEBUG, "Request to add a token");
		error = netagent_handle_add_token_setopt(session, data, len);
		break;
	}
	case NETAGENT_OPTION_TYPE_FLUSH_TOKENS: {
		NETAGENTLOG0(LOG_DEBUG, "Request to flush tokens");
		error = netagent_handle_flush_tokens_setopt(session, data, len);
		break;
	}
	case NETAGENT_OPTION_TYPE_TOKEN_LOW_WATER: {
		NETAGENTLOG0(LOG_DEBUG, "Request to set token low water mark");
		error = netagent_handle_token_low_water_setopt(session, data, len);
		break;
	}
	case NETAGENT_OPTION_TYPE_RESET_CLIENT_ERROR: {
		NETAGENTLOG0(LOG_DEBUG, "Request to reset client error");
		error = netagent_handle_reset_client_error_setopt(session, data, len);
		break;
	}
	case NETAGENT_OPTION_TYPE_ENABLE_SESSION_MODE: {
		NETAGENTLOG0(LOG_DEBUG, "Request to enable session mode");
		error = netagent_handle_enable_session_mode_setopt(session, data, len);
		break;
	}
	case NETAGENT_OPTION_TYPE_UNREGISTER_ALL: {
		NETAGENTLOG0(LOG_DEBUG, "Request for unregistration of all agents");
		error = netagent_handle_unregister_all_setopt(session, data, len);
		break;
	}
	default:
		NETAGENTLOG0(LOG_ERR, "Received unknown option");
		error = ENOPROTOOPT;
		break;
	}

done:
	return error;
}

// Session Management
static struct netagent_session *
netagent_create_session(u_int32_t control_unit)
{
	struct netagent_session *new_session = NULL;

	new_session = kalloc_type(struct netagent_session,
	    Z_WAITOK | Z_ZERO | Z_NOFAIL);
	NETAGENTLOG(LOG_DEBUG, "Create agent session, control unit %d", control_unit);
	new_session->control_unit = control_unit;
	lck_mtx_init(&new_session->session_lock, &netagent_mtx_grp, LCK_ATTR_NULL);
	TAILQ_INIT(&new_session->registrations);

	return new_session;
}

netagent_session_t
netagent_create(netagent_event_f event_handler, void *context)
{
	struct netagent_session *session = netagent_create_session(0);
	if (session == NULL) {
		return NULL;
	}

	session->event_handler = event_handler;
	session->event_context = context;
	return session;
}

static void
netagent_token_free(struct netagent_token *token)
{
	kfree_data(token->token_bytes, token->token_length);
	kfree_type(struct netagent_token, token);
}

static struct netagent_registration *
netagent_alloc_registration_memory(uint32_t data_size)
{
	struct netagent_registration *new_registration;
	size_t netagent_alloc_size = sizeof(struct netagent) + data_size;

	new_registration = kalloc_type(struct netagent_registration,
	    Z_WAITOK | Z_ZERO | Z_NOFAIL);
	new_registration->netagent = kalloc_data(netagent_alloc_size, Z_WAITOK | Z_NOFAIL);
	new_registration->netagent_alloc_size = netagent_alloc_size;

	lck_rw_init(&new_registration->agent_lock, &netagent_mtx_grp, LCK_ATTR_NULL);

	return new_registration;
}

static void
netagent_free_registration_memory(struct netagent_registration *registration)
{
	// Before destroying the lock, take the lock exclusively and then
	// drop it again. This ensures that no other thread was holding
	// onto the lock at the time of destroying it.
	// This can happen in netagent_client_message_with_params due
	// to the fact that the registration lock needs to be held during the
	// event callout, while the list lock has been released. Taking
	// this lock here ensures that any such remaining thread completes
	// before this object is released. Since the registration object has
	// already been removed from any and all lists by this point,
	// there isn't any way for a new thread to start referencing it.
	NETAGENT_LOCK_EXCLUSIVE(registration);
	NETAGENT_UNLOCK(registration);
	lck_rw_destroy(&registration->agent_lock, &netagent_mtx_grp);

	kfree_data_sized_by(registration->netagent, registration->netagent_alloc_size);
	kfree_type(struct netagent_registration, registration);
}

static void
netagent_free_registration(struct netagent_registration *registration)
{
	// Free any leftover tokens
	struct netagent_token *search_token = NULL;
	struct netagent_token *temp_token = NULL;
	TAILQ_FOREACH_SAFE(search_token, &registration->token_list, token_chain, temp_token) {
		TAILQ_REMOVE(&registration->token_list, search_token, token_chain);
		netagent_token_free(search_token);
	}

	// Free any pending client triggers
	struct netagent_client * __single search_client = NULL;
	struct netagent_client *temp_client = NULL;
	LIST_FOREACH_SAFE(search_client, &registration->pending_triggers_list, client_chain, temp_client) {
		LIST_REMOVE(search_client, client_chain);
		kfree_type(struct netagent_client, search_client);
	}

	// Free registration itself
	netagent_free_registration_memory(registration);
}

static void
netagent_unregister_all_session_registrations(struct netagent_session *session)
{
	TAILQ_HEAD(_netagent_registration_list, netagent_registration) deleting_registrations;
	TAILQ_INIT(&deleting_registrations);
	NETAGENT_LIST_LOCK_EXCLUSIVE();
	if (session != NULL) {
		NETAGENT_SESSION_LOCK(session);
		struct netagent_registration *registration = NULL;
		struct netagent_registration *temp_registration = NULL;
		TAILQ_FOREACH_SAFE(registration, &session->registrations, session_chain, temp_registration) {
			if (netagent_registered_count > 0) {
				netagent_registered_count--;
			}
			if ((registration->netagent->netagent_flags & NETAGENT_FLAG_ACTIVE) &&
			    netagent_active_count > 0) {
				netagent_active_count--;
			}

			LIST_REMOVE(registration, global_chain);
			TAILQ_REMOVE(&session->registrations, registration, session_chain);
			TAILQ_INSERT_TAIL(&deleting_registrations, registration, session_chain);
			NETAGENTLOG0(LOG_DEBUG, "Unregistered agent");
		}
		NETAGENT_SESSION_UNLOCK(session);
	}
	NETAGENT_LIST_UNLOCK();

	struct netagent_registration *registration = NULL;
	struct netagent_registration *temp_registration = NULL;
	TAILQ_FOREACH_SAFE(registration, &deleting_registrations, session_chain, temp_registration) {
		TAILQ_REMOVE(&deleting_registrations, registration, session_chain);

		ifnet_clear_netagent(registration->netagent->netagent_uuid);
		netagent_post_event(registration->netagent->netagent_uuid, KEV_NETAGENT_UNREGISTERED, TRUE, false);

		netagent_free_registration(registration);
	}
}

static void
netagent_unregister_one_session_registration(struct netagent_session *session, uuid_t agent_id)
{
	bool unregistered = false;
	NETAGENT_LIST_LOCK_EXCLUSIVE();
	if (session != NULL) {
		NETAGENT_SESSION_LOCK(session);
		struct netagent_registration *registration = NULL;
		struct netagent_registration *temp_registration = NULL;
		TAILQ_FOREACH_SAFE(registration, &session->registrations, session_chain, temp_registration) {
			if (uuid_compare(agent_id, registration->netagent->netagent_uuid) != 0) {
				// Not a match, skip
				continue;
			}

			if (netagent_registered_count > 0) {
				netagent_registered_count--;
			}
			if ((registration->netagent->netagent_flags & NETAGENT_FLAG_ACTIVE) &&
			    netagent_active_count > 0) {
				netagent_active_count--;
			}

			LIST_REMOVE(registration, global_chain);
			TAILQ_REMOVE(&session->registrations, registration, session_chain);

			unregistered = true;
			netagent_free_registration(registration);

			NETAGENTLOG0(LOG_DEBUG, "Unregistered agent");
		}
		NETAGENT_SESSION_UNLOCK(session);
	}
	NETAGENT_LIST_UNLOCK();

	if (unregistered) {
		ifnet_clear_netagent(agent_id);
		netagent_post_event(agent_id, KEV_NETAGENT_UNREGISTERED, TRUE, false);
	}
}

static void
netagent_delete_session(struct netagent_session *session)
{
	if (session != NULL) {
		netagent_unregister_all_session_registrations(session);
		lck_mtx_destroy(&session->session_lock, &netagent_mtx_grp);
		kfree_type(struct netagent_session, session);
	}
}

void
netagent_destroy(netagent_session_t session)
{
	return netagent_delete_session((struct netagent_session *)session);
}

static size_t
netagent_packet_get_netagent_data_size(mbuf_t packet, size_t offset, int *err)
{
	int error = 0;

	struct netagent netagent_peek;
	memset(&netagent_peek, 0, sizeof(netagent_peek));

	*err = 0;

	error = mbuf_copydata(packet, offset, sizeof(netagent_peek), &netagent_peek);
	if (error) {
		*err = ENOENT;
		return 0;
	}

	return netagent_peek.netagent_data_size;
}

static errno_t
netagent_handle_register_inner(struct netagent_session *session, struct netagent_registration *new_registration)
{
	NETAGENT_LIST_LOCK_EXCLUSIVE();

	NETAGENT_SESSION_LOCK(session);

	if (!session->allow_multiple_registrations && !TAILQ_EMPTY(&session->registrations)) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENT_LIST_UNLOCK();
		return EINVAL;
	}

	struct netagent_registration *existing_registration = netagent_find_agent_with_uuid_and_lock(new_registration->netagent->netagent_uuid, false, true);
	if (existing_registration != NULL) {
		NETAGENTLOG0(LOG_ERR, "Existing agent registration UUID conflicts with new agent registration");
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENT_LIST_UNLOCK();
		return EEXIST;
	}

	new_registration->control_unit = session->control_unit;
	new_registration->allow_multiple_registrations = session->allow_multiple_registrations;
	new_registration->event_handler = session->event_handler;
	new_registration->event_context = session->event_context;
	new_registration->generation = g_next_generation++;

	TAILQ_INSERT_TAIL(&session->registrations, new_registration, session_chain);
	LIST_INSERT_HEAD(&shared_netagent_list, new_registration, global_chain);
	TAILQ_INIT(&new_registration->token_list);
	LIST_INIT(&new_registration->pending_triggers_list);

	new_registration->netagent->netagent_flags |= NETAGENT_FLAG_REGISTERED;
	netagent_registered_count++;
	if (new_registration->netagent->netagent_flags & NETAGENT_FLAG_ACTIVE) {
		netagent_active_count++;
	}

	NETAGENT_SESSION_UNLOCK(session);
	NETAGENT_LIST_UNLOCK();
	return 0;
}

errno_t
netagent_register(netagent_session_t _session, struct netagent *agent)
{
	struct netagent_registration *new_registration = NULL;
	uuid_t registered_uuid;

	struct netagent_session *session = (struct netagent_session *)_session;
	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Cannot register agent on NULL session");
		return EINVAL;
	}

	if (agent == NULL) {
		NETAGENTLOG0(LOG_ERR, "Cannot register NULL agent");
		return EINVAL;
	}

	size_t data_size = agent->netagent_data_size;
	if (data_size > NETAGENT_MAX_DATA_SIZE) {
		NETAGENTLOG(LOG_ERR, "Register message size could not be read, data_size %zu",
		    data_size);
		return EINVAL;
	}

	new_registration = netagent_alloc_registration_memory(data_size);

	__nochk_memcpy(new_registration->netagent, agent, sizeof(struct netagent));
	__nochk_memcpy(netagent_get_data(new_registration->netagent), netagent_get_data(agent), data_size);

	uuid_copy(registered_uuid, new_registration->netagent->netagent_uuid);

	errno_t error = netagent_handle_register_inner(session, new_registration);
	if (error != 0) {
		netagent_free_registration_memory(new_registration);
		return error;
	}

	NETAGENTLOG0(LOG_DEBUG, "Registered new agent");
	netagent_post_event(registered_uuid, KEV_NETAGENT_REGISTERED, TRUE, false);

	return 0;
}

static errno_t
netagent_handle_register_setopt(struct netagent_session *session, u_int8_t *payload,
    size_t payload_length)
{
	struct netagent_registration *new_registration = NULL;
	errno_t response_error = 0;
	struct netagent *register_netagent = (struct netagent *)(void *)payload;
	uuid_t registered_uuid;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = EINVAL;
		goto done;
	}

	if (payload == NULL) {
		NETAGENTLOG0(LOG_ERR, "No payload received");
		response_error = EINVAL;
		goto done;
	}

	if (payload_length < sizeof(struct netagent)) {
		NETAGENTLOG(LOG_ERR, "Register message size too small for agent: (%zu < %zu)",
		    payload_length, sizeof(struct netagent));
		response_error = EINVAL;
		goto done;
	}

	size_t data_size = register_netagent->netagent_data_size;
	if (data_size > NETAGENT_MAX_DATA_SIZE) {
		NETAGENTLOG(LOG_ERR, "Register message size could not be read, data_size %zu", data_size);
		response_error = EINVAL;
		goto done;
	}

	if (payload_length != (sizeof(struct netagent) + data_size)) {
		NETAGENTLOG(LOG_ERR, "Mismatch between data size and payload length (%lu != %zu)", (sizeof(struct netagent) + data_size), payload_length);
		response_error = EINVAL;
		goto done;
	}

	new_registration = netagent_alloc_registration_memory(data_size);

	__nochk_memcpy(new_registration->netagent, register_netagent, sizeof(struct netagent));
	__nochk_memcpy(netagent_get_data(new_registration->netagent), netagent_get_data(register_netagent), data_size);

	uuid_copy(registered_uuid, new_registration->netagent->netagent_uuid);

	response_error = netagent_handle_register_inner(session, new_registration);
	if (response_error != 0) {
		netagent_free_registration_memory(new_registration);
		goto done;
	}

	NETAGENTLOG0(LOG_DEBUG, "Registered new agent");
	netagent_post_event(registered_uuid, KEV_NETAGENT_REGISTERED, TRUE, false);

done:
	return response_error;
}

static void
netagent_handle_register_message(struct netagent_session *session, u_int32_t message_id,
    size_t payload_length, mbuf_t packet, size_t offset)
{
	errno_t error;
	struct netagent_registration *new_registration = NULL;
	u_int32_t response_error = NETAGENT_MESSAGE_ERROR_INTERNAL;
	uuid_t registered_uuid;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = NETAGENT_MESSAGE_ERROR_INTERNAL;
		goto fail;
	}

	if (session->allow_multiple_registrations) {
		NETAGENTLOG0(LOG_ERR, "Not allowed to register multiple agents");
		response_error = NETAGENT_MESSAGE_ERROR_INVALID_DATA;
		goto fail;
	}

	if (payload_length < sizeof(struct netagent)) {
		NETAGENTLOG(LOG_ERR, "Register message size too small for agent: (%zu < %zu)",
		    payload_length, sizeof(struct netagent));
		response_error = NETAGENT_MESSAGE_ERROR_INVALID_DATA;
		goto fail;
	}

	size_t data_size = netagent_packet_get_netagent_data_size(packet, offset, &error);
	if (error || data_size > NETAGENT_MAX_DATA_SIZE) {
		NETAGENTLOG(LOG_ERR, "Register message size could not be read, error %d data_size %zu",
		    error, data_size);
		response_error = NETAGENT_MESSAGE_ERROR_INVALID_DATA;
		goto fail;
	}

	new_registration = netagent_alloc_registration_memory(data_size);

	error = mbuf_copydata(packet, offset, sizeof(struct netagent) + data_size,
	    new_registration->netagent);
	if (error) {
		NETAGENTLOG(LOG_ERR, "Failed to read data into agent structure: %d", error);
		netagent_free_registration_memory(new_registration);
		response_error = NETAGENT_MESSAGE_ERROR_INTERNAL;
		goto fail;
	}

	uuid_copy(registered_uuid, new_registration->netagent->netagent_uuid);

	error = netagent_handle_register_inner(session, new_registration);
	if (error) {
		NETAGENTLOG(LOG_ERR, "Failed to register agent: %d", error);
		netagent_free_registration_memory(new_registration);
		response_error = NETAGENT_MESSAGE_ERROR_INTERNAL;
		goto fail;
	}

	NETAGENTLOG0(LOG_DEBUG, "Registered new agent");
	netagent_send_success_response(session, NETAGENT_MESSAGE_TYPE_REGISTER, message_id);
	netagent_post_event(registered_uuid, KEV_NETAGENT_REGISTERED, TRUE, false);
	return;
fail:
	netagent_send_error_response(session, NETAGENT_MESSAGE_TYPE_REGISTER, message_id, response_error);
}

errno_t
netagent_unregister(netagent_session_t _session)
{
	struct netagent_session *session = (struct netagent_session *)_session;
	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Cannot unregister NULL session");
		return EINVAL;
	}

	netagent_unregister_all_session_registrations(session);
	return 0;
}

static errno_t
netagent_handle_unregister_setopt(struct netagent_session *session, u_int8_t * __sized_by(payload_length) payload,
    size_t payload_length)
{
	errno_t response_error = 0;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = EINVAL;
		goto done;
	}

	if (!session->allow_multiple_registrations) {
		netagent_unregister_all_session_registrations(session);
	} else {
		if (payload == NULL) {
			NETAGENTLOG0(LOG_ERR, "No payload received");
			response_error = EINVAL;
			goto done;
		}

		if (payload_length < sizeof(uuid_t)) {
			NETAGENTLOG(LOG_ERR, "Unregister message size too small for UUID: (%zu < %zu)",
			    payload_length, sizeof(uuid_t));
			response_error = EINVAL;
			goto done;
		}

		uuid_t agent_uuid = {};
		uuid_copy(agent_uuid, payload);
		netagent_unregister_one_session_registration(session, agent_uuid);
	}

done:
	return response_error;
}

static errno_t
netagent_handle_unregister_all_setopt(struct netagent_session *session, u_int8_t * __sized_by(payload_length) payload,
    size_t payload_length)
{
#pragma unused(payload, payload_length)

	errno_t response_error = 0;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = EINVAL;
		goto done;
	}

	netagent_unregister_all_session_registrations(session);

done:
	return response_error;
}

static void
netagent_handle_unregister_message(struct netagent_session *session, u_int32_t message_id,
    size_t payload_length, mbuf_t packet, size_t offset)
{
#pragma unused(payload_length, packet, offset)
	u_int32_t response_error = NETAGENT_MESSAGE_ERROR_INTERNAL;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = NETAGENT_MESSAGE_ERROR_INTERNAL;
		goto fail;
	}

	if (session->allow_multiple_registrations) {
		NETAGENTLOG0(LOG_ERR, "Not allowed to register multiple agents");
		response_error = NETAGENT_MESSAGE_ERROR_INVALID_DATA;
		goto fail;
	}

	netagent_unregister_all_session_registrations(session);

	netagent_send_success_response(session, NETAGENT_MESSAGE_TYPE_UNREGISTER, message_id);
	return;
fail:
	netagent_send_error_response(session, NETAGENT_MESSAGE_TYPE_UNREGISTER, message_id, response_error);
}

static void
netagent_send_cellular_failed_event(struct netagent_registration *registration,
    pid_t pid, uuid_t proc_uuid)
{
	if (strlcmp(registration->netagent->netagent_domain, "Cellular", NETAGENT_DOMAINSIZE) != 0) {
		return;
	}

	struct kev_netpolicy_ifdenied ev_ifdenied;

	bzero(&ev_ifdenied, sizeof(ev_ifdenied));

	ev_ifdenied.ev_data.epid = (u_int64_t)pid;
	uuid_copy(ev_ifdenied.ev_data.euuid, proc_uuid);
	ev_ifdenied.ev_if_functional_type = IFRTYPE_FUNCTIONAL_CELLULAR;

	netpolicy_post_msg(KEV_NETPOLICY_IFFAILED, &ev_ifdenied.ev_data, sizeof(ev_ifdenied));
}

static errno_t
netagent_handle_update_inner(struct netagent_session *session, struct netagent_registration *new_registration,
    size_t data_size, u_int8_t *agent_changed, netagent_error_domain_t error_domain)
{
	errno_t response_error = 0;

	if (agent_changed == NULL) {
		NETAGENTLOG0(LOG_ERR, "Invalid argument: agent_changed");
		return EINVAL;
	}

	NETAGENT_LIST_LOCK_EXCLUSIVE();

	NETAGENT_SESSION_LOCK(session);
	struct netagent_registration *registration = NULL;
	if (session->allow_multiple_registrations) {
		registration = netagent_session_find_agent_with_uuid_and_lock(session, new_registration->netagent->netagent_uuid, true, false);
	} else {
		registration = netagent_session_access_agent_with_lock(session, true, false);
	}

	if (registration == NULL) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENT_LIST_UNLOCK();
		response_error = ENOENT;
		return response_error;
	}

	if (uuid_compare(registration->netagent->netagent_uuid, new_registration->netagent->netagent_uuid) != 0 ||
	    memcmp(&registration->netagent->netagent_domain, &new_registration->netagent->netagent_domain,
	    sizeof(new_registration->netagent->netagent_domain)) != 0 ||
	    memcmp(&registration->netagent->netagent_type, &new_registration->netagent->netagent_type,
	    sizeof(new_registration->netagent->netagent_type)) != 0) {
		NETAGENT_UNLOCK(registration);
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENT_LIST_UNLOCK();
		NETAGENTLOG0(LOG_ERR, "Basic agent parameters do not match, cannot update");
		if (error_domain == kNetagentErrorDomainPOSIX) {
			response_error = EINVAL;
		} else if (error_domain == kNetagentErrorDomainUserDefined) {
			response_error = NETAGENT_MESSAGE_ERROR_CANNOT_UPDATE;
		}
		return response_error;
	}

	new_registration->netagent->netagent_flags |= NETAGENT_FLAG_REGISTERED;
	if (registration->netagent->netagent_data_size == new_registration->netagent->netagent_data_size &&
	    memcmp(registration->netagent, new_registration->netagent, sizeof(struct netagent)) == 0 &&
	    memcmp(netagent_get_data(registration->netagent), netagent_get_data(new_registration->netagent), data_size) == 0) {
		// Agent is exactly identical, don't increment the generation count

		// Make a copy of the list of pending clients, and clear the current list
		struct netagent_client_list_s pending_triggers_list_copy;
		LIST_INIT(&pending_triggers_list_copy);
		struct netagent_client * __single search_client = NULL;
		struct netagent_client *temp_client = NULL;
		LIST_FOREACH_SAFE(search_client, &registration->pending_triggers_list, client_chain, temp_client) {
			LIST_REMOVE(search_client, client_chain);
			LIST_INSERT_HEAD(&pending_triggers_list_copy, search_client, client_chain);
		}
		NETAGENT_UNLOCK(registration);
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENT_LIST_UNLOCK();

		// Update pending client triggers without holding a lock
		search_client = NULL;
		temp_client = NULL;
		LIST_FOREACH_SAFE(search_client, &pending_triggers_list_copy, client_chain, temp_client) {
			necp_force_update_client(search_client->client_id, registration->netagent->netagent_uuid, registration->generation);
			netagent_send_cellular_failed_event(new_registration, search_client->client_pid, search_client->client_proc_uuid);
			LIST_REMOVE(search_client, client_chain);
			kfree_type(struct netagent_client, search_client);
		}
		NETAGENTLOG0(LOG_DEBUG, "Updated agent (no changes)");
		*agent_changed = FALSE;
		return response_error;
	}

	new_registration->generation = g_next_generation++;
	new_registration->use_count = registration->use_count;

	TAILQ_INIT(&new_registration->token_list);
	TAILQ_CONCAT(&new_registration->token_list, &registration->token_list, token_chain);
	new_registration->token_count = registration->token_count;
	new_registration->token_low_water = registration->token_low_water;
	new_registration->last_client_error = registration->last_client_error;
	new_registration->client_error_count = registration->client_error_count;
	new_registration->allow_multiple_registrations = registration->allow_multiple_registrations;

	if ((new_registration->netagent->netagent_flags & NETAGENT_FLAG_ACTIVE) &&
	    !(registration->netagent->netagent_flags & NETAGENT_FLAG_ACTIVE)) {
		netagent_active_count++;
	} else if (!(new_registration->netagent->netagent_flags & NETAGENT_FLAG_ACTIVE) &&
	    (registration->netagent->netagent_flags & NETAGENT_FLAG_ACTIVE) &&
	    netagent_active_count > 0) {
		netagent_active_count--;
	}

	TAILQ_REMOVE(&session->registrations, registration, session_chain);
	LIST_REMOVE(registration, global_chain);
	NETAGENT_UNLOCK(registration);
	netagent_free_registration(registration);
	TAILQ_INSERT_TAIL(&session->registrations, new_registration, session_chain);
	new_registration->control_unit = session->control_unit;
	new_registration->event_handler = session->event_handler;
	new_registration->event_context = session->event_context;
	LIST_INSERT_HEAD(&shared_netagent_list, new_registration, global_chain);
	LIST_INIT(&new_registration->pending_triggers_list);

	NETAGENT_SESSION_UNLOCK(session);
	NETAGENT_LIST_UNLOCK();

	NETAGENTLOG0(LOG_DEBUG, "Updated agent");
	*agent_changed = TRUE;

	return response_error;
}

errno_t
netagent_update(netagent_session_t _session, struct netagent *agent)
{
	u_int8_t agent_changed;
	struct netagent_registration *new_registration = NULL;
	bool should_update_immediately;
	uuid_t updated_uuid;

	struct netagent_session *session = (struct netagent_session *)_session;
	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Cannot update agent on NULL session");
		return EINVAL;
	}

	if (agent == NULL) {
		NETAGENTLOG0(LOG_ERR, "Cannot register NULL agent");
		return EINVAL;
	}

	size_t data_size = agent->netagent_data_size;
	if (data_size > NETAGENT_MAX_DATA_SIZE) {
		NETAGENTLOG(LOG_ERR, "Update message size (%zu > %u) too large", data_size, NETAGENT_MAX_DATA_SIZE);
		return EINVAL;
	}

	new_registration = netagent_alloc_registration_memory(data_size);

	__nochk_memcpy(new_registration->netagent, agent, sizeof(struct netagent));
	__nochk_memcpy(netagent_get_data(new_registration->netagent), netagent_get_data(agent), data_size);

	uuid_copy(updated_uuid, new_registration->netagent->netagent_uuid);
	should_update_immediately = (NETAGENT_FLAG_UPDATE_IMMEDIATELY == (new_registration->netagent->netagent_flags & NETAGENT_FLAG_UPDATE_IMMEDIATELY));

	errno_t error = netagent_handle_update_inner(session, new_registration, data_size, &agent_changed, kNetagentErrorDomainPOSIX);
	if (error == 0) {
		netagent_post_event(updated_uuid, KEV_NETAGENT_UPDATED, agent_changed, should_update_immediately);
		if (agent_changed == FALSE) {
			// The session registration does not need the "new_registration" as nothing changed
			netagent_free_registration_memory(new_registration);
		}
	} else {
		netagent_free_registration_memory(new_registration);
		return error;
	}

	return 0;
}

static errno_t
netagent_handle_update_setopt(struct netagent_session *session, u_int8_t *payload, size_t payload_length)
{
	struct netagent_registration *new_registration = NULL;
	errno_t response_error = 0;
	struct netagent *update_netagent = (struct netagent *)(void *)payload;
	u_int8_t agent_changed;
	bool should_update_immediately;
	uuid_t updated_uuid;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = EINVAL;
		goto done;
	}

	if (payload == NULL) {
		NETAGENTLOG0(LOG_ERR, "No payload received");
		response_error = EINVAL;
		goto done;
	}

	if (payload_length < sizeof(struct netagent)) {
		NETAGENTLOG(LOG_ERR, "Update message size too small for agent: (%zu < %zu)",
		    payload_length, sizeof(struct netagent));
		response_error = EINVAL;
		goto done;
	}

	size_t data_size = update_netagent->netagent_data_size;
	if (data_size > NETAGENT_MAX_DATA_SIZE) {
		NETAGENTLOG(LOG_ERR, "Update message size (%zu > %u) too large", data_size, NETAGENT_MAX_DATA_SIZE);
		response_error = EINVAL;
		goto done;
	}

	if (payload_length != (sizeof(struct netagent) + data_size)) {
		NETAGENTLOG(LOG_ERR, "Mismatch between data size and payload length (%lu != %zu)", (sizeof(struct netagent) + data_size), payload_length);
		response_error = EINVAL;
		goto done;
	}

	new_registration = netagent_alloc_registration_memory(data_size);

	__nochk_memcpy(new_registration->netagent, update_netagent, sizeof(struct netagent));
	__nochk_memcpy(netagent_get_data(new_registration->netagent), netagent_get_data(update_netagent), data_size);

	uuid_copy(updated_uuid, new_registration->netagent->netagent_uuid);
	should_update_immediately = (NETAGENT_FLAG_UPDATE_IMMEDIATELY == (new_registration->netagent->netagent_flags & NETAGENT_FLAG_UPDATE_IMMEDIATELY));

	response_error = netagent_handle_update_inner(session, new_registration, data_size, &agent_changed, kNetagentErrorDomainPOSIX);
	if (response_error == 0) {
		netagent_post_event(updated_uuid, KEV_NETAGENT_UPDATED, agent_changed, should_update_immediately);
		if (agent_changed == FALSE) {
			// The session registration does not need the "new_registration" as nothing changed
			netagent_free_registration_memory(new_registration);
		}
	} else {
		netagent_free_registration_memory(new_registration);
	}

done:
	return response_error;
}

static void
netagent_handle_update_message(struct netagent_session *session, u_int32_t message_id,
    size_t payload_length, mbuf_t packet, size_t offset)
{
	int error;
	struct netagent_registration *new_registration = NULL;
	u_int32_t response_error = NETAGENT_MESSAGE_ERROR_INTERNAL;
	u_int8_t agent_changed;
	uuid_t updated_uuid;
	bool should_update_immediately;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = NETAGENT_MESSAGE_ERROR_INTERNAL;
		goto fail;
	}

	if (payload_length < sizeof(struct netagent)) {
		NETAGENTLOG(LOG_ERR, "Update message size too small for agent: (%zu < %zu)",
		    payload_length, sizeof(struct netagent));
		response_error = NETAGENT_MESSAGE_ERROR_INVALID_DATA;
		goto fail;
	}

	size_t data_size = netagent_packet_get_netagent_data_size(packet, offset, &error);
	if (error || data_size > NETAGENT_MAX_DATA_SIZE) {
		NETAGENTLOG(LOG_ERR, "Update message size could not be read, error %d data_size %zu",
		    error, data_size);
		response_error = NETAGENT_MESSAGE_ERROR_INVALID_DATA;
		goto fail;
	}

	new_registration = netagent_alloc_registration_memory(data_size);

	error = mbuf_copydata(packet, offset, new_registration->netagent_alloc_size, new_registration->netagent);
	if (error) {
		NETAGENTLOG(LOG_ERR, "Failed to read data into agent structure: %d", error);
		netagent_free_registration_memory(new_registration);
		response_error = NETAGENT_MESSAGE_ERROR_INTERNAL;
		goto fail;
	}

	uuid_copy(updated_uuid, new_registration->netagent->netagent_uuid);
	should_update_immediately = (NETAGENT_FLAG_UPDATE_IMMEDIATELY == (new_registration->netagent->netagent_flags & NETAGENT_FLAG_UPDATE_IMMEDIATELY));

	response_error = (u_int32_t)netagent_handle_update_inner(session, new_registration, data_size, &agent_changed, kNetagentErrorDomainUserDefined);
	if (response_error != 0) {
		if (response_error == ENOENT) {
			response_error = NETAGENT_MESSAGE_ERROR_NOT_REGISTERED;
		}
		netagent_free_registration_memory(new_registration);
		goto fail;
	}

	netagent_send_success_response(session, NETAGENT_MESSAGE_TYPE_UPDATE, message_id);

	netagent_post_event(updated_uuid, KEV_NETAGENT_UPDATED, agent_changed, should_update_immediately);

	if (agent_changed == FALSE) {
		// The session registration does not need the "new_registration" as nothing changed
		netagent_free_registration_memory(new_registration);
	}

	return;
fail:
	netagent_send_error_response(session, NETAGENT_MESSAGE_TYPE_UPDATE, message_id, response_error);
}

errno_t
netagent_assign_nexus(netagent_session_t _session, uuid_t necp_client_uuid,
    void * __sized_by(assigned_results_length)assign_message, size_t assigned_results_length)
{
	struct netagent_session *session = (struct netagent_session *)_session;
	uuid_t netagent_uuid;
	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Cannot assign nexus from NULL session");
		return EINVAL;
	}

	NETAGENT_SESSION_LOCK(session);

	struct netagent_registration *registration = netagent_session_access_agent_with_lock(session, false, false);
	if (registration == NULL) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session has no matching agent");
		return ENOENT;
	}
	uuid_copy(netagent_uuid, registration->netagent->netagent_uuid);
	NETAGENT_UNLOCK(registration);
	NETAGENT_SESSION_UNLOCK(session);

	// Note that if the error is 0, NECP has taken over our malloc'ed buffer
	int error = necp_assign_client_result(netagent_uuid, necp_client_uuid, assign_message, assigned_results_length);
	if (error) {
		// necp_assign_client_result returns POSIX errors; don't error for ENOENT
		NETAGENTLOG((error == ENOENT ? LOG_DEBUG : LOG_ERR), "Client assignment failed: %d", error);
		return error;
	}

	NETAGENTLOG0(LOG_DEBUG, "Agent assigned nexus properties to client");
	return 0;
}

errno_t
netagent_update_flow_protoctl_event(netagent_session_t _session,
    uuid_t client_id, uint32_t protoctl_event_code,
    uint32_t protoctl_event_val, uint32_t protoctl_event_tcp_seq_number)
{
	struct netagent_session *session = (struct netagent_session *)_session;
	uuid_t netagent_uuid;
	int error = 0;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Cannot assign nexus from NULL session");
		return EINVAL;
	}

	NETAGENT_SESSION_LOCK(session);
	struct netagent_registration *registration = netagent_session_access_agent_with_lock(session, false, false);
	if (registration == NULL) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session has no agent");
		return ENOENT;
	}
	uuid_copy(netagent_uuid, registration->netagent->netagent_uuid);
	NETAGENT_UNLOCK(registration);
	NETAGENT_SESSION_UNLOCK(session);

	error = necp_update_flow_protoctl_event(netagent_uuid,
	    client_id, protoctl_event_code, protoctl_event_val, protoctl_event_tcp_seq_number);

	return error;
}

static errno_t
netagent_handle_assign_nexus_setopt(struct netagent_session *session, u_int8_t * __sized_by(payload_length)payload,
    size_t payload_length)
{
	errno_t response_error = 0;
	uuid_t client_id;
	uuid_t netagent_uuid;
	u_int8_t *assigned_results = NULL;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = ENOENT;
		goto done;
	}

	if (payload == NULL) {
		NETAGENTLOG0(LOG_ERR, "No payload received");
		response_error = EINVAL;
		goto done;
	}

	NETAGENT_SESSION_LOCK(session);

	const size_t header_offset = (session->allow_multiple_registrations ? sizeof(uuid_t) : 0);
	if (payload_length < header_offset) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Assign message is too short");
		response_error = EINVAL;
		goto done;
	}

	struct netagent_assign_nexus_message * __single assign_nexus_netagent = (struct netagent_assign_nexus_message *)(void *)((u_int8_t *)payload + header_offset);

	struct netagent_registration *registration = NULL;
	if (session->allow_multiple_registrations) {
		uuid_t agent_uuid = {};
		uuid_copy(agent_uuid, payload);
		registration = netagent_session_find_agent_with_uuid_and_lock(session, agent_uuid, false, false);
	} else {
		registration = netagent_session_access_agent_with_lock(session, false, false);
	}

	if (registration == NULL) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session has no agent to get");
		response_error = ENOENT;
		goto done;
	}

	uuid_copy(netagent_uuid, registration->netagent->netagent_uuid);
	NETAGENT_UNLOCK(registration);
	NETAGENT_SESSION_UNLOCK(session);

	if (payload_length < (header_offset + sizeof(uuid_t))) {
		NETAGENTLOG0(LOG_ERR, "Assign message is too short");
		response_error = EINVAL;
		goto done;
	}

	memcpy(client_id, assign_nexus_netagent->assign_client_id, sizeof(client_id));
	size_t assigned_results_length = (payload_length - (header_offset + sizeof(client_id)));

	if (assigned_results_length > 0) {
		assigned_results = kalloc_data(assigned_results_length, Z_WAITOK);
		if (assigned_results == NULL) {
			NETAGENTLOG(LOG_ERR, "Failed to allocate assign message (%lu bytes)", assigned_results_length);
			response_error = ENOMEM;
			goto done;
		}
		memcpy(assigned_results,
		    netagent_assign_message_get_necp_result(assign_nexus_netagent, assigned_results_length),
		    assigned_results_length);
	}

	// Note that if the error is 0, NECP has taken over our malloc'ed buffer
	response_error = necp_assign_client_result(netagent_uuid, client_id, assigned_results, assigned_results_length);
	if (response_error) {
		// necp_assign_client_result returns POSIX errors
		kfree_data(assigned_results, assigned_results_length);
		NETAGENTLOG(LOG_ERR, "Client assignment failed: %d", response_error);
		goto done;
	}

	NETAGENTLOG0(LOG_DEBUG, "Agent assigned nexus properties to client");
done:
	return response_error;
}

static void
netagent_handle_assign_nexus_message(struct netagent_session *session, u_int32_t message_id,
    size_t payload_length, mbuf_t packet, size_t offset)
{
	int error = 0;
	u_int32_t response_error = NETAGENT_MESSAGE_ERROR_INTERNAL;
	uuid_t client_id;
	uuid_t netagent_uuid;
	u_int8_t * assigned_results = NULL;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = NETAGENT_MESSAGE_ERROR_INTERNAL;
		goto fail;
	}

	NETAGENT_SESSION_LOCK(session);
	struct netagent_registration *registration = netagent_session_access_agent_with_lock(session, false, false);
	if (registration == NULL) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session has no agent to get");
		response_error = NETAGENT_MESSAGE_ERROR_NOT_REGISTERED;
		goto fail;
	}
	uuid_copy(netagent_uuid, registration->netagent->netagent_uuid);
	NETAGENT_UNLOCK(registration);
	NETAGENT_SESSION_UNLOCK(session);

	if (payload_length < sizeof(uuid_t)) {
		NETAGENTLOG0(LOG_ERR, "Assign message is too short");
		response_error = NETAGENT_MESSAGE_ERROR_INVALID_DATA;
		goto fail;
	}

	error = mbuf_copydata(packet, offset, sizeof(client_id), &client_id);
	if (error) {
		NETAGENTLOG(LOG_ERR, "Failed to read uuid for assign message: %d", error);
		response_error = NETAGENT_MESSAGE_ERROR_INTERNAL;
		goto fail;
	}

	size_t assigned_results_length = (payload_length - sizeof(client_id));
	if (assigned_results_length > 0) {
		assigned_results = kalloc_data( assigned_results_length, Z_WAITOK);
		if (assigned_results == NULL) {
			NETAGENTLOG(LOG_ERR, "Failed to allocate assign message (%lu bytes)", assigned_results_length);
			response_error = NETAGENT_MESSAGE_ERROR_INTERNAL;
			goto fail;
		}

		error = mbuf_copydata(packet, offset + sizeof(client_id), assigned_results_length, assigned_results);
		if (error) {
			kfree_data(assigned_results, assigned_results_length);
			NETAGENTLOG(LOG_ERR, "Failed to read assign message: %d", error);
			response_error = NETAGENT_MESSAGE_ERROR_INTERNAL;
			goto fail;
		}
	}

	// Note that if the error is 0, NECP has taken over our malloc'ed buffer
	error = necp_assign_client_result(netagent_uuid, client_id, assigned_results, assigned_results_length);
	if (error) {
		kfree_data(assigned_results, assigned_results_length);
		NETAGENTLOG(LOG_ERR, "Client assignment failed: %d", error);
		response_error = NETAGENT_MESSAGE_ERROR_CANNOT_ASSIGN;
		goto fail;
	}

	NETAGENTLOG0(LOG_DEBUG, "Agent assigned nexus properties to client");
	netagent_send_success_response(session, NETAGENT_MESSAGE_TYPE_ASSIGN_NEXUS, message_id);
	return;
fail:
	netagent_send_error_response(session, NETAGENT_MESSAGE_TYPE_ASSIGN_NEXUS, message_id, response_error);
}

static errno_t
netagent_handle_assign_group_setopt(struct netagent_session *session, u_int8_t * __sized_by(payload_length)payload,
    size_t payload_length)
{
	errno_t response_error = 0;
	uuid_t client_id;
	uuid_t netagent_uuid;
	u_int8_t *assigned_group_members = NULL;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = ENOENT;
		goto done;
	}

	if (payload == NULL) {
		NETAGENTLOG0(LOG_ERR, "No payload received");
		response_error = EINVAL;
		goto done;
	}

	NETAGENT_SESSION_LOCK(session);

	const size_t header_offset = (session->allow_multiple_registrations ? sizeof(uuid_t) : 0);
	if (payload_length < header_offset) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Assign message is too short");
		response_error = EINVAL;
		goto done;
	}

	struct netagent_assign_nexus_message *assign_message = (struct netagent_assign_nexus_message *)(void *)((u_int8_t *)payload + header_offset);

	struct netagent_registration *registration = NULL;
	if (session->allow_multiple_registrations) {
		uuid_t agent_uuid = {};
		uuid_copy(agent_uuid, payload);
		registration = netagent_session_find_agent_with_uuid_and_lock(session, agent_uuid, false, false);
	} else {
		registration = netagent_session_access_agent_with_lock(session, false, false);
	}

	if (registration == NULL) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session has no agent to get");
		response_error = ENOENT;
		goto done;
	}

	uuid_copy(netagent_uuid, registration->netagent->netagent_uuid);
	NETAGENT_UNLOCK(registration);
	NETAGENT_SESSION_UNLOCK(session);

	if (payload_length < (header_offset + sizeof(uuid_t))) {
		NETAGENTLOG0(LOG_ERR, "Group assign message is too short");
		response_error = EINVAL;
		goto done;
	}

	memcpy(client_id, assign_message->assign_client_id, sizeof(client_id));
	size_t assigned_group_members_length = (payload_length - (header_offset + sizeof(client_id)));

	if (assigned_group_members_length > 0) {
		assigned_group_members = (u_int8_t *)kalloc_data(assigned_group_members_length, Z_WAITOK);
		if (assigned_group_members == NULL) {
			NETAGENTLOG(LOG_ERR, "Failed to allocate group assign message (%lu bytes)", assigned_group_members_length);
			response_error = ENOMEM;
			goto done;
		}
		memcpy(assigned_group_members, netagent_assign_message_get_necp_result(assign_message, assigned_group_members_length), assigned_group_members_length);
	}

	// Note that if the error is 0, NECP has taken over our malloc'ed buffer
	response_error = necp_assign_client_group_members(netagent_uuid, client_id, assigned_group_members, assigned_group_members_length);
	if (response_error != 0) {
		// necp_assign_client_group_members returns POSIX errors
		if (assigned_group_members != NULL) {
			kfree_data(assigned_group_members, assigned_group_members_length);
		}
		NETAGENTLOG(LOG_ERR, "Client group assignment failed: %d", response_error);
		goto done;
	}

	NETAGENTLOG0(LOG_DEBUG, "Agent assigned group members to client");
done:
	return response_error;
}

errno_t
netagent_handle_use_count_setopt(struct netagent_session *session, u_int8_t * __sized_by(payload_length)payload, size_t payload_length)
{
	errno_t response_error = 0;
	uint64_t use_count = 0;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = ENOENT;
		goto done;
	}

	if (payload == NULL) {
		NETAGENTLOG0(LOG_ERR, "No payload received");
		response_error = EINVAL;
		goto done;
	}

	NETAGENT_SESSION_LOCK(session);
	const size_t header_offset = (session->allow_multiple_registrations ? sizeof(uuid_t) : 0);
	const size_t expected_length = header_offset + sizeof(use_count);
	if (payload_length != expected_length) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG(LOG_ERR, "Payload length is invalid (%lu)", payload_length);
		response_error = EINVAL;
		goto done;
	}

	memcpy(&use_count, payload + header_offset, sizeof(use_count));

	struct netagent_registration *registration = NULL;
	if (session->allow_multiple_registrations) {
		uuid_t agent_uuid = {};
		uuid_copy(agent_uuid, payload);
		registration = netagent_session_find_agent_with_uuid_and_lock(session, agent_uuid, false, false);
	} else {
		registration = netagent_session_access_agent_with_lock(session, true, false);
	}

	if (registration == NULL) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session has no agent registered");
		response_error = ENOENT;
		goto done;
	}

	registration->use_count = use_count;
	NETAGENT_UNLOCK(registration);
	NETAGENT_SESSION_UNLOCK(session);

done:
	return response_error;
}

errno_t
netagent_handle_use_count_getopt(struct netagent_session *session, u_int8_t * __sized_by(*buffer_length)buffer, size_t *buffer_length)
{
	errno_t response_error = 0;
	uint64_t use_count = 0;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = ENOENT;
		goto done;
	}

	if (buffer == NULL) {
		NETAGENTLOG0(LOG_ERR, "No payload received");
		response_error = EINVAL;
		goto done;
	}

	NETAGENT_SESSION_LOCK(session);
	const size_t header_offset = (session->allow_multiple_registrations ? sizeof(uuid_t) : 0);
	const size_t expected_length = header_offset + sizeof(use_count);
	if (*buffer_length != expected_length) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG(LOG_ERR, "Buffer length is invalid (%lu)", *buffer_length);
		response_error = EINVAL;
		goto done;
	}

	struct netagent_registration *registration = NULL;
	if (session->allow_multiple_registrations) {
		uuid_t agent_uuid = {};
		uuid_copy(agent_uuid, buffer);
		registration = netagent_session_find_agent_with_uuid_and_lock(session, agent_uuid, false, false);
	} else {
		registration = netagent_session_access_agent_with_lock(session, false, false);
	}

	if (registration == NULL) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session has no agent registered");
		response_error = ENOENT;
		goto done;
	}

	use_count = registration->use_count;
	NETAGENT_UNLOCK(registration);
	NETAGENT_SESSION_UNLOCK(session);

	memcpy(buffer + header_offset, &use_count, sizeof(use_count));
	*buffer_length = (header_offset + sizeof(use_count));

done:
	return response_error;
}

static errno_t
netagent_handle_add_token_setopt(struct netagent_session *session, u_int8_t * __sized_by(token_length)token, size_t token_length)
{
	errno_t response_error = 0;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = ENOENT;
		goto done;
	}

	if (token == NULL) {
		NETAGENTLOG0(LOG_ERR, "No token received");
		response_error = EINVAL;
		goto done;
	}

	NETAGENT_SESSION_LOCK(session);
	const size_t header_offset = (session->allow_multiple_registrations ? sizeof(uuid_t) : 0);
	if (token_length > (header_offset + NETAGENT_MAX_DATA_SIZE) ||
	    token_length < header_offset) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG(LOG_ERR, "Token length is invalid (%lu)", token_length);
		response_error = EINVAL;
		goto done;
	}

	struct netagent_registration *registration = NULL;
	if (session->allow_multiple_registrations) {
		uuid_t agent_uuid = {};
		uuid_copy(agent_uuid, token);
		registration = netagent_session_find_agent_with_uuid_and_lock(session, agent_uuid, true, false);
	} else {
		registration = netagent_session_access_agent_with_lock(session, true, false);
	}

	if (registration == NULL) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session has no agent registered");
		response_error = ENOENT;
		goto done;
	}

	if (registration->token_count >= NETAGENT_MAX_TOKEN_COUNT) {
		NETAGENT_UNLOCK(registration);
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session cannot add more tokens");
		response_error = EINVAL;
		goto done;
	}

	struct netagent_token *token_struct = NULL;

	token_struct = kalloc_type(struct netagent_token, Z_WAITOK | Z_ZERO | Z_NOFAIL);
	token_struct->token_bytes = kalloc_data((token_length - header_offset), Z_WAITOK | Z_NOFAIL);
	token_struct->token_length = (u_int32_t)(token_length - header_offset);
	memcpy(token_struct->token_bytes, token + header_offset, (token_length - header_offset));

	TAILQ_INSERT_TAIL(&registration->token_list, token_struct, token_chain);

	registration->token_count++;

	// Reset deadline time, now that there are more than 0 tokens
	registration->need_tokens_event_deadline = 0;

	NETAGENT_UNLOCK(registration);
	NETAGENT_SESSION_UNLOCK(session);
done:
	return response_error;
}

static errno_t
netagent_handle_flush_tokens_setopt(struct netagent_session *session, u_int8_t * __sized_by(buffer_length)buffer, size_t buffer_length)
{
	errno_t response_error = 0;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = ENOENT;
		goto done;
	}

	NETAGENT_SESSION_LOCK(session);
	struct netagent_registration *registration = NULL;
	if (session->allow_multiple_registrations) {
		if (buffer_length != sizeof(uuid_t)) {
			NETAGENT_SESSION_UNLOCK(session);
			NETAGENTLOG(LOG_ERR, "Buffer length is invalid (%lu)", buffer_length);
			response_error = EINVAL;
			goto done;
		}

		uuid_t agent_uuid = {};
		uuid_copy(agent_uuid, buffer);
		registration = netagent_session_find_agent_with_uuid_and_lock(session, agent_uuid, true, false);
	} else {
		registration = netagent_session_access_agent_with_lock(session, true, false);
	}

	if (registration == NULL) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session has no agent registered");
		response_error = ENOENT;
		goto done;
	}

	struct netagent_token *search_token = NULL;
	struct netagent_token *temp_token = NULL;
	TAILQ_FOREACH_SAFE(search_token, &registration->token_list, token_chain, temp_token) {
		TAILQ_REMOVE(&registration->token_list, search_token, token_chain);
		netagent_token_free(search_token);
	}
	registration->token_count = 0;
	NETAGENT_UNLOCK(registration);
	NETAGENT_SESSION_UNLOCK(session);
done:
	return response_error;
}

static errno_t
netagent_handle_token_count_getopt(struct netagent_session *session, u_int8_t * __sized_by(*buffer_length)buffer, size_t *buffer_length)
{
	errno_t response_error = 0;
	uint32_t token_count = 0;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = ENOENT;
		goto done;
	}

	if (buffer == NULL) {
		NETAGENTLOG0(LOG_ERR, "No payload received");
		response_error = EINVAL;
		goto done;
	}

	NETAGENT_SESSION_LOCK(session);
	const size_t header_offset = (session->allow_multiple_registrations ? sizeof(uuid_t) : 0);
	const size_t expected_length = header_offset + sizeof(token_count);
	if (*buffer_length != expected_length) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG(LOG_ERR, "Buffer length is invalid (%lu)", *buffer_length);
		response_error = EINVAL;
		goto done;
	}

	struct netagent_registration *registration = NULL;
	if (session->allow_multiple_registrations) {
		uuid_t agent_uuid = {};
		uuid_copy(agent_uuid, buffer);
		registration = netagent_session_find_agent_with_uuid_and_lock(session, agent_uuid, false, false);
	} else {
		registration = netagent_session_access_agent_with_lock(session, false, false);
	}

	if (registration == NULL) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session has no agent registered");
		response_error = ENOENT;
		goto done;
	}

	token_count = registration->token_count;
	NETAGENT_UNLOCK(registration);
	NETAGENT_SESSION_UNLOCK(session);

	memcpy(buffer + header_offset, &token_count, sizeof(token_count));
	*buffer_length = (header_offset + sizeof(token_count));

done:
	return response_error;
}

static errno_t
netagent_handle_token_low_water_setopt(struct netagent_session *session, u_int8_t * __sized_by(buffer_length)buffer, size_t buffer_length)
{
	errno_t response_error = 0;
	uint32_t token_low_water = 0;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = ENOENT;
		goto done;
	}

	if (buffer == NULL) {
		NETAGENTLOG0(LOG_ERR, "No payload received");
		response_error = EINVAL;
		goto done;
	}

	NETAGENT_SESSION_LOCK(session);
	const size_t header_offset = (session->allow_multiple_registrations ? sizeof(uuid_t) : 0);
	const size_t expected_length = header_offset + sizeof(token_low_water);
	if (buffer_length != expected_length) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG(LOG_ERR, "Buffer length is invalid (%lu)", buffer_length);
		response_error = EINVAL;
		goto done;
	}

	memcpy(&token_low_water, buffer + header_offset, sizeof(token_low_water));

	struct netagent_registration *registration = NULL;
	if (session->allow_multiple_registrations) {
		uuid_t agent_uuid = {};
		uuid_copy(agent_uuid, buffer);
		registration = netagent_session_find_agent_with_uuid_and_lock(session, agent_uuid, true, false);
	} else {
		registration = netagent_session_access_agent_with_lock(session, true, false);
	}

	if (registration == NULL) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session has no agent registered");
		response_error = ENOENT;
		goto done;
	}

	registration->token_low_water = token_low_water;
	NETAGENT_UNLOCK(registration);
	NETAGENT_SESSION_UNLOCK(session);

done:
	return response_error;
}

static errno_t
netagent_handle_token_low_water_getopt(struct netagent_session *session, u_int8_t * __sized_by(*buffer_length)buffer, size_t *buffer_length)
{
	errno_t response_error = 0;
	uint32_t token_low_water = 0;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = ENOENT;
		goto done;
	}

	if (buffer == NULL) {
		NETAGENTLOG0(LOG_ERR, "No payload received");
		response_error = EINVAL;
		goto done;
	}

	NETAGENT_SESSION_LOCK(session);
	const size_t header_offset = (session->allow_multiple_registrations ? sizeof(uuid_t) : 0);
	const size_t expected_length = header_offset + sizeof(token_low_water);
	if (*buffer_length != expected_length) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG(LOG_ERR, "Buffer length is invalid (%lu)", *buffer_length);
		response_error = EINVAL;
		goto done;
	}

	struct netagent_registration *registration = NULL;
	if (session->allow_multiple_registrations) {
		uuid_t agent_uuid = {};
		uuid_copy(agent_uuid, buffer);
		registration = netagent_session_find_agent_with_uuid_and_lock(session, agent_uuid, false, false);
	} else {
		registration = netagent_session_access_agent_with_lock(session, false, false);
	}

	if (registration == NULL) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session has no agent registered");
		response_error = ENOENT;
		goto done;
	}

	token_low_water = registration->token_low_water;
	NETAGENT_UNLOCK(registration);
	NETAGENT_SESSION_UNLOCK(session);

	memcpy(buffer + header_offset, &token_low_water, sizeof(token_low_water));
	*buffer_length = (header_offset + sizeof(token_low_water));

done:
	return response_error;
}

static errno_t
netagent_handle_reset_client_error_setopt(struct netagent_session *session, u_int8_t * __sized_by(payload_length)payload, size_t payload_length)
{
	errno_t response_error = 0;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = ENOENT;
		goto done;
	}

	NETAGENT_SESSION_LOCK(session);
	struct netagent_registration *registration = NULL;
	if (session->allow_multiple_registrations) {
		if (payload_length != sizeof(uuid_t)) {
			NETAGENT_SESSION_UNLOCK(session);
			NETAGENTLOG(LOG_ERR, "Payload length is invalid (%lu)", payload_length);
			response_error = EINVAL;
			goto done;
		}

		uuid_t agent_uuid = {};
		uuid_copy(agent_uuid, payload);
		registration = netagent_session_find_agent_with_uuid_and_lock(session, agent_uuid, true, false);
	} else {
		registration = netagent_session_access_agent_with_lock(session, true, false);
	}

	if (registration == NULL) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session has no agent registered");
		response_error = ENOENT;
		goto done;
	}

	struct netagent_token *search_token = NULL;
	struct netagent_token *temp_token = NULL;
	TAILQ_FOREACH_SAFE(search_token, &registration->token_list, token_chain, temp_token) {
		TAILQ_REMOVE(&registration->token_list, search_token, token_chain);
		netagent_token_free(search_token);
	}
	registration->last_client_error = 0;
	registration->client_error_count = 0;

	NETAGENT_UNLOCK(registration);
	NETAGENT_SESSION_UNLOCK(session);
done:
	return response_error;
}

static errno_t
netagent_handle_enable_session_mode_setopt(struct netagent_session *session, __unused u_int8_t *payload, __unused size_t payload_length)
{
	errno_t response_error = 0;

	if (session == NULL) {
		NETAGENTLOG0(LOG_ERR, "Failed to find session");
		response_error = ENOENT;
		goto done;
	}

	NETAGENT_SESSION_LOCK(session);
	if (!TAILQ_EMPTY(&session->registrations)) {
		NETAGENT_SESSION_UNLOCK(session);
		NETAGENTLOG0(LOG_ERR, "Session already has agent registered");
		response_error = EEXIST;
		goto done;
	}

	session->allow_multiple_registrations = true;
	NETAGENT_SESSION_UNLOCK(session);
done:
	return response_error;
}

static struct netagent_registration *
netagent_find_agent_with_uuid_and_lock(uuid_t uuid, bool exclusively, bool ignore_lock)
{
	NETAGENT_LIST_ASSERT_LOCKED();

	struct netagent_registration *registration = NULL;
	LIST_FOREACH(registration, &shared_netagent_list, global_chain) {
		if (uuid_compare(registration->netagent->netagent_uuid, uuid) == 0) {
			if (!ignore_lock) {
				if (exclusively) {
					NETAGENT_LOCK_EXCLUSIVE(registration);
				} else {
					NETAGENT_LOCK_SHARED(registration);
				}
			}
			return registration;
		}
	}

	return NULL;
}

static struct netagent_registration *
netagent_session_find_agent_with_uuid_and_lock(struct netagent_session *session, uuid_t uuid, bool exclusively, bool ignore_lock)
{
	NETAGENT_SESSION_ASSERT_LOCKED(session);

	struct netagent_registration *registration = NULL;
	TAILQ_FOREACH(registration, &session->registrations, session_chain) {
		if (uuid_compare(registration->netagent->netagent_uuid, uuid) == 0) {
			if (!ignore_lock) {
				if (exclusively) {
					NETAGENT_LOCK_EXCLUSIVE(registration);
				} else {
					NETAGENT_LOCK_SHARED(registration);
				}
			}
			return registration;
		}
	}

	return NULL;
}

static struct netagent_registration *
netagent_session_access_agent_with_lock(struct netagent_session *session, bool exclusively, bool ignore_lock)
{
	NETAGENT_SESSION_ASSERT_LOCKED(session);

	struct netagent_registration *registration = TAILQ_FIRST(&session->registrations);
	if (registration != NULL) {
		if (!ignore_lock) {
			if (exclusively) {
				NETAGENT_LOCK_EXCLUSIVE(registration);
			} else {
				NETAGENT_LOCK_SHARED(registration);
			}
		}
	}

	return registration;
}

void
netagent_post_updated_interfaces(uuid_t uuid)
{
	if (!uuid_is_null(uuid)) {
		netagent_post_event(uuid, KEV_NETAGENT_UPDATED_INTERFACES, true, false);
	} else {
		NETAGENTLOG0(LOG_DEBUG, "Interface event with no associated agent");
	}
}

static u_int32_t
netagent_dump_get_data_size_locked()
{
	NETAGENT_LIST_ASSERT_LOCKED();

	struct netagent_registration *search_netagent = NULL;
	u_int32_t total_netagent_data_size = 0;
	// Traverse the shared list to know how much data the client needs to allocate to get the list of agent UUIDs
	LIST_FOREACH(search_netagent, &shared_netagent_list, global_chain) {
		total_netagent_data_size += sizeof(search_netagent->netagent->netagent_uuid);
	}
	return total_netagent_data_size;
}

static void
netagent_dump_copy_data_locked(u_int8_t * __sized_by(buffer_length)buffer, u_int32_t buffer_length)
{
	NETAGENT_LIST_ASSERT_LOCKED();

	size_t response_size = 0;
	u_int8_t * __indexable cursor = NULL;
	struct netagent_registration * __single search_netagent = NULL;

	response_size = buffer_length; // We already know that buffer_length is the same as total_netagent_data_size.
	cursor = buffer;
	LIST_FOREACH(search_netagent, &shared_netagent_list, global_chain) {
		memcpy(cursor, search_netagent->netagent->netagent_uuid, sizeof(search_netagent->netagent->netagent_uuid));
		cursor += sizeof(search_netagent->netagent->netagent_uuid);
	}
}

int
netagent_ioctl(u_long cmd, caddr_t __sized_by(IOCPARM_LEN(cmd)) data)
{
	int error = 0;

	switch (cmd) {
	case SIOCGIFAGENTLIST32:
	case SIOCGIFAGENTLIST64: {
		/* Check entitlement if the client requests agent dump */
		errno_t cred_result = priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_NECP_POLICIES, 0);
		if (cred_result != 0) {
			NETAGENTLOG0(LOG_ERR, "Client does not hold the necessary entitlement to get netagent information");
			return EINVAL;
		}
		break;
	}
	default:
		break;
	}

	NETAGENT_LIST_LOCK_SHARED();
	switch (cmd) {
	case SIOCGIFAGENTDATA32: {
		struct netagent_req32 *ifsir32 = (struct netagent_req32 *)(void *)data;
		struct netagent_registration *registration = netagent_find_agent_with_uuid_and_lock(ifsir32->netagent_uuid, false, false);
		if (registration == NULL) {
			error = ENOENT;
			break;
		}
		uuid_copy(ifsir32->netagent_uuid, registration->netagent->netagent_uuid);
		memcpy(ifsir32->netagent_domain, registration->netagent->netagent_domain, sizeof(ifsir32->netagent_domain));
		memcpy(ifsir32->netagent_type, registration->netagent->netagent_type, sizeof(ifsir32->netagent_type));
		memcpy(ifsir32->netagent_desc, registration->netagent->netagent_desc, sizeof(ifsir32->netagent_desc));
		ifsir32->netagent_flags = registration->netagent->netagent_flags;
		if (ifsir32->netagent_data_size == 0) {
			// First pass, client wants data size
			ifsir32->netagent_data_size = registration->netagent->netagent_data_size;
		} else if (ifsir32->netagent_data != USER_ADDR_NULL &&
		    ifsir32->netagent_data_size == registration->netagent->netagent_data_size) {
			// Second pass, client wants data buffer filled out
			error = copyout(netagent_get_data(registration->netagent), ifsir32->netagent_data, registration->netagent->netagent_data_size);
		} else {
			error = EINVAL;
		}
		NETAGENT_UNLOCK(registration);
		break;
	}
	case SIOCGIFAGENTDATA64: {
		struct netagent_req64 *ifsir64 = (struct netagent_req64 *)(void *)data;
		struct netagent_registration *registration = netagent_find_agent_with_uuid_and_lock(ifsir64->netagent_uuid, false, false);
		if (registration == NULL) {
			error = ENOENT;
			break;
		}
		uuid_copy(ifsir64->netagent_uuid, registration->netagent->netagent_uuid);
		memcpy(ifsir64->netagent_domain, registration->netagent->netagent_domain, sizeof(ifsir64->netagent_domain));
		memcpy(ifsir64->netagent_type, registration->netagent->netagent_type, sizeof(ifsir64->netagent_type));
		memcpy(ifsir64->netagent_desc, registration->netagent->netagent_desc, sizeof(ifsir64->netagent_desc));
		ifsir64->netagent_flags = registration->netagent->netagent_flags;
		if (ifsir64->netagent_data_size == 0) {
			// First pass, client wants data size
			ifsir64->netagent_data_size = registration->netagent->netagent_data_size;
		} else if (ifsir64->netagent_data != USER_ADDR_NULL &&
		    ifsir64->netagent_data_size == registration->netagent->netagent_data_size) {
			// Second pass, client wants data buffer filled out
			error = copyout(netagent_get_data(registration->netagent), ifsir64->netagent_data, registration->netagent->netagent_data_size);
		} else {
			error = EINVAL;
		}
		NETAGENT_UNLOCK(registration);
		break;
	}
	case SIOCGIFAGENTLIST32: {
		struct netagentlist_req32 *ifsir32 = (struct netagentlist_req32 *)(void *)data;
		if (ifsir32->data_size == 0) {
			// First pass, client wants data size
			ifsir32->data_size = netagent_dump_get_data_size_locked();
		} else if (ifsir32->data != USER_ADDR_NULL &&
		    ifsir32->data_size > 0 &&
		    ifsir32->data_size == netagent_dump_get_data_size_locked()) {
			// Second pass, client wants data buffer filled out
			u_int8_t *response = NULL;
			response = (u_int8_t *)kalloc_data(ifsir32->data_size, Z_NOWAIT | Z_ZERO);
			if (response == NULL) {
				error = ENOMEM;
				break;
			}

			netagent_dump_copy_data_locked(response, ifsir32->data_size);
			error = copyout(response, ifsir32->data, ifsir32->data_size);
			kfree_data(response, ifsir32->data_size);
		} else {
			error = EINVAL;
		}
		break;
	}
	case SIOCGIFAGENTLIST64: {
		struct netagentlist_req64 *ifsir64 = (struct netagentlist_req64 *)(void *)data;
		if (ifsir64->data_size == 0) {
			// First pass, client wants data size
			ifsir64->data_size = netagent_dump_get_data_size_locked();
		} else if (ifsir64->data != USER_ADDR_NULL &&
		    ifsir64->data_size > 0 &&
		    ifsir64->data_size == netagent_dump_get_data_size_locked()) {
			// Second pass, client wants data buffer filled out
			u_int8_t *response = NULL;
			response = (u_int8_t *)kalloc_data(ifsir64->data_size, Z_NOWAIT | Z_ZERO);
			if (response == NULL) {
				error = ENOMEM;
				break;
			}

			netagent_dump_copy_data_locked(response, ifsir64->data_size);
			error = copyout(response, ifsir64->data, ifsir64->data_size);
			kfree_data(response, ifsir64->data_size);
		} else {
			error = EINVAL;
		}
		break;
	}
	default: {
		error = EINVAL;
		break;
	}
	}
	NETAGENT_LIST_UNLOCK();
	return error;
}

u_int32_t
netagent_get_flags(uuid_t uuid)
{
	u_int32_t flags = 0;
	NETAGENT_LIST_LOCK_SHARED();
	struct netagent_registration *registration = netagent_find_agent_with_uuid_and_lock(uuid, false, false);
	if (registration != NULL) {
		flags = registration->netagent->netagent_flags;
		NETAGENT_UNLOCK(registration);
	} else {
		NETAGENTLOG0(LOG_DEBUG, "Flags requested for invalid netagent");
	}
	NETAGENT_LIST_UNLOCK();

	return flags;
}

errno_t
netagent_set_flags(uuid_t uuid, u_int32_t flags)
{
	errno_t error = 0;
	bool updated = false;

	NETAGENT_LIST_LOCK_SHARED();
	struct netagent_registration *registration = netagent_find_agent_with_uuid_and_lock(uuid, true, false);
	if (registration != NULL) {
		// Don't allow the clients to clear
		// NETAGENT_FLAG_REGISTERED.
		uint32_t registered =
		    registration->netagent->netagent_flags & NETAGENT_FLAG_REGISTERED;
		flags |= registered;
		if (registration->netagent->netagent_flags != flags) {
			registration->netagent->netagent_flags = flags;
			registration->generation = g_next_generation++;
			updated = true;
		}
		NETAGENT_UNLOCK(registration);
	} else {
		NETAGENTLOG0(LOG_DEBUG,
		    "Attempt to set flags for invalid netagent");
		error = ENOENT;
	}
	NETAGENT_LIST_UNLOCK();
	if (updated) {
		netagent_post_event(uuid, KEV_NETAGENT_UPDATED, true, false);
	}

	return error;
}

u_int32_t
netagent_get_generation(uuid_t uuid)
{
	u_int32_t generation = 0;
	NETAGENT_LIST_LOCK_SHARED();
	struct netagent_registration *registration = netagent_find_agent_with_uuid_and_lock(uuid, false, false);
	if (registration != NULL) {
		generation = registration->generation;
		NETAGENT_UNLOCK(registration);
	} else {
		NETAGENTLOG0(LOG_DEBUG, "Generation requested for invalid netagent");
	}
	NETAGENT_LIST_UNLOCK();

	return generation;
}

bool
netagent_get_agent_domain_and_type(uuid_t uuid, char * __sized_by(NETAGENT_DOMAINSIZE)domain, char * __sized_by(NETAGENT_TYPESIZE)type)
{
	bool found = FALSE;
	if (domain == NULL || type == NULL) {
		NETAGENTLOG(LOG_ERR, "Invalid arguments for netagent_get_agent_domain_and_type %p %p", domain, type);
		return FALSE;
	}

	NETAGENT_LIST_LOCK_SHARED();
	struct netagent_registration *registration = netagent_find_agent_with_uuid_and_lock(uuid, false, false);
	if (registration != NULL) {
		found = TRUE;
		memcpy(domain, registration->netagent->netagent_domain, NETAGENT_DOMAINSIZE);
		memcpy(type, registration->netagent->netagent_type, NETAGENT_TYPESIZE);
		NETAGENT_UNLOCK(registration);
	} else {
		NETAGENTLOG0(LOG_ERR, "Type requested for invalid netagent");
	}
	NETAGENT_LIST_UNLOCK();

	return found;
}

int
netagent_kernel_trigger(uuid_t uuid)
{
	int error = 0;

	NETAGENT_LIST_LOCK_SHARED();
	struct netagent_registration *registration = netagent_find_agent_with_uuid_and_lock(uuid, false, false);
	if (registration == NULL) {
		NETAGENTLOG0(LOG_ERR, "Requested netagent for kernel trigger could not be found");
		error = ENOENT;
		goto done;
	}

	if ((registration->netagent->netagent_flags & NETAGENT_FLAG_KERNEL_ACTIVATED) == 0) {
		NETAGENTLOG0(LOG_ERR, "Requested netagent for kernel trigger is not kernel activated");
		// Agent does not accept kernel triggers
		error = EINVAL;
		goto done;
	}

	if ((registration->netagent->netagent_flags & NETAGENT_FLAG_ACTIVE)) {
		// Agent already active
		NETAGENTLOG0(LOG_INFO, "Requested netagent for kernel trigger is already active");
		error = 0;
		goto done;
	}

	error = netagent_send_trigger(registration, current_proc(), NETAGENT_TRIGGER_FLAG_KERNEL, NETAGENT_MESSAGE_TYPE_TRIGGER);
	NETAGENTLOG((error ? LOG_ERR : LOG_INFO), "Triggered netagent from kernel (error %d)", error);
done:
	if (registration != NULL) {
		NETAGENT_UNLOCK(registration);
	}
	NETAGENT_LIST_UNLOCK();
	return error;
}

int
netagent_client_message_with_params(uuid_t agent_uuid,
    uuid_t necp_client_uuid,
    pid_t pid,
    void *handle,
    u_int8_t message_type,
    struct necp_client_agent_parameters *parameters,
    void * __sized_by(*assigned_results_length) *assigned_results,
    size_t *assigned_results_length)
{
	int error = 0;

	if (message_type != NETAGENT_MESSAGE_TYPE_CLIENT_TRIGGER &&
	    message_type != NETAGENT_MESSAGE_TYPE_CLIENT_ASSERT &&
	    message_type != NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT &&
	    message_type != NETAGENT_MESSAGE_TYPE_CLIENT_ERROR &&
	    message_type != NETAGENT_MESSAGE_TYPE_REQUEST_NEXUS &&
	    message_type != NETAGENT_MESSAGE_TYPE_CLOSE_NEXUS &&
	    message_type != NETAGENT_MESSAGE_TYPE_ABORT_NEXUS &&
	    message_type != NETAGENT_MESSAGE_TYPE_ADD_GROUP_MEMBERS &&
	    message_type != NETAGENT_MESSAGE_TYPE_REMOVE_GROUP_MEMBERS &&
	    message_type != NETAGENT_MESSAGE_TYPE_UPDATE_NEXUS) {
		NETAGENTLOG(LOG_ERR, "Client netagent message type (%d) is invalid", message_type);
		return EINVAL;
	}

	NETAGENT_LIST_LOCK_SHARED();
	bool should_unlock_list = true;
	bool should_unlock_registration = true;
	struct netagent_registration *registration = netagent_find_agent_with_uuid_and_lock(agent_uuid, false, false);
	if (registration == NULL) {
		NETAGENTLOG0(LOG_DEBUG, "Requested netagent for nexus instance could not be found");
		error = ENOENT;
		goto done;
	}

	if (message_type == NETAGENT_MESSAGE_TYPE_CLIENT_TRIGGER) {
		if ((registration->netagent->netagent_flags & NETAGENT_FLAG_USER_ACTIVATED) == 0) {
			// Agent does not accept user triggers
			// Don't log, since this is a common case used to trigger events that cellular data is blocked, etc.
			error = ENOTSUP;


			pid_t report_pid = 0;
			uuid_t report_proc_uuid = {};
			if (parameters != NULL) {
				report_pid = parameters->u.nexus_request.epid;
				uuid_copy(report_proc_uuid, parameters->u.nexus_request.euuid);
			} else {
				struct proc *p = current_proc();
				if (p != NULL) {
					report_pid = proc_pid(p);
					proc_getexecutableuuid(p, report_proc_uuid, sizeof(report_proc_uuid));
				}
			}
			netagent_send_cellular_failed_event(registration, report_pid, report_proc_uuid);
			goto done;
		}
	} else if (message_type == NETAGENT_MESSAGE_TYPE_REQUEST_NEXUS ||
	    message_type == NETAGENT_MESSAGE_TYPE_CLOSE_NEXUS ||
	    message_type == NETAGENT_MESSAGE_TYPE_ABORT_NEXUS ||
	    message_type == NETAGENT_MESSAGE_TYPE_UPDATE_NEXUS) {
		bool is_nexus_agent = ((registration->netagent->netagent_flags &
		    (NETAGENT_FLAG_NEXUS_PROVIDER |
		    NETAGENT_FLAG_NEXUS_LISTENER |
		    NETAGENT_FLAG_CUSTOM_IP_NEXUS |
		    NETAGENT_FLAG_CUSTOM_ETHER_NEXUS |
		    NETAGENT_FLAG_INTERPOSE_NEXUS)) != 0);
		if (!is_nexus_agent) {
			NETAGENTLOG0(LOG_ERR, "Requested netagent for nexus instance is not a nexus provider");
			// Agent is not a nexus provider
			error = EINVAL;
			goto done;
		}

		if ((registration->netagent->netagent_flags & NETAGENT_FLAG_ACTIVE) == 0) {
			// Agent not active
			NETAGENTLOG0(LOG_INFO, "Requested netagent for nexus instance is not active");
			error = EINVAL;
			goto done;
		}
	} else if (message_type == NETAGENT_MESSAGE_TYPE_ADD_GROUP_MEMBERS ||
	    message_type == NETAGENT_MESSAGE_TYPE_REMOVE_GROUP_MEMBERS) {
		bool is_group_agent = ((registration->netagent->netagent_flags & (NETAGENT_FLAG_SUPPORTS_GROUPS)) != 0);
		if (!is_group_agent) {
			NETAGENTLOG0(LOG_ERR, "Requested netagent for group operation is not a group provider");
			error = EINVAL;
			goto done;
		}

		if ((registration->netagent->netagent_flags & NETAGENT_FLAG_ACTIVE) == 0) {
			// Agent not active
			NETAGENTLOG0(LOG_INFO, "Requested netagent for group operation is not active");
			error = EINVAL;
			goto done;
		}
	}

	if (registration->control_unit == 0) {
		if (registration->event_handler == NULL) {
			// No event handler registered for kernel agent
			error = EINVAL;
		} else {
			// We hold the registration lock during the event handler callout, so it is expected
			// that the event handler will not lead to any registrations or unregistrations
			// of network agents.
			// We release the list lock before calling the event handler to allow other threads
			// to access the list while the event is processing.
			NETAGENT_LIST_UNLOCK();
			should_unlock_list = false;
			error = registration->event_handler(message_type, necp_client_uuid, pid, handle,
			    registration->event_context, parameters,
			    assigned_results, assigned_results_length);
			if (error != 0) {
				VERIFY(assigned_results == NULL || *assigned_results == NULL);
				VERIFY(assigned_results_length == NULL || *assigned_results_length == 0);
			}
		}
	} else {
		// ABORT_NEXUS is kernel-private, so translate it for userspace nexus
		if (message_type == NETAGENT_MESSAGE_TYPE_ABORT_NEXUS) {
			message_type = NETAGENT_MESSAGE_TYPE_CLOSE_NEXUS;
		}

		if (message_type == NETAGENT_MESSAGE_TYPE_CLIENT_ERROR) {
			const int32_t client_error = parameters->u.error.error;
			const bool force_report = parameters->u.error.force_report;
			if (registration->last_client_error != client_error || // Always notify for an error change
			    force_report || // Always notify if force reporting was requested
			    (client_error == 0 && registration->client_error_count == 0) || // Only notify once for no-error
			    (client_error != 0 && registration->client_error_count < NETAGENT_MAX_CLIENT_ERROR_COUNT)) {
				if (NETAGENT_LOCK_SHARED_TO_EXCLUSIVE(registration)) {
					if (registration->last_client_error != client_error) {
						registration->last_client_error = client_error;
						registration->client_error_count = 1;
					} else {
						registration->client_error_count++;
					}
					error = netagent_send_error_message(registration, necp_client_uuid, message_type, client_error);
				} else {
					// If NETAGENT_LOCK_SHARED_TO_EXCLUSIVE fails, it unlocks automatically
					should_unlock_registration = false;
				}
			}
		} else if (message_type == NETAGENT_MESSAGE_TYPE_ADD_GROUP_MEMBERS ||
		    message_type == NETAGENT_MESSAGE_TYPE_REMOVE_GROUP_MEMBERS) {
			error = netagent_send_group_message(registration, necp_client_uuid, message_type, &parameters->u.group_members);
		} else {
			error = netagent_send_client_message(registration, necp_client_uuid, message_type);
		}
		if (error == 0 && message_type == NETAGENT_MESSAGE_TYPE_CLIENT_TRIGGER) {
			if (NETAGENT_LOCK_SHARED_TO_EXCLUSIVE(registration)) {
				// Grab the lock exclusively to add a pending client to the list
				struct netagent_client *new_pending_client = NULL;
				new_pending_client = kalloc_type(struct netagent_client, Z_WAITOK);
				if (new_pending_client == NULL) {
					NETAGENTLOG0(LOG_ERR, "Failed to allocate client for trigger");
				} else {
					uuid_copy(new_pending_client->client_id, necp_client_uuid);
					if (parameters != NULL) {
						new_pending_client->client_pid = parameters->u.nexus_request.epid;
						uuid_copy(new_pending_client->client_proc_uuid, parameters->u.nexus_request.euuid);
					} else {
						struct proc *p = current_proc();
						if (p != NULL) {
							new_pending_client->client_pid = proc_pid(p);
							proc_getexecutableuuid(p, new_pending_client->client_proc_uuid, sizeof(new_pending_client->client_proc_uuid));
						}
					}
					LIST_INSERT_HEAD(&registration->pending_triggers_list, new_pending_client, client_chain);
				}
			} else {
				// If NETAGENT_LOCK_SHARED_TO_EXCLUSIVE fails, it unlocks automatically
				should_unlock_registration = false;
			}
		}
	}
	NETAGENTLOG(((error && error != ENOENT) ? LOG_ERR : LOG_INFO), "Send message %d for client (error %d)", message_type, error);
	if (message_type == NETAGENT_MESSAGE_TYPE_CLIENT_TRIGGER) {
		uuid_string_t uuid_str;
		uuid_unparse(agent_uuid, uuid_str);
		NETAGENTLOG(LOG_NOTICE, "Triggered network agent %s, error = %d", uuid_str, error);
	}
done:
	if (should_unlock_registration && registration != NULL) {
		NETAGENT_UNLOCK(registration);
	}
	if (should_unlock_list) {
		NETAGENT_LIST_UNLOCK();
	}
	return error;
}

int
netagent_client_message(uuid_t agent_uuid, uuid_t necp_client_uuid, pid_t pid, void *handle, u_int8_t message_type)
{
	size_t dummy_length = 0;
	void *dummy_results __sized_by(dummy_length) = NULL;

	return netagent_client_message_with_params(agent_uuid, necp_client_uuid, pid, handle, message_type, NULL, &dummy_results, &dummy_length);
}

int
netagent_use(uuid_t agent_uuid, uint64_t *out_use_count)
{
	int error = 0;

	NETAGENT_LIST_LOCK_SHARED();
	struct netagent_registration *registration = netagent_find_agent_with_uuid_and_lock(agent_uuid, true, false);
	if (registration == NULL) {
		NETAGENTLOG0(LOG_ERR, "netagent_assert: Requested netagent UUID is not registered");
		error = ENOENT;
		goto done;
	}

	uint64_t current_count = registration->use_count;
	registration->use_count++;

	if (out_use_count != NULL) {
		*out_use_count = current_count;
	}

done:
	if (registration != NULL) {
		NETAGENT_UNLOCK(registration);
	}
	NETAGENT_LIST_UNLOCK();
	return error;
}

int
netagent_copyout(uuid_t agent_uuid, user_addr_t user_addr, u_int32_t user_size)
{
	int error = 0;

	NETAGENT_LIST_LOCK_SHARED();
	struct netagent_registration *registration = netagent_find_agent_with_uuid_and_lock(agent_uuid, false, false);
	if (registration == NULL) {
		NETAGENTLOG0(LOG_DEBUG, "Requested netagent for nexus instance could not be found");
		error = ENOENT;
		goto done;
	}

	u_int32_t total_size = (sizeof(struct netagent) + registration->netagent->netagent_data_size);
	if (user_size < total_size) {
		NETAGENTLOG(LOG_ERR, "Provided user buffer is too small (%u < %u)", user_size, total_size);
		error = EINVAL;
		goto done;
	}

	u_int8_t *ptr = __unsafe_forge_bidi_indexable(u_int8_t *, registration->netagent, total_size);
	error = copyout(ptr, user_addr, total_size);

	NETAGENTLOG((error ? LOG_ERR : LOG_DEBUG), "Copied agent content (error %d)", error);
done:
	if (registration != NULL) {
		NETAGENT_UNLOCK(registration);
	}
	NETAGENT_LIST_UNLOCK();
	return error;
}

#define NETAGENT_TOKEN_EVENT_INTERVAL_NSEC (NSEC_PER_SEC * 10) // Only fire repeated events up to once every 10 seconds

int
netagent_acquire_token(uuid_t agent_uuid, user_addr_t user_addr, u_int32_t user_size, int *retval)
{
	int error = 0;

	NETAGENT_LIST_LOCK_SHARED();
	struct netagent_registration *registration = netagent_find_agent_with_uuid_and_lock(agent_uuid, true, false);
	if (registration == NULL) {
		NETAGENTLOG0(LOG_DEBUG, "Network agent for request UUID could not be found");
		error = ENOENT;
		goto done;
	}

	struct netagent_token *token = TAILQ_FIRST(&registration->token_list);
	if (token == NULL) {
		NETAGENTLOG0(LOG_DEBUG, "Network agent does not have any tokens");
		if (registration->token_low_water != 0) {
			// Only fire an event if one hasn't occurred in the last 10 seconds
			if (mach_absolute_time() >= registration->need_tokens_event_deadline) {
				int event_error = netagent_send_tokens_needed(registration);
				if (event_error == 0) {
					// Reset the deadline
					uint64_t deadline = 0;
					nanoseconds_to_absolutetime(NETAGENT_TOKEN_EVENT_INTERVAL_NSEC, &deadline);
					clock_absolutetime_interval_to_deadline(deadline, &deadline);
					registration->need_tokens_event_deadline = deadline;
				}
			}
		}
		error = ENODATA;
		goto done;
	}

	if (user_size < token->token_length) {
		NETAGENTLOG(LOG_ERR, "Provided user buffer is too small (%u < %u)", user_size, token->token_length);
		error = EMSGSIZE;
		goto done;
	}

	error = copyout(token->token_bytes, user_addr, token->token_length);
	if (error == 0) {
		*retval = (int)token->token_length;
	}

	NETAGENTLOG((error ? LOG_ERR : LOG_DEBUG), "Copied token content (error %d)", error);

	TAILQ_REMOVE(&registration->token_list, token, token_chain);
	netagent_token_free(token);
	if (registration->token_count > 0) {
		registration->token_count--;
	}
	if (registration->token_count < registration->token_low_water) {
		(void)netagent_send_tokens_needed(registration);
	}
done:
	if (registration != NULL) {
		NETAGENT_UNLOCK(registration);
	}
	NETAGENT_LIST_UNLOCK();
	return error;
}

int
netagent_trigger(struct proc *p, struct netagent_trigger_args *uap, int32_t *retval)
{
#pragma unused(p, retval)
	uuid_t agent_uuid = {};
	int error = 0;

	if (uap == NULL) {
		NETAGENTLOG0(LOG_ERR, "uap == NULL");
		return EINVAL;
	}

	if (uap->agent_uuid) {
		if (uap->agent_uuidlen != sizeof(uuid_t)) {
			NETAGENTLOG(LOG_ERR, "Incorrect length (got %zu, expected %lu)",
			    (size_t)uap->agent_uuidlen, sizeof(uuid_t));
			return ERANGE;
		}

		error = copyin(uap->agent_uuid, agent_uuid, sizeof(uuid_t));
		if (error) {
			NETAGENTLOG(LOG_ERR, "copyin error (%d)", error);
			return error;
		}
	}

	if (uuid_is_null(agent_uuid)) {
		NETAGENTLOG0(LOG_ERR, "Requested netagent UUID is empty");
		return EINVAL;
	}

	NETAGENT_LIST_LOCK_SHARED();
	struct netagent_registration *registration = netagent_find_agent_with_uuid_and_lock(agent_uuid, false, false);
	if (registration == NULL) {
		NETAGENTLOG0(LOG_ERR, "Requested netagent UUID is not registered");
		error = ENOENT;
		goto done;
	}

	if ((registration->netagent->netagent_flags & NETAGENT_FLAG_USER_ACTIVATED) == 0) {
		// Agent does not accept triggers
		NETAGENTLOG0(LOG_ERR, "Requested netagent UUID is not eligible for triggering");
		error = ENOTSUP;
		goto done;
	}

	if ((registration->netagent->netagent_flags & NETAGENT_FLAG_ACTIVE)) {
		// Agent already active
		NETAGENTLOG0(LOG_INFO, "Requested netagent UUID is already active");
		error = 0;
		goto done;
	}

	error = netagent_send_trigger(registration, p, NETAGENT_TRIGGER_FLAG_USER, NETAGENT_MESSAGE_TYPE_TRIGGER);
	NETAGENTLOG((error ? LOG_ERR : LOG_INFO), "Triggered netagent (error %d)", error);
done:
	if (registration != NULL) {
		NETAGENT_UNLOCK(registration);
	}
	NETAGENT_LIST_UNLOCK();
	return error;
}