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
// Copyright 2019 Fabian Freyer <fabian.freyer@physik.tu-berlin.de>
// Copyright 2018 David O'Rourke <david.orourke@gmail.com>
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

// Note:
// The rctl_api_wrapper function, the usage() function as well as the state
// check are based on code from phyber/jail_exporter:
// https://github.com/phyber/jail_exporter/blob/6498d628143399fc365fad4217ad85db12348e65/src/rctl/mod.rs

//! Resource limits and accounting with `RCTL` and `RACCT`
//!
//! Large parts of this documentation are adapted from the [`rctl(8)`] manpage.
//!
//! [`rctl(8)`]: https://www.freebsd.org/cgi/man.cgi?query=rctl&sektion=8&manpath=FreeBSD+11.2-stable

#[macro_use]
extern crate failure;
extern crate libc;
extern crate nix;
extern crate number_prefix;
extern crate sysctl;
extern crate users;

#[cfg(feature = "serialize")]
#[macro_use]
extern crate serde;

pub use nix::sys::signal::Signal;
use number_prefix::{NumberPrefix, Prefix, Prefixed, Standalone};
use std::collections::HashMap;
use std::ffi::{CStr, CString, NulError};
use std::fmt;
use std::io;
use std::num;
use std::str;

#[cfg(feature = "serialize")]
use serde::Serializer;

// Set to the same value as found in rctl.c in FreeBSD 11.1
const RCTL_DEFAULT_BUFSIZE: usize = 128 * 1024;

#[derive(Debug, Fail, PartialEq, Clone)]
pub enum ParseError {
    #[fail(display = "Unknown subject type: {}", _0)]
    UnknownSubjectType(String),

    #[fail(display = "No such user: {}", _0)]
    UnknownUser(String),

    #[fail(display = "Unknown resource: {}", _0)]
    UnknownResource(String),

    #[fail(display = "Unknown action: {}", _0)]
    UnknownAction(String),

    #[fail(display = "Bogus data at end of limit: {}", _0)]
    LimitBogusData(String),

    #[fail(display = "Invalid limit literal: {}", _0)]
    InvalidLimitLiteral(String),

    #[fail(display = "Invalid numeric value: {}", _0)]
    InvalidNumeral(#[cause] num::ParseIntError),

    #[fail(display = "No subject specified")]
    NoSubjectGiven,

    #[fail(display = "Bogus data at end of subject: {}", _0)]
    SubjectBogusData(String),

    #[fail(display = "Invalid Rule syntax: '{}'", _0)]
    InvalidRuleSyntax(String),
}

#[derive(Debug, Fail)]
pub enum Error {
    #[fail(display = "Parse Error: {}", _0)]
    ParseError(#[cause] ParseError),

    #[fail(display = "OS Error: {}", _0)]
    OsError(#[cause] io::Error),

    #[fail(
        display = "An interior Nul byte was found while attempting to construct a CString: {}",
        _0
    )]
    CStringError(#[cause] NulError),

    #[fail(display = "The statistics returned by the kernel were invalid.")]
    InvalidStatistics,

    #[fail(display = "Invalid RCTL / RACCT kernel state: {}", _0)]
    InvalidKernelState(State),
}

/// Helper module containing enums representing [Subjects](Subject)
mod subject {
    use super::ParseError;
    use libc;
    use std::fmt;
    use users;
    use users::{get_user_by_name, get_user_by_uid};

    /// Represents a user subject
    #[derive(Clone, Debug, PartialEq, Eq, Hash)]
    #[cfg_attr(feature="serialize", derive(Serialize))]
    pub struct User(pub users::uid_t);

    impl User {
        pub fn from_uid(uid: libc::uid_t) -> User {
            User(uid as users::uid_t)
        }

        pub fn from_name(name: &str) -> Result<User, ParseError> {
            let uid = get_user_by_name(name)
                .ok_or_else(|| ParseError::UnknownUser(name.into()))?
                .uid();

            Ok(User::from_uid(uid))
        }
    }

    impl fmt::Display for User {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            match get_user_by_uid(self.0) {
                Some(user) => write!(f, "user:{}", user.name().to_str().ok_or(fmt::Error)?),
                None => write!(f, "user:{}", self.0),
            }
        }
    }

    impl<'a> Into<String> for &'a User {
        fn into(self) -> String {
            format!("user:{}", self.0)
        }
    }

    /// Represents a process subject
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    #[cfg_attr(feature="serialize", derive(Serialize))]
    pub struct Process(pub libc::pid_t);

    impl fmt::Display for Process {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "process:{}", self.0)
        }
    }

    impl<'a> Into<String> for &'a Process {
        fn into(self) -> String {
            format!("{}", self)
        }
    }

    /// Represents a jail subject
    #[derive(Clone, Debug, PartialEq, Eq, Hash)]
    #[cfg_attr(feature="serialize", derive(Serialize))]
    pub struct Jail(pub String);

    impl fmt::Display for Jail {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "jail:{}", self.0)
        }
    }

    impl<'a> Into<String> for &'a Jail {
        fn into(self) -> String {
            format!("{}", self)
        }
    }

    /// Represents a login class subject
    #[derive(Clone, Debug, PartialEq, Eq, Hash)]
    #[cfg_attr(feature="serialize", derive(Serialize))]
    pub struct LoginClass(pub String);

    impl fmt::Display for LoginClass {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "loginclass:{}", self.0)
        }
    }

    impl<'a> Into<String> for &'a LoginClass {
        fn into(self) -> String {
            format!("{}", self)
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn display_jail_name() {
            assert_eq!(
                format!("{}", Jail("testjail_rctl_name".into())),
                "jail:testjail_rctl_name".to_string()
            );
        }

        #[test]
        fn display_user() {
            assert_eq!(
                format!("{}", User::from_name("nobody").expect("no nobody user")),
                "user:nobody".to_string()
            );

            assert_eq!(format!("{}", User::from_uid(4242)), "user:4242".to_string());
        }

        #[test]
        fn display_loginclass() {
            assert_eq!(
                format!("{}", LoginClass("test".into())),
                "loginclass:test".to_string()
            );
        }
    }
}

/// A struct representing an RCTL subject.
///
/// From [`rctl(8)`]:
/// > Subject defines the kind of entity the rule applies to.  It can be either
/// > process, user, login class, or jail.
/// >
/// > Subject ID identifies the subject. It can be user name, numerical user ID
/// > login class name, or jail name.
///
/// [`rctl(8)`]: https://www.freebsd.org/cgi/man.cgi?query=rctl&sektion=8&manpath=FreeBSD+11.2-stable
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature="serialize", derive(Serialize))]
pub enum Subject {
    Process(subject::Process),
    Jail(subject::Jail),
    User(subject::User),
    LoginClass(subject::LoginClass),
}

impl Subject {
    pub fn process_id(pid: libc::pid_t) -> Self {
        Subject::Process(subject::Process(pid))
    }

    pub fn user_name(name: &str) -> Result<Self, ParseError> {
        Ok(Subject::User(subject::User::from_name(name)?))
    }

    pub fn user_id(uid: libc::uid_t) -> Self {
        Subject::User(subject::User::from_uid(uid))
    }

    pub fn login_class<S: Into<String>>(name: S) -> Self {
        Subject::LoginClass(subject::LoginClass(name.into()))
    }

    pub fn jail_name<S: Into<String>>(name: S) -> Self {
        Subject::Jail(subject::Jail(name.into()))
    }

    /// Get the resource usage for a specific [Subject].
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate rctl;
    /// # use rctl;
    /// # if !rctl::State::check().is_enabled() {
    /// #     return;
    /// # }
    /// extern crate libc;
    ///
    /// let uid = unsafe { libc::getuid() };
    /// let subject = rctl::Subject::user_id(uid);
    ///
    /// let usage = subject.usage()
    ///     .expect("Could not get RCTL usage");
    ///
    /// println!("{:#?}", usage);
    /// ```
    pub fn usage(&self) -> Result<HashMap<Resource, usize>, Error> {
        extern "C" {
            fn rctl_get_racct(
                inbufp: *const libc::c_char,
                inbuflen: libc::size_t,
                outbufp: *mut libc::c_char,
                outbuflen: libc::size_t,
            ) -> libc::c_int;
        }

        let filter = Filter::new().subject(self);

        let rusage = rctl_api_wrapper(rctl_get_racct, &filter)?;

        let mut map: HashMap<Resource, usize> = HashMap::new();

        for statistic in rusage.split(',') {
            let mut kv = statistic.split('=');

            let resource = kv
                .next()
                .ok_or(Error::InvalidStatistics)?
                .parse::<Resource>()
                .map_err(Error::ParseError)?;

            let value = kv
                .next()
                .ok_or(Error::InvalidStatistics)?
                .parse::<usize>()
                .map_err(ParseError::InvalidNumeral)
                .map_err(Error::ParseError)?;

            map.insert(resource, value);
        }

        Ok(map)
    }

    /// Get an IntoIterator over the rules that apply to this subject.
    pub fn limits(&self) -> Result<RuleParsingIntoIter<String>, Error> {
        extern "C" {
            fn rctl_get_limits(
                inbufp: *const libc::c_char,
                inbuflen: libc::size_t,
                outbufp: *mut libc::c_char,
                outbuflen: libc::size_t,
            ) -> libc::c_int;
        }

        let outbuf = rctl_api_wrapper(rctl_get_limits, self)?;

        Ok(RuleParsingIntoIter { inner: outbuf })
    }
}

impl fmt::Display for Subject {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Subject::Process(p) => write!(f, "{}", p),
            Subject::User(u) => write!(f, "{}", u),
            Subject::Jail(j) => write!(f, "{}", j),
            Subject::LoginClass(c) => write!(f, "{}", c),
        }
    }
}

impl<'a> Into<String> for &'a Subject {
    fn into(self) -> String {
        match self {
            Subject::Process(ref p) => p.into(),
            Subject::User(ref u) => u.into(),
            Subject::Jail(ref j) => j.into(),
            Subject::LoginClass(ref c) => c.into(),
        }
    }
}

fn parse_process(s: &str) -> Result<Subject, ParseError> {
    s.parse::<libc::pid_t>()
        .map_err(ParseError::InvalidNumeral)
        .map(Subject::process_id)
}

fn parse_user(s: &str) -> Result<Subject, ParseError> {
    match s.parse::<libc::uid_t>() {
        Ok(uid) => Ok(Subject::user_id(uid)),
        Err(_) => Ok(Subject::user_name(s)?),
    }
}

fn parse_jail(s: &str) -> Result<Subject, ParseError> {
    Ok(Subject::jail_name(s))
}

fn parse_login_class(s: &str) -> Result<Subject, ParseError> {
    Ok(Subject::login_class(s))
}

impl str::FromStr for Subject {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<_> = s.split(':').collect();

        let subject_type = parts[0].parse::<SubjectType>()?;

        match parts.len() {
            1 => Err(ParseError::NoSubjectGiven),
            2 => match subject_type {
                SubjectType::Process => parse_process(parts[1]),
                SubjectType::User => parse_user(parts[1]),
                SubjectType::LoginClass => parse_login_class(parts[1]),
                SubjectType::Jail => parse_jail(parts[1]),
            },
            _ => Err(ParseError::SubjectBogusData(format!(
                ":{}",
                parts[2..].join(":")
            ))),
        }
    }
}

/// The type of a [Subject].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature="serialize", derive(Serialize))]
pub enum SubjectType {
    Process,
    Jail,
    User,
    LoginClass,
}

impl str::FromStr for SubjectType {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "process" => Ok(SubjectType::Process),
            "jail" => Ok(SubjectType::Jail),
            "user" => Ok(SubjectType::User),
            "loginclass" => Ok(SubjectType::LoginClass),
            _ => Err(ParseError::UnknownSubjectType(s.into())),
        }
    }
}

impl<'a> From<&'a Subject> for SubjectType {
    fn from(subject: &'a Subject) -> Self {
        match subject {
            Subject::Process(_) => SubjectType::Process,
            Subject::Jail(_) => SubjectType::Jail,
            Subject::User(_) => SubjectType::User,
            Subject::LoginClass(_) => SubjectType::LoginClass,
        }
    }
}

impl SubjectType {
    pub fn as_str(&self) -> &'static str {
        match self {
            SubjectType::Process => "process",
            SubjectType::Jail => "jail",
            SubjectType::User => "user",
            SubjectType::LoginClass => "loginclass",
        }
    }
}

impl<'a> Into<&'static str> for &'a SubjectType {
    fn into(self) -> &'static str {
        self.as_str()
    }
}

impl<'a> Into<String> for &'a SubjectType {
    fn into(self) -> String {
        self.as_str().into()
    }
}

impl fmt::Display for SubjectType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let r: &'static str = self.into();
        write!(f, "{}", r)
    }
}

/// An Enum representing a resource type
#[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)]
#[cfg_attr(feature="serialize", derive(Serialize))]
pub enum Resource {
    /// CPU time, in seconds
    CpuTime,

    /// datasize, in bytes
    DataSize,

    /// stack size, in bytes
    ///
    /// from the [FreeBSD Handbook Chapter 13.13 - Resource Limits]:
    /// > The maximum size of a process stack. This alone is not sufficient to
    /// > limit the amount of memory a program may use, so it should be used in
    /// > conjunction with other limits.
    ///
    /// [FreeBSD Handbook Chapter 13.13 - Resource Limits]:
    ///   https://www.freebsd.org/doc/handbook/security-resourcelimits.html#resource-limits
    StackSize,

    /// coredump size, in bytes
    ///
    /// from the [FreeBSD Handbook Chapter 13.13 - Resource Limits]:
    /// > The limit on the size of a core file generated by a program is
    /// > subordinate to other limits on disk usage, such as filesize or disk
    /// > quotas. This limit is often used as a less severe method of
    /// > controlling disk space consumption. Since users do not generate core
    /// > files and often do not delete them, this setting may save them from
    /// > running out of disk space should a large program crash.
    ///
    /// [FreeBSD Handbook Chapter 13.13 - Resource Limits]:
    ///   https://www.freebsd.org/doc/handbook/security-resourcelimits.html#resource-limits
    CoreDumpSize,

    /// resident setsize, in bytes
    MemoryUse,

    /// locked memory, in bytes
    ///
    /// from the [FreeBSD Handbook Chapter 13.13 - Resource Limits]:
    /// > The maximum amount of memory a process may request to be locked into
    /// > main memory using [`mlock(2)`]. Some system-critical programs, such as
    /// > [`amd(8)`], lock into main memory so that if the system begins to
    /// > swap, they do not contribute to disk thrashing.
    ///
    /// [`mlock(2)`]:
    ///   https://www.freebsd.org/cgi/man.cgi?query=mlock&sektion=2&manpath=freebsd-release-ports
    /// [`amd(8)`]:
    ///   https://www.freebsd.org/cgi/man.cgi?query=amd&sektion=8&manpath=freebsd-release-ports
    /// [FreeBSD Handbook Chapter 13.13 - Resource Limits]:
    ///   https://www.freebsd.org/doc/handbook/security-resourcelimits.html#resource-limits
    MemoryLocked,

    /// number of processes
    MaxProcesses,

    /// File descriptor table size
    OpenFiles,

    /// address space limit, in bytes
    VMemoryUse,

    /// number of PTYs
    PseudoTerminals,

    /// swapspace that may be reserved or used, in bytes
    SwapUse,

    /// number of threads
    NThreads,

    /// number of queued SysV messages
    MsgqQueued,

    /// SysVmessagequeue size, in bytes
    MsgqSize,

    /// number of SysV message queues
    NMsgq,

    /// number of SysV semaphores
    Nsem,

    /// number of SysV semaphores modified in a single `semop(2)` call
    NSemop,

    /// number of SysV shared memorysegments
    NShm,

    /// SysVshared memory size, in bytes
    ShmSize,

    /// wallclock time, in seconds
    Wallclock,

    /// %CPU, in percents of a single CPU core
    PercentCpu,

    /// filesystem reads, in bytes per second
    ReadBps,

    /// filesystem writes, in bytes per second
    WriteBps,

    /// filesystem reads, inoperations per second
    ReadIops,

    /// filesystem writes, in operations persecond
    WriteIops,
}

impl Resource {
    /// Return the string representation of the resource
    ///
    /// # Examples
    /// ```
    /// use rctl::Resource;
    /// assert_eq!(Resource::CpuTime.as_str(), "cputime");
    /// ```
    pub fn as_str(&self) -> &'static str {
        match self {
            Resource::CpuTime => "cputime",
            Resource::DataSize => "datasize",
            Resource::StackSize => "stacksize",
            Resource::CoreDumpSize => "coredumpsize",
            Resource::MemoryUse => "memoryuse",
            Resource::MemoryLocked => "memorylocked",
            Resource::MaxProcesses => "maxproc",
            Resource::OpenFiles => "openfiles",
            Resource::VMemoryUse => "vmemoryuse",
            Resource::PseudoTerminals => "pseudoterminals",
            Resource::SwapUse => "swapuse",
            Resource::NThreads => "nthr",
            Resource::MsgqQueued => "msgqqueued",
            Resource::MsgqSize => "msgqsize",
            Resource::NMsgq => "nmsgq",
            Resource::Nsem => "nsem",
            Resource::NSemop => "nsemop",
            Resource::NShm => "nshm",
            Resource::ShmSize => "shmsize",
            Resource::Wallclock => "wallclock",
            Resource::PercentCpu => "pcpu",
            Resource::ReadBps => "readbps",
            Resource::WriteBps => "writebps",
            Resource::ReadIops => "readiops",
            Resource::WriteIops => "writeiops",
        }
    }
}

impl str::FromStr for Resource {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "cputime" => Ok(Resource::CpuTime),
            "datasize" => Ok(Resource::DataSize),
            "stacksize" => Ok(Resource::StackSize),
            "coredumpsize" => Ok(Resource::CoreDumpSize),
            "memoryuse" => Ok(Resource::MemoryUse),
            "memorylocked" => Ok(Resource::MemoryLocked),
            "maxproc" => Ok(Resource::MaxProcesses),
            "openfiles" => Ok(Resource::OpenFiles),
            "vmemoryuse" => Ok(Resource::VMemoryUse),
            "pseudoterminals" => Ok(Resource::PseudoTerminals),
            "swapuse" => Ok(Resource::SwapUse),
            "nthr" => Ok(Resource::NThreads),
            "msgqqueued" => Ok(Resource::MsgqQueued),
            "msgqsize" => Ok(Resource::MsgqSize),
            "nmsgq" => Ok(Resource::NMsgq),
            "nsem" => Ok(Resource::Nsem),
            "nsemop" => Ok(Resource::NSemop),
            "nshm" => Ok(Resource::NShm),
            "shmsize" => Ok(Resource::ShmSize),
            "wallclock" => Ok(Resource::Wallclock),
            "pcpu" => Ok(Resource::PercentCpu),
            "readbps" => Ok(Resource::ReadBps),
            "writebps" => Ok(Resource::WriteBps),
            "readiops" => Ok(Resource::ReadIops),
            "writeiops" => Ok(Resource::WriteIops),
            _ => Err(ParseError::UnknownResource(s.into())),
        }
    }
}

impl<'a> Into<&'static str> for &'a Resource {
    fn into(self) -> &'static str {
        self.as_str()
    }
}

impl<'a> Into<String> for &'a Resource {
    fn into(self) -> String {
        self.as_str().into()
    }
}

impl fmt::Display for Resource {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let r: &'static str = self.into();
        write!(f, "{}", r)
    }
}

/// Represents the action to be taken when a [Subject] offends against a Rule.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature="serialize", derive(Serialize))]
pub enum Action {
    /// Deny the resource allocation
    ///
    /// Not supported for the following [Resources]: [`CpuTime`], [`Wallclock`],
    /// [`ReadBps`], [`WriteBps`], [`ReadIops`], [`WriteIops`]
    ///
    /// [`CpuTime`]: Resource::CpuTime

    /// [`WallClock`]: Resource::Wallclock
    /// [`ReadBps`]: Resource::ReadBps
    /// [`WriteBps`]: Resource::WriteBps
    /// [`ReadIops`]: Resource::ReadIops
    /// [`WriteIops`]: Resource::WriteIops
    /// [Resources]: Resource
    Deny,

    /// Log a warning to the console
    Log,

    /// Send a notification to [`devd(8)`] using `system = "RCTL"`,
    /// `subsystem = "rule"`, `type = "matched"`
    ///
    /// [`devd(8)`]: https://www.freebsd.org/cgi/man.cgi?query=devd&sektion=8&manpath=FreeBSD+11.2-stable
    DevCtl,

    /// Send a [signal] to the offending process.
    ///
    /// # Example
    /// ```
    /// # extern crate rctl;
    /// use rctl::Signal;
    /// use rctl::Action;
    ///
    /// let action = Action::Signal(Signal::SIGTERM);
    /// ```
    ///
    /// [signal]: Signal
    #[cfg_attr(feature="serialize", serde(serialize_with = "signal_serialize"))]
    Signal(Signal),

    /// Slow down process execution
    ///
    /// Only supported for the following [Resources]:
    /// [`ReadBps`], [`WriteBps`], [`ReadIops`], [`WriteIops`]
    ///
    /// [`ReadBps`]: Resource::ReadBps
    /// [`WriteBps`]: Resource::WriteBps
    /// [`ReadIops`]: Resource::ReadIops
    /// [`WriteIops`]: Resource::WriteIops
    /// [Resources]: Resource
    Throttle,
}

impl Action {
    /// Return the string representation of the Action according to [`rctl(8)`]
    ///
    /// # Examples
    /// ```
    /// use rctl::Action;
    /// assert_eq!(Action::Deny.as_str(), "deny");
    /// ```
    ///
    /// Signals are handled by `rctl::Signal`:
    /// ```
    /// # extern crate rctl;
    /// # use rctl::Action;
    /// use rctl::Signal;
    /// assert_eq!(Action::Signal(Signal::SIGKILL).as_str(), "sigkill");
    /// ```
    ///
    /// [`rctl(8)`]: https://www.freebsd.org/cgi/man.cgi?query=rctl&sektion=8&manpath=FreeBSD+11.2-stable
    pub fn as_str(&self) -> &'static str {
        match self {
            Action::Deny => "deny",
            Action::Log => "log",
            Action::DevCtl => "devctl",
            Action::Throttle => "throttle",
            Action::Signal(sig) => match sig {
                Signal::SIGHUP => "sighup",
                Signal::SIGINT => "sigint",
                Signal::SIGQUIT => "sigquit",
                Signal::SIGILL => "sigill",
                Signal::SIGTRAP => "sigtrap",
                Signal::SIGABRT => "sigabrt",
                Signal::SIGBUS => "sigbus",
                Signal::SIGFPE => "sigfpe",
                Signal::SIGKILL => "sigkill",
                Signal::SIGUSR1 => "sigusr1",
                Signal::SIGSEGV => "sigsegv",
                Signal::SIGUSR2 => "sigusr2",
                Signal::SIGPIPE => "sigpipe",
                Signal::SIGALRM => "sigalrm",
                Signal::SIGTERM => "sigterm",
                Signal::SIGCHLD => "sigchld",
                Signal::SIGCONT => "sigcont",
                Signal::SIGSTOP => "sigstop",
                Signal::SIGTSTP => "sigtstp",
                Signal::SIGTTIN => "sigttin",
                Signal::SIGTTOU => "sigttou",
                Signal::SIGURG => "sigurg",
                Signal::SIGXCPU => "sigxcpu",
                Signal::SIGXFSZ => "sigxfsz",
                Signal::SIGVTALRM => "sigvtalrm",
                Signal::SIGPROF => "sigprof",
                Signal::SIGWINCH => "sigwinch",
                Signal::SIGIO => "sigio",
                Signal::SIGSYS => "sigsys",
                Signal::SIGEMT => "sigemt",
                Signal::SIGINFO => "siginfo",
            },
        }
    }
}

impl str::FromStr for Action {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "deny" => Ok(Action::Deny),
            "log" => Ok(Action::Log),
            "devctl" => Ok(Action::DevCtl),
            "throttle" => Ok(Action::Throttle),
            "sighup" => Ok(Action::Signal(Signal::SIGHUP)),
            "sigint" => Ok(Action::Signal(Signal::SIGINT)),
            "sigquit" => Ok(Action::Signal(Signal::SIGQUIT)),
            "sigill" => Ok(Action::Signal(Signal::SIGILL)),
            "sigtrap" => Ok(Action::Signal(Signal::SIGTRAP)),
            "sigabrt" => Ok(Action::Signal(Signal::SIGABRT)),
            "sigbus" => Ok(Action::Signal(Signal::SIGBUS)),
            "sigfpe" => Ok(Action::Signal(Signal::SIGFPE)),
            "sigkill" => Ok(Action::Signal(Signal::SIGKILL)),
            "sigusr1" => Ok(Action::Signal(Signal::SIGUSR1)),
            "sigsegv" => Ok(Action::Signal(Signal::SIGSEGV)),
            "sigusr2" => Ok(Action::Signal(Signal::SIGUSR2)),
            "sigpipe" => Ok(Action::Signal(Signal::SIGPIPE)),
            "sigalrm" => Ok(Action::Signal(Signal::SIGALRM)),
            "sigterm" => Ok(Action::Signal(Signal::SIGTERM)),
            "sigchld" => Ok(Action::Signal(Signal::SIGCHLD)),
            "sigcont" => Ok(Action::Signal(Signal::SIGCONT)),
            "sigstop" => Ok(Action::Signal(Signal::SIGSTOP)),
            "sigtstp" => Ok(Action::Signal(Signal::SIGTSTP)),
            "sigttin" => Ok(Action::Signal(Signal::SIGTTIN)),
            "sigttou" => Ok(Action::Signal(Signal::SIGTTOU)),
            "sigurg" => Ok(Action::Signal(Signal::SIGURG)),
            "sigxcpu" => Ok(Action::Signal(Signal::SIGXCPU)),
            "sigxfsz" => Ok(Action::Signal(Signal::SIGXFSZ)),
            "sigvtalrm" => Ok(Action::Signal(Signal::SIGVTALRM)),
            "sigprof" => Ok(Action::Signal(Signal::SIGPROF)),
            "sigwinch" => Ok(Action::Signal(Signal::SIGWINCH)),
            "sigio" => Ok(Action::Signal(Signal::SIGIO)),
            "sigsys" => Ok(Action::Signal(Signal::SIGSYS)),
            "sigemt" => Ok(Action::Signal(Signal::SIGEMT)),
            "siginfo" => Ok(Action::Signal(Signal::SIGINFO)),
            _ => Err(ParseError::UnknownAction(s.into())),
        }
    }
}

impl<'a> Into<&'static str> for &'a Action {
    fn into(self) -> &'static str {
        self.as_str()
    }
}

impl<'a> Into<String> for &'a Action {
    fn into(self) -> String {
        self.as_str().into()
    }
}

impl fmt::Display for Action {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

#[cfg(feature="serialize")]
fn signal_serialize<S>(signal: &Signal, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let sig_str = format!("{:?}", signal);
    s.serialize_str(&sig_str)
}

/// Defines how much of a [Resource] a process can use beofore the defined
/// [Action] triggers.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature="serialize", derive(Serialize))]
pub struct Limit {
    amount: usize,
    per: Option<SubjectType>,
}

impl Limit {
    /// Construct a limit representing the amount used before an [Action]
    /// triggers.
    ///
    /// The entity the amount gets accounted for defaults to the type of the
    /// [Subject] of the respective [Rule].
    pub fn amount(amount: usize) -> Limit {
        Limit { amount, per: None }
    }

    /// Limit the amount per [SubjectType].
    ///
    /// This defines what entity the amount gets accounted for.
    ///
    /// # Examples
    ///
    /// For example the following [Rule] means that each process of any user
    /// belonging to the login class "users" may allocate up to 100 MiB of
    /// virtual memory:
    /// ```rust
    /// # use rctl::{Subject, SubjectType, Resource, Action, Limit, Rule};
    /// Rule {
    ///     subject: Subject::login_class("users"),
    ///     resource: Resource::VMemoryUse,
    ///     action: Action::Deny,
    ///     limit: Limit::amount_per(100*1024*1024, SubjectType::Process),
    /// }
    /// # ;
    /// ```
    ///
    /// Setting `per: Some(SubjectType::User)` on the above [Rule] would mean
    /// that for each user belonging to the login class "users", the sum of
    /// virtual memory allocated by all the processes of that user will not
    /// exceed 100 MiB.
    ///
    /// Setting `per: Some(SubjectType::LoginClass)` on the above [Rule] would
    /// mean that the sum of virtual memory allocated by all processes of all
    /// users belonging to that login class will not exceed 100 MiB.
    pub fn amount_per(amount: usize, per: SubjectType) -> Limit {
        Limit {
            amount,
            per: Some(per),
        }
    }

    /// Return the String representation of the Limit.
    pub fn to_string(&self) -> String {
        format!("{}", self)
    }
}

fn parse_limit_with_suffix(s: &str) -> Result<usize, ParseError> {
    let s = s.trim().to_lowercase();

    if let Ok(v) = s.parse::<usize>() {
        return Ok(v);
    }

    let suffixes = ["k", "m", "g", "t", "p", "e", "z", "y"];

    for (i, suffix) in suffixes.iter().enumerate() {
        match s
            .split(suffix)
            .next()
            .expect("could not split the suffix off")
            .parse::<usize>()
        {
            Err(_) => continue,
            Ok(v) => return Ok(v * 1024usize.pow((i + 1) as u32)),
        };
    }

    Err(ParseError::InvalidLimitLiteral(s.into()))
}

impl str::FromStr for Limit {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<_> = s.split('/').collect();

        let val = parse_limit_with_suffix(parts[0])?;

        match parts.len() {
            1 => Ok(Limit::amount(val)),
            2 => Ok(Limit::amount_per(val, parts[1].parse::<SubjectType>()?)),
            _ => Err(ParseError::LimitBogusData(format!(
                "/{}",
                parts[2..].join("/")
            ))),
        }
    }
}

impl fmt::Display for Limit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let amount = match NumberPrefix::binary(self.amount as f64) {
            Standalone(amt) => format!("{}", amt),
            Prefixed(prefix, amt) => {
                let prefix = match prefix {
                    Prefix::Kibi => "k",
                    Prefix::Mibi => "m",
                    Prefix::Gibi => "g",
                    Prefix::Tebi => "t",
                    Prefix::Pebi => "p",
                    Prefix::Exbi => "e",
                    Prefix::Zebi => "z",
                    Prefix::Yobi => "y",
                    _ => panic!("called binary_prefix but got decimal prefix"),
                };

                format!("{}{}", amt, prefix)
            }
        };

        let per = match &self.per {
            Some(ref s) => format!("/{}", s),
            None => "".to_string(),
        };

        write!(f, "{}{}", amount, per)
    }
}

impl<'a> Into<String> for &'a Limit {
    fn into(self) -> String {
        let per = match &self.per {
            Some(ref s) => format!("/{}", s),
            None => "".to_string(),
        };
        format!("{}{}", self.amount, per)
    }
}

/// A rule represents an [Action] to be taken when a particular [Subject] hits
/// a [Limit] for a [Resource].
///
/// Syntax for the string representation of a rule is
/// `subject:subject-id:resource:action=amount/per`.
///
/// # Examples
///
/// ```rust
/// use rctl::{Subject, SubjectType, Resource, Action, Limit, Rule};
/// let rule = Rule {
///     subject: Subject::user_name("nobody").expect("no user 'nobody'"),
///     resource: Resource::VMemoryUse,
///     action: Action::Deny,
///     limit: Limit::amount(1024*1024*1024),
/// };
///
/// assert_eq!(rule.to_string(), "user:nobody:vmemoryuse:deny=1g".to_string());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature="serialize", derive(Serialize))]
pub struct Rule {
    pub subject: Subject,
    pub resource: Resource,
    pub limit: Limit,
    pub action: Action,
}

impl Rule {
    pub fn to_string(&self) -> String {
        format!("{}", self)
    }

    /// Add this rule to the resource limits database.
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate rctl;
    /// # if !rctl::State::check().is_enabled() {
    /// #     return;
    /// # }
    /// use rctl::{Rule, Subject, Resource, Action, Limit};
    ///
    /// let rule = Rule {
    ///     subject: Subject::jail_name("testjail_rctl_rule_apply_method"),
    ///     resource: Resource::VMemoryUse,
    ///     action: Action::Log,
    ///     limit: Limit::amount(100*1024*1024),
    /// };
    ///
    /// rule.apply();
    /// # rule.remove();
    /// ```
    pub fn apply(&self) -> Result<(), Error> {
        extern "C" {
            fn rctl_add_rule(
                inbufp: *const libc::c_char,
                inbuflen: libc::size_t,
                outbufp: *mut libc::c_char,
                outbuflen: libc::size_t,
            ) -> libc::c_int;
        }

        rctl_api_wrapper(rctl_add_rule, self)?;

        Ok(())
    }

    /// Attempt to remove this rule from the resource limits database.
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate rctl;
    /// # if !rctl::State::check().is_enabled() {
    /// #     return;
    /// # }
    /// use rctl::{Rule, Subject, Resource, Action, Limit};
    ///
    /// let rule = Rule {
    ///     subject: Subject::jail_name("testjail_rctl_rule_remove_method"),
    ///     resource: Resource::VMemoryUse,
    ///     action: Action::Log,
    ///     limit: Limit::amount(100*1024*1024),
    /// };
    ///
    /// # rule.apply();
    /// rule.remove();
    /// ```
    pub fn remove(&self) -> Result<(), Error> {
        let filter: Filter = self.into();
        filter.remove_rules()
    }
}

impl fmt::Display for Rule {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}:{}:{}={}",
            self.subject, self.resource, self.action, self.limit
        )
    }
}

impl<'a> Into<String> for &'a Rule {
    fn into(self) -> String {
        let subject: String = (&self.subject).into();
        let resource: &str = (&self.resource).into();
        let action: &str = (&self.action).into();
        let limit: String = (&self.limit).into();
        format!("{}:{}:{}={}", subject, resource, action, limit)
    }
}

impl str::FromStr for Rule {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // subject:subject-id:resource:action=amount/per
        let parts: Vec<_> = s.split(':').collect();

        if parts.len() != 4 {
            return Err(ParseError::InvalidRuleSyntax(s.into()));
        }

        let subject = format!("{}:{}", parts[0], parts[1]).parse::<Subject>()?;
        let resource = parts[2].parse::<Resource>()?;

        let parts: Vec<_> = parts[3].split('=').collect();

        if parts.len() != 2 {
            return Err(ParseError::InvalidRuleSyntax(s.into()));
        }

        let action = parts[0].parse::<Action>()?;
        let limit = parts[1].parse::<Limit>()?;

        Ok(Rule {
            subject,
            resource,
            action,
            limit,
        })
    }
}

/// Adapter over objects parseable into a [Rule]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RuleParserAdapter<I> {
    inner: I,
}

impl<'a, I> Iterator for RuleParserAdapter<I>
where
    I: Iterator<Item = &'a str>,
{
    type Item = Rule;

    fn next(&mut self) -> Option<Rule> {
        match self.inner.next() {
            Some(item) => item.parse::<Rule>().ok(),
            None => None,
        }
    }
}

/// Owning struct implementing IntoIterator, returning a [RuleParserAdapter].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RuleParsingIntoIter<S> {
    inner: S,
}

impl<'a> IntoIterator for &'a RuleParsingIntoIter<String> {
    type Item = Rule;
    type IntoIter = RuleParserAdapter<str::Split<'a, &'a str>>;

    fn into_iter(self) -> Self::IntoIter {
        RuleParserAdapter {
            inner: self.inner.split(","),
        }
    }
}

trait RuleParsingExt<'a>: Sized {
    fn parse_rules(self) -> RuleParserAdapter<Self>;
}

impl<'a> RuleParsingExt<'a> for str::Split<'a, &'a str> {
    fn parse_rules(self) -> RuleParserAdapter<Self> {
        RuleParserAdapter { inner: self }
    }
}

/// A filter can match a set of [Rules](Rule).
#[derive(Debug, Clone, PartialEq)]
pub struct Filter {
    subject_type: Option<SubjectType>,
    subject: Option<Subject>,

    resource: Option<Resource>,
    limit: Option<Limit>,

    action: Option<Action>,
    limit_per: Option<SubjectType>,
}

impl Filter {
    /// Return the filter that matches all rules
    ///
    /// # Example
    ///
    /// ```
    /// # use rctl::Filter;
    /// let filter = Filter::new();
    /// assert_eq!(filter.to_string(), ":".to_string());
    /// ```
    pub fn new() -> Filter {
        Filter {
            subject_type: None,
            subject: None,
            resource: None,
            limit: None,
            action: None,
            limit_per: None,
        }
    }

    /// Constrain the filter to a specific [SubjectType]
    ///
    /// If the filter is already constrained to a subject, this is a No-Op.
    ///
    /// # Example
    ///
    /// ```
    /// # use rctl::{Filter, SubjectType};
    /// let filter = Filter::new()
    ///     .subject_type(&SubjectType::LoginClass);
    /// assert_eq!(filter.to_string(), "loginclass:".to_string());
    /// ```
    pub fn subject_type(mut self: Filter, subject_type: &SubjectType) -> Filter {
        if self.subject.is_none() {
            self.subject_type = Some(*subject_type);
        }
        self
    }

    /// Constrain the filter to a specific [Subject]
    ///
    /// Resets the subject type.
    ///
    /// # Example
    ///
    /// ```
    /// # use rctl::{Filter, Subject};
    /// let filter = Filter::new()
    ///     .subject(&Subject::user_name("nobody").expect("no user 'nobody'"));
    /// assert_eq!(filter.to_string(), "user:nobody".to_string());
    /// ```
    pub fn subject(mut self: Filter, subject: &Subject) -> Filter {
        self.subject = Some(subject.clone());
        self.subject_type = None;
        self
    }

    /// Constrain the filter to a specific [Resource]
    ///
    /// # Example
    ///
    /// ```
    /// # use rctl::{Filter, Resource};
    /// let filter = Filter::new()
    ///     .resource(&Resource::MemoryLocked);
    /// assert_eq!(filter.to_string(), "::memorylocked".to_string());
    /// ```
    pub fn resource(mut self: Filter, resource: &Resource) -> Filter {
        self.resource = Some(*resource);
        self
    }

    /// Constrain the filter to a specific [Action]
    ///
    /// # Example
    ///
    /// ```
    /// # use rctl::{Filter, Action};
    /// let filter = Filter::new()
    ///     .action(&Action::Deny);
    /// assert_eq!(filter.to_string(), ":::deny".to_string());
    /// ```
    pub fn action(mut self: Filter, action: &Action) -> Filter {
        self.action = Some(*action);
        self
    }

    /// Constrain the filter to the [Deny](Action::Deny) [Action]
    ///
    /// # Example
    ///
    /// ```
    /// # use rctl::{Filter, Action};
    /// let filter = Filter::new()
    ///     .deny();
    /// assert_eq!(filter, Filter::new().action(&Action::Deny));
    /// ```
    pub fn deny(self: Filter) -> Filter {
        self.action(&Action::Deny)
    }

    /// Constrain the filter to the [Log](Action::Log) [Action]
    ///
    /// # Example
    ///
    /// ```
    /// # use rctl::{Filter, Action};
    /// let filter = Filter::new()
    ///     .log();
    /// assert_eq!(filter, Filter::new().action(&Action::Log));
    /// ```
    pub fn log(self: Filter) -> Filter {
        self.action(&Action::Log)
    }

    /// Constrain the filter to the [DevCtl](Action::DevCtl) [Action]
    ///
    /// # Example
    ///
    /// ```
    /// # use rctl::{Filter, Action};
    /// let filter = Filter::new()
    ///     .devctl();
    /// assert_eq!(filter, Filter::new().action(&Action::DevCtl));
    /// ```
    pub fn devctl(self: Filter) -> Filter {
        self.action(&Action::DevCtl)
    }

    /// Constrain the filter to the [Signal](Action::Signal) [Action]
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate rctl;
    /// # use rctl::{Filter, Action, Signal};
    /// let filter = Filter::new()
    ///     .signal(Signal::SIGTERM);
    /// assert_eq!(filter.to_string(), ":::sigterm".to_string());
    /// ```
    pub fn signal(self: Filter, signal: Signal) -> Filter {
        self.action(&Action::Signal(signal))
    }

    /// Constrain the filter to a particular [Limit]
    ///
    /// Resets any limit_per, if the given limit has a `per` set.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rctl::{Filter, Limit};
    /// let filter = Filter::new()
    ///     .limit(&Limit::amount(100*1024*1024));
    /// assert_eq!(filter.to_string(), ":::=100m".to_string());
    /// ```
    ///
    /// ```
    /// # use rctl::{Filter, Limit, SubjectType};
    /// let filter = Filter::new()
    ///     .limit(&Limit::amount_per(100*1024*1024, SubjectType::Process));
    /// assert_eq!(filter.to_string(), ":::=100m/process".to_string());
    /// ```
    pub fn limit(mut self: Filter, limit: &Limit) -> Filter {
        let mut limit = limit.clone();

        // if the limit given doesn't have a `per` set, but we do, move it
        // into the limit.
        if let (Some(limit_per), None) = (self.limit_per, limit.per) {
            limit.per = Some(limit_per);
        }

        self.limit_per = None;
        self.limit = Some(limit);
        self
    }

    fn sanity(&self) {
        if let (Some(ref subject), Some(ref subject_type)) = (&self.subject, &self.subject_type) {
            let actual_type: SubjectType = subject.into();
            assert_eq!(&actual_type, subject_type);
        }
    }

    /// Return the string representation of the [Filter].
    pub fn to_string(&self) -> String {
        format!("{}", self)
    }

    /// Return an [IntoIterator] over all [Rules] matching this [Filter].
    ///
    /// # Example
    ///
    /// List all rules:
    ///
    /// ```
    /// use rctl;
    ///
    /// let filter = rctl::Filter::new();
    /// for rule in filter.rules() {
    ///     println!("{:?}", rule);
    /// }
    /// ```
    ///
    /// [Rules]: Rule
    pub fn rules(&self) -> Result<RuleParsingIntoIter<String>, Error> {
        extern "C" {
            fn rctl_get_rules(
                inbufp: *const libc::c_char,
                inbuflen: libc::size_t,
                outbufp: *mut libc::c_char,
                outbuflen: libc::size_t,
            ) -> libc::c_int;
        }

        let outbuf = rctl_api_wrapper(rctl_get_rules, self)?;

        Ok(RuleParsingIntoIter { inner: outbuf })
    }

    /// Remove all matching [Rules] from the resource limits database.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate rctl;
    /// # if !rctl::State::check().is_enabled() {
    /// #     return;
    /// # }
    /// # use rctl::{Rule, Resource, Action, Limit};
    /// use rctl::{Filter, Subject};
    /// # let rule = Rule {
    /// #     subject: Subject::jail_name("testjail_rctl_filter_remove"),
    /// #     resource: Resource::VMemoryUse,
    /// #     action: Action::Log,
    /// #     limit: Limit::amount(100*1024*1024),
    /// # };
    /// # rule.apply();
    /// # let rule = Rule {
    /// #     subject: Subject::jail_name("testjail_rctl_filter_remove"),
    /// #     resource: Resource::StackSize,
    /// #     action: Action::Log,
    /// #     limit: Limit::amount(100*1024*1024),
    /// # };
    /// # rule.apply();
    /// let filter = Filter::new()
    ///     .subject(&Subject::jail_name("testjail_rctl_filter_remove"))
    ///     .remove_rules()
    ///     .expect("Could not remove rules");
    /// ```
    ///
    /// Remove all rules, clearing the resource limits database by using the
    /// default (`':'`) [Filter]:
    /// ```no_run
    /// # extern crate rctl;
    /// # use rctl::{Rule, Subject, Resource, Action, Limit};
    /// use rctl;
    ///
    /// rctl::Filter::new().remove_rules().expect("Could not remove all rules");
    /// ```
    ///
    /// [Rules]: Rule
    pub fn remove_rules(&self) -> Result<(), Error> {
        extern "C" {
            fn rctl_remove_rule(
                inbufp: *const libc::c_char,
                inbuflen: libc::size_t,
                outbufp: *mut libc::c_char,
                outbuflen: libc::size_t,
            ) -> libc::c_int;
        }

        rctl_api_wrapper(rctl_remove_rule, self)?;

        Ok(())
    }
}

impl fmt::Display for Filter {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.sanity();

        match self {
            Filter {
                subject_type: Some(s),
                ..
            } => write!(f, "{}:", s),
            Filter {
                subject_type: None,
                subject: Some(ref s),
                ..
            } => write!(f, "{}", s),
            Filter {
                subject_type: None,
                subject: None,
                ..
            } => write!(f, ":"),
        }?;

        // If Resource, Action, and Limit are unset, leave it at this.
        if let Filter {
            resource: None,
            action: None,
            limit: None,
            limit_per: None,
            ..
        } = self
        {
            return Ok(());
        }

        match &self.resource {
            Some(resource) => write!(f, ":{}", resource),
            None => write!(f, ":"),
        }?;

        // If action, and limit are unset, leave it at this.
        if let Filter {
            action: None,
            limit: None,
            limit_per: None,
            ..
        } = self
        {
            return Ok(());
        }

        match &self.action {
            Some(action) => write!(f, ":{}", action),
            None => write!(f, ":"),
        }?;

        // If limit is unset, leave it at this
        if let Filter {
            limit: None,
            limit_per: None,
            ..
        } = self
        {
            return Ok(());
        }

        match &self.limit {
            Some(limit) => write!(f, "={}", limit),
            None => write!(
                f,
                "=/{}",
                self.limit_per.expect("could not unwrap limit_per")
            ),
        }
    }
}

impl<'a> Into<String> for &'a Filter {
    fn into(self) -> String {
        let subject: String = match self.subject {
            Some(ref s) => s.into(),
            None => ":".into(),
        };

        let resource: &str = match self.resource {
            Some(ref r) => r.into(),
            None => "",
        };

        let action: &str = match self.action {
            Some(ref a) => a.into(),
            None => "",
        };

        let limit: String = match self.limit {
            Some(ref l) => l.into(),
            None => "".into(),
        };

        format!("{}:{}:{}={}", subject, resource, action, limit)
    }
}

impl From<Rule> for Filter {
    fn from(rule: Rule) -> Self {
        Filter {
            subject_type: None,
            subject: Some(rule.subject),
            resource: Some(rule.resource),
            limit: Some(rule.limit),
            limit_per: None,
            action: Some(rule.action),
        }
    }
}

impl<'a> From<&'a Rule> for Filter {
    fn from(rule: &'a Rule) -> Self {
        let rule = rule.clone();
        Filter {
            subject_type: None,
            subject: Some(rule.subject),
            resource: Some(rule.resource),
            limit: Some(rule.limit),
            limit_per: None,
            action: Some(rule.action),
        }
    }
}

impl<'a> From<&'a Subject> for Filter {
    fn from(subject: &'a Subject) -> Self {
        Filter::new().subject(subject)
    }
}

impl From<Subject> for Filter {
    fn from(subject: Subject) -> Self {
        Filter::new().subject(&subject)
    }
}

impl<'a> From<&'a SubjectType> for Filter {
    fn from(subject_type: &'a SubjectType) -> Self {
        Filter::new().subject_type(subject_type)
    }
}

impl From<SubjectType> for Filter {
    fn from(subject_type: SubjectType) -> Self {
        Filter::new().subject_type(&subject_type)
    }
}

impl<'a> From<&'a Action> for Filter {
    fn from(action: &'a Action) -> Self {
        Filter::new().action(action)
    }
}

impl From<Action> for Filter {
    fn from(action: Action) -> Self {
        Filter::new().action(&action)
    }
}

impl<'a> From<&'a Limit> for Filter {
    fn from(limit: &'a Limit) -> Self {
        Filter::new().limit(limit)
    }
}

impl From<Limit> for Filter {
    fn from(limit: Limit) -> Self {
        Filter::new().limit(&limit)
    }
}

/// Enum representing the state of `RACCT`/`RCTL` in the kernel.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Copy)]
pub enum State {
    /// `RCTL` / `RACCT` is present in the kernel, but is not enabled via the
    /// `kern.racct.enable` tunable.
    Disabled,

    /// `RCTL` / `RACCT` is enabled.
    Enabled,

    /// `RCTL` / `RACCT` is disabled.
    ///
    /// The kernel does not support `RCTL` / `RACCT`. The following options have
    /// to be set in the kernel configuration when compiling the kernel to
    /// add support for `RCTL` / `RACCT`:
    ///
    /// ```ignore
    /// options         RACCT
    /// options         RCTL
    /// ```
    NotPresent,

    /// `RCTL` is not available within a Jail
    Jailed,
}

impl State {
    /// Check the state of the `RCTL` / `RACCT` support.
    ///
    /// This queries the `kern.racct.enable` sysctl. If this fails in any way,
    /// (most probably by the sysctl not being present), the kernel is assumed
    /// to be compiled without the `RCTL` / `RACCT` options.
    ///
    /// # Example
    ///
    /// ```
    /// # use rctl;
    /// let state = rctl::State::check();
    /// ```
    pub fn check() -> State {
        // RCTL is not available in a jail
        let jailed = sysctl::Ctl::new("security.jail.jailed");

        // If the sysctl call fails (unlikely), we assume we're in a Jail.
        if jailed.is_err() {
            return State::Jailed;
        }

        match jailed.unwrap().value() {
            Ok(sysctl::CtlValue::Int(0)) => {}
            _ => return State::Jailed,
        };

        // Check the kern.racct.enable sysctl.
        let enable_racct = sysctl::Ctl::new("kern.racct.enable");

        // If the sysctl call fails, we assume it to be disabled.
        if enable_racct.is_err() {
            return State::NotPresent;
        }

        match enable_racct.unwrap().value() {
            Ok(sysctl::CtlValue::Uint(v)) => match v {
                1 => State::Enabled,
                _ => State::Disabled,
            },
            // If we could not get the sysctl value, assume it to be disabled.
            _ => State::NotPresent,
        }
    }

    /// Return `true` if the `RCTL` / `RACCT` support is [Enabled].
    ///
    /// # Examples
    ///
    /// ```
    /// # use rctl;
    /// if rctl::State::check().is_enabled() {
    ///     // do things requiring `RCTL` / `RACCT` support.
    /// }
    /// ```
    ///
    /// [Enabled]: State::Enabled
    pub fn is_enabled(&self) -> bool {
        match self {
            State::Enabled => true,
            _ => false,
        }
    }

    /// Return `true` if the kernel has `RCTL` / `RACCT` support compiled in.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rctl;
    /// if ! rctl::State::check().is_present() {
    ///     println!("The kernel does not have RCTL / RACCT support");
    /// }
    /// ```
    pub fn is_present(&self) -> bool {
        match self {
            State::NotPresent => false,
            _ => true,
        }
    }
}

impl fmt::Display for State {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            State::Enabled => write!(f, "enabled"),
            State::Disabled => write!(f, "disabled"),
            State::NotPresent => write!(f, "not present"),
            State::Jailed => write!(f, "not available in a jail"),
        }
    }
}

fn rctl_api_wrapper<S: Into<String>>(
    api: unsafe extern "C" fn(*const libc::c_char, libc::size_t, *mut libc::c_char, libc::size_t)
        -> libc::c_int,
    input: S,
) -> Result<String, Error> {
    // Get the input buffer as a C string.
    let input: String = input.into();
    let inputlen = input.len() + 1;
    let inbuf = CString::new(input).map_err(Error::CStringError)?;

    // C compatible output buffer.
    let mut outbuf: Vec<i8> = vec![0; RCTL_DEFAULT_BUFSIZE];

    loop {
        // Unsafe C call to get the jail resource usage.
        if unsafe { api(inbuf.as_ptr(), inputlen, outbuf.as_mut_ptr(), outbuf.len()) } != 0 {
            let err = io::Error::last_os_error();

            match err.raw_os_error() {
                Some(libc::ERANGE) => {
                    // if the error code is ERANGE, retry with a larger buffer
                    let current_len = outbuf.len();
                    outbuf.resize(current_len + RCTL_DEFAULT_BUFSIZE, 0);
                    continue;
                }
                Some(libc::EPERM) => {
                    let state = State::check();
                    break match state.is_enabled() {
                        true => Err(Error::OsError(err)),
                        false => Err(Error::InvalidKernelState(State::check())),
                    };
                }
                Some(libc::ENOSYS) => break Err(Error::InvalidKernelState(State::check())),
                Some(libc::ESRCH) => break Ok("".into()),
                _ => break Err(Error::OsError(err)),
            }
        }

        // If everything went well, convert the return C string in the outbuf
        // back into an easily usable Rust string and return.
        break Ok(unsafe { CStr::from_ptr(outbuf.as_ptr() as *mut i8) }
            .to_string_lossy()
            .into());
    }
}

#[cfg(test)]
pub mod tests {
    use super::*;
    use std::collections::HashSet;

    #[test]
    fn parse_subject_type() {
        assert_eq!(
            "user"
                .parse::<SubjectType>()
                .expect("could not parse user subject type"),
            SubjectType::User,
        );

        assert_eq!(
            "jail"
                .parse::<SubjectType>()
                .expect("could not parse jail subject type"),
            SubjectType::Jail,
        );

        assert!("bogus".parse::<SubjectType>().is_err());
    }

    #[test]
    fn parse_subject() {
        assert_eq!(
            "user:42"
                .parse::<Subject>()
                .expect("Could not parse 'user:42' as Subject"),
            Subject::user_id(42)
        );

        assert_eq!(
            "user:nobody"
                .parse::<Subject>()
                .expect("Could not parse 'user:nobody' as Subject"),
            Subject::user_name("nobody").expect("no user 'nobody'")
        );

        assert_eq!(
            "process:42"
                .parse::<Subject>()
                .expect("Could not parse 'process:42' as Subject"),
            Subject::process_id(42)
        );

        assert_eq!(
            "jail:www"
                .parse::<Subject>()
                .expect("Could not parse 'jail:www' as Subject"),
            Subject::jail_name("www")
        );

        assert_eq!(
            "loginclass:test"
                .parse::<Subject>()
                .expect("Could not parse 'loginclass:test' as Subject"),
            Subject::login_class("test")
        );

        assert!("".parse::<Subject>().is_err());
        assert!(":".parse::<Subject>().is_err());
        assert!(":1234".parse::<Subject>().is_err());
        assert!("bogus".parse::<Subject>().is_err());
        assert!("user".parse::<Subject>().is_err());
        assert!("process:bogus".parse::<Subject>().is_err());
        assert!("process:".parse::<Subject>().is_err());
        assert!("user:test:bogus".parse::<Subject>().is_err());
    }

    #[test]
    fn parse_resource() {
        assert_eq!(
            "vmemoryuse"
                .parse::<Resource>()
                .expect("could not parse vmemoryuse resource"),
            Resource::VMemoryUse,
        );

        assert!("bogus".parse::<Resource>().is_err());
    }

    #[test]
    fn parse_action() {
        assert_eq!(
            "deny"
                .parse::<Action>()
                .expect("could not parse deny action"),
            Action::Deny
        );

        assert_eq!(
            "log".parse::<Action>().expect("could not parse log action"),
            Action::Log
        );

        assert_eq!(
            "throttle"
                .parse::<Action>()
                .expect("could not parse throttle action"),
            Action::Throttle
        );

        assert_eq!(
            "devctl"
                .parse::<Action>()
                .expect("could not parse devctl action"),
            Action::DevCtl
        );

        assert_eq!(
            "sigterm"
                .parse::<Action>()
                .expect("could not parse sigterm action"),
            Action::Signal(Signal::SIGTERM)
        );

        assert!("bogus".parse::<Action>().is_err());
    }

    #[test]
    fn display_limit() {
        assert_eq!(
            Limit {
                amount: 100 * 1024 * 1024,
                per: None
            }.to_string(),
            "100m".to_string()
        );

        assert_eq!(
            Limit {
                amount: 100 * 1024 * 1024,
                per: Some(SubjectType::User)
            }.to_string(),
            "100m/user".to_string()
        );

        assert_eq!(
            Limit {
                amount: 42,
                per: Some(SubjectType::LoginClass)
            }.to_string(),
            "42/loginclass".to_string()
        );
    }

    #[test]
    fn parse_limit() {
        assert_eq!(
            "100m"
                .parse::<Limit>()
                .expect("Could not parse '100m' as Limit"),
            Limit::amount(100 * 1024 * 1024),
        );

        assert_eq!(
            "100m/user"
                .parse::<Limit>()
                .expect("Could not parse '100m/user' as Limit"),
            Limit::amount_per(100 * 1024 * 1024, SubjectType::User),
        );

        assert!("100m/bogus".parse::<Limit>().is_err());
        assert!("100m/userbogus".parse::<Limit>().is_err());
        assert!("100q".parse::<Limit>().is_err());
        assert!("-42".parse::<Limit>().is_err());
        assert!("".parse::<Limit>().is_err());
        assert!("bogus".parse::<Limit>().is_err());
    }

    #[test]
    fn parse_rule() {
        assert_eq!(
            "user:nobody:vmemoryuse:deny=1g"
                .parse::<Rule>()
                .expect("Could not parse 'user:nobody:vmemoryuse:deny=1g' as Rule"),
            Rule {
                subject: Subject::user_name("nobody").expect("no user 'nobody'"),
                resource: Resource::VMemoryUse,
                action: Action::Deny,
                limit: Limit::amount(1 * 1024 * 1024 * 1024),
            }
        );

        assert!(":::=/".parse::<Rule>().is_err());
        assert!("user:missing_resource:=100m/user".parse::<Rule>().is_err());
        assert!("user:missing_resource=100m/user".parse::<Rule>().is_err());
        assert!(
            "user:too:many:colons:vmemoryuse:deny=100m/user"
                .parse::<Rule>()
                .is_err()
        );
        assert!(
            "loginclass:nolimit:vmemoryuse:deny="
                .parse::<Rule>()
                .is_err()
        );
        assert!(
            "loginclass:nolimit:vmemoryuse:deny"
                .parse::<Rule>()
                .is_err()
        );
        assert!(
            "loginclass:equals:vmemoryuse:deny=123=456"
                .parse::<Rule>()
                .is_err()
        );
        assert!("-42".parse::<Rule>().is_err());
        assert!("".parse::<Rule>().is_err());
        assert!("bogus".parse::<Rule>().is_err());
    }

    #[test]
    fn display_filter() {
        assert_eq!(Filter::new().to_string(), ":".to_string());

        assert_eq!(
            Filter::new()
                .subject_type(&SubjectType::LoginClass)
                .to_string(),
            "loginclass:".to_string()
        );

        assert_eq!(
            Filter::new().subject(&Subject::user_id(42)).to_string(),
            "user:42".to_string()
        );

        assert_eq!(
            Filter::new().resource(&Resource::MaxProcesses).to_string(),
            "::maxproc".to_string()
        );

        assert_eq!(
            Filter::new()
                .subject(&Subject::user_id(42))
                .resource(&Resource::MemoryUse)
                .to_string(),
            "user:42:memoryuse".to_string()
        );

        assert_eq!(Filter::new().deny().to_string(), ":::deny".to_string());
    }

    #[test]
    fn iterate_rules() {
        if !State::check().is_enabled() {
            return;
        }

        let common_subject = Subject::jail_name("testjail_rctl_rules");
        let rule1 = Rule {
            subject: common_subject.clone(),
            resource: Resource::VMemoryUse,
            action: Action::Log,
            limit: Limit::amount(100 * 1024 * 1024),
        };
        rule1.apply().expect("Could not apply rule 1");

        let rule2 = Rule {
            subject: common_subject.clone(),
            resource: Resource::StackSize,
            action: Action::Log,
            limit: Limit::amount(100 * 1024 * 1024),
        };
        rule2.apply().expect("Could not apply rule 2");

        let filter = Filter::new().subject(&common_subject);

        let rules: HashSet<_> = filter
            .rules()
            .expect("Could not get rules matching filter")
            .into_iter()
            .collect();

        assert!(rules.contains(&rule1));
        assert!(rules.contains(&rule2));

        filter.remove_rules().expect("Could not remove rules");
    }

    #[cfg(feature="serialize")]
    #[test]
    fn serialize_rule() {
        let rule = "process:23:vmemoryuse:sigterm=100m"
            .parse::<Rule>()
            .expect("Could not parse rule");

        let serialized = serde_json::to_string(&rule)
            .expect("Could not serialize rule");

        let rule_map: serde_json::Value = serde_json::from_str(&serialized)
            .expect("Could not load serialized rule");

        assert_eq!(rule_map["subject"]["Process"], 23);
        assert_eq!(rule_map["resource"], "VMemoryUse");
        assert_eq!(rule_map["action"]["Signal"], "SIGTERM");
        assert_eq!(rule_map["limit"]["amount"], 100 * 1024 * 1024)
    }
}