unofficial mirror of guix-patches@gnu.org 
 help / color / mirror / code / Atom feed
blob bdc0ee3bf71eff9fd17edd1597b1a3aa1a5629c6 181188 bytes (raw)
name: gnu/services/mail.scm 	 # note: path name is non-authoritative(*)

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
 
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2015 Andy Wingo <wingo@igalia.com>
;;; Copyright © 2017, 2018 Clément Lassieur <clement@lassieur.org>
;;; Copyright © 2017 Carlo Zancanaro <carlo@zancanaro.id.au>
;;; Copyright © 2017, 2020 Tobias Geerinckx-Rice <me@tobias.gr>
;;; Copyright © 2019 Kristofer Buffington <kristoferbuffington@gmail.com>
;;; Copyright © 2020 Jonathan Brielmaier <jonathan.brielmaier@web.de>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.
;;;
;;; Some of the help text was taken from the default dovecot.conf files.

(define-module (gnu services mail)
  #:use-module (gnu services)
  #:use-module (gnu services base)
  #:use-module (gnu services configuration)
  #:use-module (gnu services shepherd)
  #:use-module (gnu system pam)
  #:use-module (gnu system shadow)
  #:use-module (gnu packages mail)
  #:use-module (gnu packages admin)
  #:use-module (gnu packages dav)
  #:use-module (gnu packages tls)
  #:use-module (guix records)
  #:use-module (guix packages)
  #:use-module (guix gexp)
  #:use-module (ice-9 match)
  #:use-module (ice-9 format)
  #:use-module (srfi srfi-1)
  #:export (dovecot-service
            dovecot-service-type
            dovecot-configuration
            opaque-dovecot-configuration

            dict-configuration
            passdb-configuration
            userdb-configuration
            unix-listener-configuration
            fifo-listener-configuration
            inet-listener-configuration
            service-configuration
            protocol-configuration
            plugin-configuration
            mailbox-configuration
            namespace-configuration

            opensmtpd-table-configuration
            opensmtpd-table-configuration?
            opensmtpd-table-configuration-name
            opensmtpd-table-configuration-file-db
            opensmtpd-table-configuration-data

            opensmtpd-ca-configuration
            opensmtpd-ca-configuration?
            opensmtpd-ca-configuration-name
            opensmtpd-ca-configuration-file

            opensmtpd-pki-configuration
            opensmtpd-pki-configuration?
            opensmtpd-pki-configuration-domain
            opensmtpd-pki-configuration-cert
            opensmtpd-pki-configuration-key
            opensmtpd-pki-configuration-dhe

            opensmtpd-action-local-delivery-configuration
            opensmtpd-action-local-delivery-configuration?
            opensmtpd-action-local-delivery-configuration-method
            opensmtpd-action-local-delivery-configuration-alias
            opensmtpd-action-local-delivery-configuration-ttl
            opensmtpd-action-local-delivery-configuration-user
            opensmtpd-action-local-delivery-configuration-userbase
            opensmtpd-action-local-delivery-configuration-virtual
            opensmtpd-action-local-delivery-configuration-wrapper

            opensmtpd-maildir-configuration
            opensmtpd-maildir-configuration?
            opensmtpd-maildir-configuration-pathname
            opensmtpd-maildir-configuration-junk

            opensmtpd-mda-configuration
            opensmtpd-mda-configuration-name
            opensmtpd-mda-configuration-command

            opensmtpd-action-relay-configuration
            opensmtpd-action-relay-configuration?
            opensmtpd-action-relay-configuration-backup
            opensmtpd-action-relay-configuration-backup-mx
            opensmtpd-action-relay-configuration-helo
            opensmtpd-action-relay-configuration-domain
            opensmtpd-action-relay-configuration-host
            opensmtpd-action-relay-configuration-pki
            opensmtpd-action-relay-configuration-srs
            opensmtpd-action-relay-configuration-tls
            opensmtpd-action-relay-configuration-auth
            opensmtpd-action-relay-configuration-mail-from
            opensmtpd-action-relay-configuration-src

            opensmtpd-option-configuration
            opensmtpd-option-configuration?
            opensmtpd-option-configuration-option
            opensmtpd-option-configuration-not
            opensmtpd-option-configuration-regex
            opensmtpd-option-configuration-data

            opensmtpd-filter-phase-configuration
            opensmtpd-filter-phase-configuration?
            opensmtpd-filter-phase-configuration-name
            opensmtpd-filter-phase-configuration-phase-name
            opensmtpd-filter-phase-configuration-options
            opensmtpd-filter-phase-configuration-decision
            opensmtpd-filter-phase-configuration-message
            opensmtpd-filter-phase-configuration-value

            opensmtpd-filter-configuration
            opensmtpd-filter-configuration?
            opensmtpd-filter-configuration-name
            opensmtpd-filter-configuration-proc

            opensmtpd-listen-on-configuration
            opensmtpd-listen-on-configuration?
            opensmtpd-listen-on-configuration-interface
            opensmtpd-listen-on-configuration-family
            opensmtpd-listen-on-configuration-auth
            opensmtpd-listen-on-configuration-auth-optional
            opensmtpd-listen-on-configuration-filters
            opensmtpd-listen-on-configuration-hostname
            opensmtpd-listen-on-configuration-hostnames
            opensmtpd-listen-on-configuration-mask-src
            opensmtpd-listen-on-configuration-disable-dsn
            opensmtpd-listen-on-configuration-pki
            opensmtpd-listen-on-configuration-port
            opensmtpd-listen-on-configuration-proxy-v2
            opensmtpd-listen-on-configuration-received-auth
            opensmtpd-listen-on-configuration-senders
            opensmtpd-listen-on-configuration-secure-connection
            opensmtpd-listen-on-configuration-tag

            opensmtpd-listen-on-socket-configuration
            opensmtpd-listen-on-socket-configuration?
            opensmtpd-listen-on-socket-configuration-filters
            opensmtpd-listen-on-socket-configuration-mask-src
            opensmtpd-listen-on-socket-configuration-tag

            opensmtpd-match-configuration
            opensmtpd-match-configuration?
            opensmtpd-match-configuration-action
            opensmtpd-match-configuration-options

            opensmtpd-smtp-configuration
            opensmtpd-smtp-configuration?
            opensmtpd-smtp-configuration-ciphers
            opensmtpd-smtp-configuration-limit-max-mails
            opensmtpd-smtp-configuration-limit-max-rcpt
            opensmtpd-smtp-configuration-max-message-size
            opensmtpd-smtp-configuration-sub-addr-delim character

            opensmtpd-srs-configuration
            opensmtpd-srs-configuration?
            opensmtpd-srs-configuration-key
            opensmtpd-srs-configuration-backup-key
            opensmtpd-srs-configuration-ttl-delay

            opensmtpd-queue-configuration
            opensmtpd-queue-configuration?
            opensmtpd-queue-configuration-compression
            opensmtpd-queue-configuration-encryption
            opensmtpd-queue-configuration-ttl-delay

            opensmtpd-configuration
            opensmtpd-configuration?
            opensmtpd-package
            opensmtpd-config-file
            opensmtpd-configuration-bounce
            opensmtpd-configuration-listen-ons
            opensmtpd-configuration-listen-on-socket
            opensmtpd-configuration-includes
            opensmtpd-configuration-matches
            opensmtpd-configuration-mda-wrappers
            opensmtpd-configuration-mta-max-deferred
            opensmtpd-configuration-srs
            opensmtpd-configuration-smtp
            opensmtpd-configuration-queue

            opensmtpd-service-type
            %default-opensmtpd-config-file

            mail-aliases-service-type

            exim-configuration
            exim-configuration?
            exim-service-type
            %default-exim-config-file

            imap4d-configuration
            imap4d-configuration?
            imap4d-service-type
            %default-imap4d-config-file

            radicale-configuration
            radicale-configuration?
            radicale-service-type
            %default-radicale-config-file))

;;; Commentary:
;;;
;;; This module provides service definitions for the Dovecot POP3 and IMAP
;;; mail server.
;;;
;;; Code:

(define (uglify-field-name field-name)
  (let ((str (symbol->string field-name)))
    (string-join (string-split (if (string-suffix? "?" str)
                                   (substring str 0 (1- (string-length str)))
                                   str)
                               #\-)
                 "_")))

(define (serialize-field field-name val)
  (format #t "~a=~a\n" (uglify-field-name field-name) val))

(define (serialize-string field-name val)
  (serialize-field field-name val))

(define (space-separated-string-list? val)
  (and (list? val)
       (and-map (lambda (x)
                  (and (string? x) (not (string-index x #\space))))
                val)))
(define (serialize-space-separated-string-list field-name val)
  (match val
    (() #f)
    (_ (serialize-field field-name (string-join val " ")))))

(define (comma-separated-string-list? val)
  (and (list? val)
       (and-map (lambda (x)
                  (and (string? x) (not (string-index x #\,))))
                val)))
(define (serialize-comma-separated-string-list field-name val)
  (serialize-field field-name (string-join val ",")))

(define (file-name? val)
  (and (string? val)
       (string-prefix? "/" val)))
(define (serialize-file-name field-name val)
  (serialize-string field-name val))

(define (colon-separated-file-name-list? val)
  (and (list? val)
       ;; Trailing slashes not needed and not
       (and-map file-name? val)))
(define (serialize-colon-separated-file-name-list field-name val)
  (serialize-field field-name (string-join val ":")))

(define (serialize-boolean field-name val)
  (serialize-string field-name (if val "yes" "no")))

(define (non-negative-integer? val)
  (and (exact-integer? val) (not (negative? val))))
(define (serialize-non-negative-integer field-name val)
  (serialize-field field-name val))

(define (hours? val) (non-negative-integer? val))
(define (serialize-hours field-name val)
  (serialize-field field-name (format #f "~a hours" val)))

(define (free-form-fields? val)
  (match val
    (() #t)
    ((((? symbol?) . (? string?)) . val) (free-form-fields? val))
    (_ #f)))
(define (serialize-free-form-fields field-name val)
  (for-each (match-lambda ((k . v) (serialize-field k v))) val))

(define (free-form-args? val)
  (match val
    (() #t)
    ((((? symbol?) . (? string?)) . val) (free-form-args? val))
    (_ #f)))
(define (serialize-free-form-args field-name val)
  (serialize-field field-name
                   (string-join
                    (map (match-lambda ((k . v) (format #f "~a=~a" k v))) val)
                    " ")))

(define-configuration dict-configuration
  (entries
   (free-form-fields '())
   "A list of key-value pairs that this dict should hold."))

(define (serialize-dict-configuration field-name val)
  (format #t "dict {\n")
  (serialize-configuration val dict-configuration-fields)
  (format #t "}\n"))

(define-configuration passdb-configuration
  (driver
   (string "pam")
   "The driver that the passdb should use.  Valid values include
@samp{pam}, @samp{passwd}, @samp{shadow}, @samp{bsdauth}, and
@samp{static}.")
  (args
   (space-separated-string-list '())
   "Space separated list of arguments to the passdb driver."))

(define (serialize-passdb-configuration field-name val)
  (format #t "passdb {\n")
  (serialize-configuration val passdb-configuration-fields)
  (format #t "}\n"))
(define (passdb-configuration-list? val)
  (and (list? val) (and-map passdb-configuration? val)))
(define (serialize-passdb-configuration-list field-name val)
  (for-each (lambda (val) (serialize-passdb-configuration field-name val)) val))

(define-configuration userdb-configuration
  (driver
   (string "passwd")
   "The driver that the userdb should use.  Valid values include
@samp{passwd} and @samp{static}.")
  (args
   (space-separated-string-list '())
   "Space separated list of arguments to the userdb driver.")
  (override-fields
   (free-form-args '())
   "Override fields from passwd."))

(define (serialize-userdb-configuration field-name val)
  (format #t "userdb {\n")
  (serialize-configuration val userdb-configuration-fields)
  (format #t "}\n"))
(define (userdb-configuration-list? val)
  (and (list? val) (and-map userdb-configuration? val)))
(define (serialize-userdb-configuration-list field-name val)
  (for-each (lambda (val) (serialize-userdb-configuration field-name val)) val))

(define-configuration unix-listener-configuration
  (path
   (string (configuration-missing-field 'unix-listener 'path))
   "Path to the file, relative to @code{base-dir} field.  This is also used as
the section name.")
  (mode
   (string "0600")
   "The access mode for the socket.")
  (user
   (string "")
   "The user to own the the socket.")
  (group
   (string "")
   "The group to own the socket."))

(define (serialize-unix-listener-configuration field-name val)
  (format #t "unix_listener ~a {\n" (unix-listener-configuration-path val))
  (serialize-configuration val (cdr unix-listener-configuration-fields))
  (format #t "}\n"))

(define-configuration fifo-listener-configuration
  (path
   (string (configuration-missing-field 'fifo-listener 'path))
   "Path to the file, relative to @code{base-dir} field.  This is also used as
the section name.")
  (mode
   (string "0600")
   "The access mode for the socket.")
  (user
   (string "")
   "The user to own the the socket.")
  (group
   (string "")
   "The group to own the socket."))

(define (serialize-fifo-listener-configuration field-name val)
  (format #t "fifo_listener ~a {\n" (fifo-listener-configuration-path val))
  (serialize-configuration val (cdr fifo-listener-configuration-fields))
  (format #t "}\n"))

(define-configuration inet-listener-configuration
  (protocol
   (string (configuration-missing-field 'inet-listener 'protocol))
   "The protocol to listen for.")
  (address
   (string "")
   "The address on which to listen, or empty for all addresses.")
  (port
   (non-negative-integer
    (configuration-missing-field 'inet-listener 'port))
   "The port on which to listen.")
  (ssl?
   (boolean #t)
   "Whether to use SSL for this service; @samp{yes}, @samp{no}, or
@samp{required}."))

(define (serialize-inet-listener-configuration field-name val)
  (format #t "inet_listener ~a {\n" (inet-listener-configuration-protocol val))
  (serialize-configuration val (cdr inet-listener-configuration-fields))
  (format #t "}\n"))

(define (listener-configuration? val)
  (or (unix-listener-configuration? val)
      (fifo-listener-configuration? val)
      (inet-listener-configuration? val)))
(define (serialize-listener-configuration field-name val)
  (cond
   ((unix-listener-configuration? val)
    (serialize-unix-listener-configuration field-name val))
   ((fifo-listener-configuration? val)
    (serialize-fifo-listener-configuration field-name val))
   ((inet-listener-configuration? val)
    (serialize-inet-listener-configuration field-name val))
   (else (configuration-field-error field-name val))))
(define (listener-configuration-list? val)
  (and (list? val) (and-map listener-configuration? val)))
(define (serialize-listener-configuration-list field-name val)
  (for-each (lambda (val)
              (serialize-listener-configuration field-name val))
            val))

(define-configuration service-configuration
  (kind
   (string (configuration-missing-field 'service 'kind))
   "The service kind.  Valid values include @code{director},
@code{imap-login}, @code{pop3-login}, @code{lmtp}, @code{imap},
@code{pop3}, @code{auth}, @code{auth-worker}, @code{dict},
@code{tcpwrap}, @code{quota-warning}, or anything else.")
  (listeners
   (listener-configuration-list '())
   "Listeners for the service.  A listener is either an
@code{unix-listener-configuration}, a @code{fifo-listener-configuration}, or
an @code{inet-listener-configuration}.")
  (client-limit
   (non-negative-integer 0)
   "Maximum number of simultaneous client connections per process.  Once this
number of connections is received, the next incoming connection will prompt
Dovecot to spawn another process.  If set to 0, @code{default-client-limit} is
used instead.")
  (service-count
   (non-negative-integer 1)
   "Number of connections to handle before starting a new process.
Typically the only useful values are 0 (unlimited) or 1.  1 is more
secure, but 0 is faster.  <doc/wiki/LoginProcess.txt>.")
  (process-limit
   (non-negative-integer 0)
   "Maximum number of processes that can exist for this service.  If set to 0,
@code{default-process-limit} is used instead.")
  (process-min-avail
   (non-negative-integer 0)
   "Number of processes to always keep waiting for more connections.")
  ;; FIXME: Need to be able to take the default for this value from other
  ;; parts of the config.
  (vsz-limit
   (non-negative-integer #e256e6)
   "If you set @samp{service-count 0}, you probably need to grow
this."))

(define (serialize-service-configuration field-name val)
  (format #t "service ~a {\n" (service-configuration-kind val))
  (serialize-configuration val (cdr service-configuration-fields))
  (format #t "}\n"))
(define (service-configuration-list? val)
  (and (list? val) (and-map service-configuration? val)))
(define (serialize-service-configuration-list field-name val)
  (for-each (lambda (val)
              (serialize-service-configuration field-name val))
            val))

(define-configuration protocol-configuration
  (name
   (string (configuration-missing-field 'protocol 'name))
   "The name of the protocol.")
  (auth-socket-path
   (string "/var/run/dovecot/auth-userdb")
   "UNIX socket path to master authentication server to find users.
This is used by imap (for shared users) and lda.")
  (mail-plugins
   (space-separated-string-list '("$mail_plugins"))
   "Space separated list of plugins to load.")
  (mail-max-userip-connections
   (non-negative-integer 10)
   "Maximum number of IMAP connections allowed for a user from each IP
address.  NOTE: The username is compared case-sensitively.")
  (imap-metadata?
   (boolean #f)
   "Whether to enable the @code{IMAP METADATA} extension as defined in
@uref{https://tools.ietf.org/html/rfc5464, RFC@tie{}5464}, which provides
a means for clients to set and retrieve per-mailbox, per-user metadata
and annotations over IMAP.

If this is @samp{#t}, you must also specify a dictionary @i{via} the
@code{mail-attribute-dict} setting.")
  (managesieve-notify-capability
   (space-separated-string-list '())
   "Which NOTIFY capabilities to report to clients that first connect to
the ManageSieve service, before authentication.  These may differ from the
capabilities offered to authenticated users.  If this field is left empty,
report what the Sieve interpreter supports by default.")
  (managesieve-sieve-capability
   (space-separated-string-list '())
   "Which SIEVE capabilities to report to clients that first connect to
the ManageSieve service, before authentication.  These may differ from the
capabilities offered to authenticated users.  If this field is left empty,
report what the Sieve interpreter supports by default."))

(define (serialize-protocol-configuration field-name val)
  (format #t "protocol ~a {\n" (protocol-configuration-name val))
  (serialize-configuration val (cdr protocol-configuration-fields))
  (format #t "}\n"))
(define (protocol-configuration-list? val)
  (and (list? val) (and-map protocol-configuration? val)))
(define (serialize-protocol-configuration-list field-name val)
  (serialize-field 'protocols
                   (string-join (map protocol-configuration-name val) " "))
  (for-each (lambda (val)
              (serialize-protocol-configuration field-name val))
            val))

(define-configuration plugin-configuration
  (entries
   (free-form-fields '())
   "A list of key-value pairs that this dict should hold."))

(define (serialize-plugin-configuration field-name val)
  (format #t "plugin {\n")
  (serialize-configuration val plugin-configuration-fields)
  (format #t "}\n"))

(define-configuration mailbox-configuration
  (name
   (string (error "mailbox name is required"))
   "Name for this mailbox.")

  (auto
   (string "no")
   "@samp{create} will automatically create this mailbox.
@samp{subscribe} will both create and subscribe to the mailbox.")

  (special-use
   (space-separated-string-list '())
   "List of IMAP @code{SPECIAL-USE} attributes as specified by RFC 6154.
Valid values are @code{\\All}, @code{\\Archive}, @code{\\Drafts},
@code{\\Flagged}, @code{\\Junk}, @code{\\Sent}, and @code{\\Trash}."))

(define (serialize-mailbox-configuration field-name val)
  (format #t "mailbox \"~a\" {\n" (mailbox-configuration-name val))
  (serialize-configuration val (cdr mailbox-configuration-fields))
  (format #t "}\n"))
(define (mailbox-configuration-list? val)
  (and (list? val) (and-map mailbox-configuration? val)))
(define (serialize-mailbox-configuration-list field-name val)
  (for-each (lambda (val)
              (serialize-mailbox-configuration field-name val))
            val))

(define-configuration namespace-configuration
  (name
   (string (error "namespace name is required"))
   "Name for this namespace.")

  (type
   (string "private")
   "Namespace type: @samp{private}, @samp{shared} or @samp{public}.")

  (separator
   (string "")
   "Hierarchy separator to use. You should use the same separator for
all namespaces or some clients get confused.  @samp{/} is usually a good
one.  The default however depends on the underlying mail storage
format.")

  (prefix
   (string "")
   "Prefix required to access this namespace.  This needs to be
different for all namespaces. For example @samp{Public/}.")

  (location
   (string "")
   "Physical location of the mailbox. This is in same format as
mail_location, which is also the default for it.")

  (inbox?
   (boolean #f)
   "There can be only one INBOX, and this setting defines which
namespace has it.")

  (hidden?
   (boolean #f)
   "If namespace is hidden, it's not advertised to clients via NAMESPACE
extension. You'll most likely also want to set @samp{list? #f}.  This is mostly
useful when converting from another server with different namespaces
which you want to deprecate but still keep working.  For example you can
create hidden namespaces with prefixes @samp{~/mail/}, @samp{~%u/mail/}
and @samp{mail/}.")

  (list?
   (boolean #t)
   "Show the mailboxes under this namespace with LIST command. This
makes the namespace visible for clients that don't support NAMESPACE
extension.  The special @code{children} value lists child mailboxes, but
hides the namespace prefix.")

  (subscriptions?
   (boolean #t)
   "Namespace handles its own subscriptions.  If set to @code{#f}, the
parent namespace handles them.  The empty prefix should always have this
as @code{#t}.)")

  (mailboxes
   (mailbox-configuration-list '())
   "List of predefined mailboxes in this namespace."))

(define (serialize-namespace-configuration field-name val)
  (format #t "namespace ~a {\n" (namespace-configuration-name val))
  (serialize-configuration val (cdr namespace-configuration-fields))
  (format #t "}\n"))
(define (list-of-namespace-configuration? val)
  (and (list? val) (and-map namespace-configuration? val)))
(define (serialize-list-of-namespace-configuration field-name val)
  (for-each (lambda (val)
              (serialize-namespace-configuration field-name val))
            val))

(define-configuration dovecot-configuration
  (dovecot
   (file-like dovecot)
   "The dovecot package.")

  (listen
   (comma-separated-string-list '("*" "::"))
   "A list of IPs or hosts where to listen in for connections.  @samp{*}
listens in all IPv4 interfaces, @samp{::} listens in all IPv6
interfaces.  If you want to specify non-default ports or anything more
complex, customize the address and port fields of the
@samp{inet-listener} of the specific services you are interested in.")

  (dict
   (dict-configuration (dict-configuration))
   "Dict configuration, as created by the @code{dict-configuration}
constructor.")

  (passdbs
   (passdb-configuration-list (list (passdb-configuration (driver "pam"))))
   "List of passdb configurations, each one created by the
@code{passdb-configuration} constructor.")

  (userdbs
   (userdb-configuration-list (list (userdb-configuration (driver "passwd"))))
   "List of userdb configurations, each one created by the
@code{userdb-configuration} constructor.")

  (plugin-configuration
   (plugin-configuration (plugin-configuration))
   "Plug-in configuration, created by the @code{plugin-configuration}
constructor.")

  (namespaces
   (list-of-namespace-configuration
    (list
     (namespace-configuration
      (name "inbox")
      (prefix "")
      (inbox? #t)
      (mailboxes
       (list
        (mailbox-configuration (name "Drafts") (special-use '("\\Drafts")))
        (mailbox-configuration (name "Junk") (special-use '("\\Junk")))
        (mailbox-configuration (name "Trash") (special-use '("\\Trash")))
        (mailbox-configuration (name "Sent") (special-use '("\\Sent")))
        (mailbox-configuration (name "Sent Messages") (special-use '("\\Sent")))
        (mailbox-configuration (name "Drafts") (special-use '("\\Drafts"))))))))
   "List of namespaces.  Each item in the list is created by the
@code{namespace-configuration} constructor.")

  (base-dir
   (file-name "/var/run/dovecot/")
   "Base directory where to store runtime data.")

  (login-greeting
   (string "Dovecot ready.")
   "Greeting message for clients.")

  (login-trusted-networks
   (space-separated-string-list '())
   "List of trusted network ranges.  Connections from these IPs are
allowed to override their IP addresses and ports (for logging and for
authentication checks).  @samp{disable-plaintext-auth} is also ignored
for these networks.  Typically you'd specify your IMAP proxy servers
here.")

  (login-access-sockets
   (space-separated-string-list '())
   "List of login access check sockets (e.g. tcpwrap).")

  (verbose-proctitle?
   (boolean #f)
   "Show more verbose process titles (in ps).  Currently shows user name
and IP address.  Useful for seeing who are actually using the IMAP
processes (e.g. shared mailboxes or if same uid is used for multiple
accounts).")

  (shutdown-clients?
   (boolean #t)
   "Should all processes be killed when Dovecot master process shuts down.
Setting this to @code{#f} means that Dovecot can be upgraded without
forcing existing client connections to close (although that could also
be a problem if the upgrade is e.g. because of a security fix).")

  (doveadm-worker-count
   (non-negative-integer 0)
   "If non-zero, run mail commands via this many connections to doveadm
server, instead of running them directly in the same process.")

  (doveadm-socket-path
   (string "doveadm-server")
   "UNIX socket or host:port used for connecting to doveadm server.")

  (import-environment
   (space-separated-string-list '("TZ"))
   "List of environment variables that are preserved on Dovecot startup
and passed down to all of its child processes.  You can also give
key=value pairs to always set specific settings.")

;;; Authentication processes

  (disable-plaintext-auth?
   (boolean #t)
   "Disable LOGIN command and all other plaintext authentications unless
SSL/TLS is used (LOGINDISABLED capability).  Note that if the remote IP
matches the local IP (i.e. you're connecting from the same computer),
the connection is considered secure and plaintext authentication is
allowed.  See also ssl=required setting.")

  (auth-cache-size
   (non-negative-integer 0)
   "Authentication cache size (e.g. @samp{#e10e6}).  0 means it's disabled.
Note that bsdauth, PAM and vpopmail require @samp{cache-key} to be set
for caching to be used.")

  (auth-cache-ttl
   (string "1 hour")
   "Time to live for cached data.  After TTL expires the cached record
is no longer used, *except* if the main database lookup returns internal
failure.  We also try to handle password changes automatically: If
user's previous authentication was successful, but this one wasn't, the
cache isn't used.  For now this works only with plaintext
authentication.")

  (auth-cache-negative-ttl
   (string "1 hour")
   "TTL for negative hits (user not found, password mismatch).
0 disables caching them completely.")

  (auth-realms
   (space-separated-string-list '())
   "List of realms for SASL authentication mechanisms that need them.
You can leave it empty if you don't want to support multiple realms.
Many clients simply use the first one listed here, so keep the default
realm first.")

  (auth-default-realm
   (string "")
   "Default realm/domain to use if none was specified.  This is used for
both SASL realms and appending @@domain to username in plaintext
logins.")

  (auth-username-chars
   (string
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890.-_@")
   "List of allowed characters in username.  If the user-given username
contains a character not listed in here, the login automatically fails.
This is just an extra check to make sure user can't exploit any
potential quote escaping vulnerabilities with SQL/LDAP databases.  If
you want to allow all characters, set this value to empty.")

  (auth-username-translation
   (string "")
   "Username character translations before it's looked up from
databases.  The value contains series of from -> to characters.  For
example @samp{#@@/@@} means that @samp{#} and @samp{/} characters are
translated to @samp{@@}.")

  (auth-username-format
   (string "%Lu")
   "Username formatting before it's looked up from databases.  You can
use the standard variables here, e.g. %Lu would lowercase the username,
%n would drop away the domain if it was given, or @samp{%n-AT-%d} would
change the @samp{@@} into @samp{-AT-}.  This translation is done after
@samp{auth-username-translation} changes.")

  (auth-master-user-separator
   (string "")
   "If you want to allow master users to log in by specifying the master
username within the normal username string (i.e. not using SASL
mechanism's support for it), you can specify the separator character
here.  The format is then <username><separator><master username>.
UW-IMAP uses @samp{*} as the separator, so that could be a good
choice.")

  (auth-anonymous-username
   (string "anonymous")
   "Username to use for users logging in with ANONYMOUS SASL
mechanism.")

  (auth-worker-max-count
   (non-negative-integer 30)
   "Maximum number of dovecot-auth worker processes.  They're used to
execute blocking passdb and userdb queries (e.g. MySQL and PAM).
They're automatically created and destroyed as needed.")

  (auth-gssapi-hostname
   (string "")
   "Host name to use in GSSAPI principal names.  The default is to use
the name returned by gethostname().  Use @samp{$ALL} (with quotes) to
allow all keytab entries.")

  (auth-krb5-keytab
   (string "")
   "Kerberos keytab to use for the GSSAPI mechanism.  Will use the
system default (usually /etc/krb5.keytab) if not specified.  You may
need to change the auth service to run as root to be able to read this
file.")

  (auth-use-winbind?
   (boolean #f)
   "Do NTLM and GSS-SPNEGO authentication using Samba's winbind daemon
and @samp{ntlm-auth} helper.
<doc/wiki/Authentication/Mechanisms/Winbind.txt>.")

  (auth-winbind-helper-path
   (file-name "/usr/bin/ntlm_auth")
   "Path for Samba's @samp{ntlm-auth} helper binary.")

  (auth-failure-delay
   (string "2 secs")
   "Time to delay before replying to failed authentications.")

  (auth-ssl-require-client-cert?
   (boolean #f)
   "Require a valid SSL client certificate or the authentication
fails.")

  (auth-ssl-username-from-cert?
   (boolean #f)
   "Take the username from client's SSL certificate, using
@code{X509_NAME_get_text_by_NID()} which returns the subject's DN's
CommonName.")

  (auth-mechanisms
   (space-separated-string-list '("plain"))
   "List of wanted authentication mechanisms.  Supported mechanisms are:
@samp{plain}, @samp{login}, @samp{digest-md5}, @samp{cram-md5},
@samp{ntlm}, @samp{rpa}, @samp{apop}, @samp{anonymous}, @samp{gssapi},
@samp{otp}, @samp{skey}, and @samp{gss-spnego}.  NOTE: See also
@samp{disable-plaintext-auth} setting.")

  (director-servers
   (space-separated-string-list '())
   "List of IPs or hostnames to all director servers, including ourself.
Ports can be specified as ip:port.  The default port is the same as what
director service's @samp{inet-listener} is using.")

  (director-mail-servers
   (space-separated-string-list '())
   "List of IPs or hostnames to all backend mail servers.  Ranges are
allowed too, like 10.0.0.10-10.0.0.30.")

  (director-user-expire
   (string "15 min")
   "How long to redirect users to a specific server after it no longer
has any connections.")

  (director-username-hash
   (string "%Lu")
   "How the username is translated before being hashed.  Useful values
include %Ln if user can log in with or without @@domain, %Ld if mailboxes
are shared within domain.")

;;; Log destination.

  (log-path
   (string "syslog")
   "Log file to use for error messages.  @samp{syslog} logs to syslog,
@samp{/dev/stderr} logs to stderr.")

  (info-log-path
   (string "")
   "Log file to use for informational messages.  Defaults to
@samp{log-path}.")

  (debug-log-path
   (string "")
   "Log file to use for debug messages.  Defaults to
@samp{info-log-path}.")

  (syslog-facility
   (string "mail")
   "Syslog facility to use if you're logging to syslog.  Usually if you
don't want to use @samp{mail}, you'll use local0..local7.  Also other
standard facilities are supported.")

  (auth-verbose?
   (boolean #f)
   "Log unsuccessful authentication attempts and the reasons why they
failed.")

  (auth-verbose-passwords
   (string "no")
   "In case of password mismatches, log the attempted password.  Valid
values are no, plain and sha1.  sha1 can be useful for detecting brute
force password attempts vs.  user simply trying the same password over
and over again.  You can also truncate the value to n chars by appending
\":n\" (e.g. sha1:6).")

  (auth-debug?
   (boolean #f)
   "Even more verbose logging for debugging purposes.  Shows for example
SQL queries.")

  (auth-debug-passwords?
   (boolean #f)
   "In case of password mismatches, log the passwords and used scheme so
the problem can be debugged.  Enabling this also enables
@samp{auth-debug}.")

  (mail-debug?
   (boolean #f)
   "Enable mail process debugging.  This can help you figure out why
Dovecot isn't finding your mails.")

  (verbose-ssl?
   (boolean #f)
   "Show protocol level SSL errors.")

  (log-timestamp
   (string "\"%b %d %H:%M:%S \"")
   "Prefix for each line written to log file.  % codes are in
strftime(3) format.")

  (login-log-format-elements
   (space-separated-string-list
    '("user=<%u>" "method=%m" "rip=%r" "lip=%l" "mpid=%e" "%c"))
   "List of elements we want to log.  The elements which have a
non-empty variable value are joined together to form a comma-separated
string.")

  (login-log-format
   (string "%$: %s")
   "Login log format.  %s contains @samp{login-log-format-elements}
string, %$ contains the data we want to log.")

  (mail-log-prefix
   (string "\"%s(%u)<%{pid}><%{session}>: \"")
   "Log prefix for mail processes.  See doc/wiki/Variables.txt for list
of possible variables you can use.")

  (deliver-log-format
   (string "msgid=%m: %$")
   "Format to use for logging mail deliveries.  You can use variables:
@table @code
@item %$
Delivery status message (e.g. @samp{saved to INBOX})
@item %m
Message-ID
@item %s
Subject
@item %f
From address
@item %p
Physical size
@item %w
Virtual size.
@end table")

;;; Mailbox locations and namespaces

  (mail-location
   (string "")
   "Location for users' mailboxes.  The default is empty, which means
that Dovecot tries to find the mailboxes automatically.  This won't work
if the user doesn't yet have any mail, so you should explicitly tell
Dovecot the full location.

If you're using mbox, giving a path to the INBOX
file (e.g. /var/mail/%u) isn't enough.  You'll also need to tell Dovecot
where the other mailboxes are kept.  This is called the \"root mail
directory\", and it must be the first path given in the
@samp{mail-location} setting.

There are a few special variables you can use, eg.:

@table @samp
@item %u
username
@item %n
user part in user@@domain, same as %u if there's no domain
@item %d
domain part in user@@domain, empty if there's no domain
@item %h
home director
@end table

See doc/wiki/Variables.txt for full list.  Some examples:
@table @samp
@item maildir:~/Maildir
@item mbox:~/mail:INBOX=/var/mail/%u
@item mbox:/var/mail/%d/%1n/%n:INDEX=/var/indexes/%d/%1n/%
@end table")

  (mail-uid
   (string "")
   "System user and group used to access mails.  If you use multiple,
userdb can override these by returning uid or gid fields.  You can use
either numbers or names.  <doc/wiki/UserIds.txt>.")

  (mail-gid
   (string "")
   "")

  (mail-privileged-group
   (string "")
   "Group to enable temporarily for privileged operations.  Currently
this is used only with INBOX when either its initial creation or
dotlocking fails.  Typically this is set to \"mail\" to give access to
/var/mail.")

  (mail-access-groups
   (string "")
   "Grant access to these supplementary groups for mail processes.
Typically these are used to set up access to shared mailboxes.  Note
that it may be dangerous to set these if users can create
symlinks (e.g. if \"mail\" group is set here, ln -s /var/mail ~/mail/var
could allow a user to delete others' mailboxes, or ln -s
/secret/shared/box ~/mail/mybox would allow reading it).")

  (mail-full-filesystem-access?
   (boolean #f)
   "Allow full file system access to clients.  There's no access checks
other than what the operating system does for the active UID/GID.  It
works with both maildir and mboxes, allowing you to prefix mailboxes
names with e.g. /path/ or ~user/.")

;;; Mail processes

  (mmap-disable?
   (boolean #f)
   "Don't use mmap() at all.  This is required if you store indexes to
shared file systems (NFS or clustered file system).")

  (dotlock-use-excl?
   (boolean #t)
   "Rely on @samp{O_EXCL} to work when creating dotlock files.  NFS
supports @samp{O_EXCL} since version 3, so this should be safe to use
nowadays by default.")

  (mail-fsync
   (string "optimized")
   "When to use fsync() or fdatasync() calls:
@table @code
@item optimized
Whenever necessary to avoid losing important data
@item always
Useful with e.g. NFS when write()s are delayed
@item never
Never use it (best performance, but crashes can lose data).
@end table")

  (mail-nfs-storage?
   (boolean #f)
   "Mail storage exists in NFS.  Set this to yes to make Dovecot flush
NFS caches whenever needed.  If you're using only a single mail server
this isn't needed.")

  (mail-nfs-index?
   (boolean #f)
   "Mail index files also exist in NFS.  Setting this to yes requires
@samp{mmap-disable? #t} and @samp{fsync-disable? #f}.")

  (lock-method
   (string "fcntl")
   "Locking method for index files.  Alternatives are fcntl, flock and
dotlock.  Dotlocking uses some tricks which may create more disk I/O
than other locking methods.  NFS users: flock doesn't work, remember to
change @samp{mmap-disable}.")

  (mail-temp-dir
   (file-name "/tmp")
   "Directory in which LDA/LMTP temporarily stores incoming mails >128
kB.")

  (first-valid-uid
   (non-negative-integer 500)
   "Valid UID range for users.  This is mostly to make sure that users can't
log in as daemons or other system users.  Note that denying root logins is
hardcoded to dovecot binary and can't be done even if @samp{first-valid-uid}
is set to 0.")

  (last-valid-uid
   (non-negative-integer 0)
   "")

  (first-valid-gid
   (non-negative-integer 1)
   "Valid GID range for users.  Users having non-valid GID as primary group ID
aren't allowed to log in.  If user belongs to supplementary groups with
non-valid GIDs, those groups are not set.")

  (last-valid-gid
   (non-negative-integer 0)
   "")

  (mail-max-keyword-length
   (non-negative-integer 50)
   "Maximum allowed length for mail keyword name.  It's only forced when
trying to create new keywords.")

  (valid-chroot-dirs
   (colon-separated-file-name-list '())
   "List of directories under which chrooting is allowed for mail
processes (i.e. /var/mail will allow chrooting to /var/mail/foo/bar
too).  This setting doesn't affect @samp{login-chroot}
@samp{mail-chroot} or auth chroot settings.  If this setting is empty,
\"/./\" in home dirs are ignored.  WARNING: Never add directories here
which local users can modify, that may lead to root exploit.  Usually
this should be done only if you don't allow shell access for users.
<doc/wiki/Chrooting.txt>.")

  (mail-chroot
   (string "")
   "Default chroot directory for mail processes.  This can be overridden
for specific users in user database by giving /./ in user's home
directory (e.g. /home/./user chroots into /home).  Note that usually
there is no real need to do chrooting, Dovecot doesn't allow users to
access files outside their mail directory anyway.  If your home
directories are prefixed with the chroot directory, append \"/.\" to
@samp{mail-chroot}.  <doc/wiki/Chrooting.txt>.")

  (auth-socket-path
   (file-name "/var/run/dovecot/auth-userdb")
   "UNIX socket path to master authentication server to find users.
This is used by imap (for shared users) and lda.")

  (mail-plugin-dir
   (file-name "/usr/lib/dovecot")
   "Directory where to look up mail plugins.")

  (mail-plugins
   (space-separated-string-list '())
   "List of plugins to load for all services.  Plugins specific to IMAP,
LDA, etc. are added to this list in their own .conf files.")


  (mail-cache-min-mail-count
   (non-negative-integer 0)
   "The minimum number of mails in a mailbox before updates are done to
cache file.  This allows optimizing Dovecot's behavior to do less disk
writes at the cost of more disk reads.")

  (mailbox-idle-check-interval
   (string "30 secs")
   "When IDLE command is running, mailbox is checked once in a while to
see if there are any new mails or other changes.  This setting defines
the minimum time to wait between those checks.  Dovecot can also use
dnotify, inotify and kqueue to find out immediately when changes
occur.")

  (mail-save-crlf?
   (boolean #f)
   "Save mails with CR+LF instead of plain LF.  This makes sending those
mails take less CPU, especially with sendfile() syscall with Linux and
FreeBSD.  But it also creates a bit more disk I/O which may just make it
slower.  Also note that if other software reads the mboxes/maildirs,
they may handle the extra CRs wrong and cause problems.")

  (maildir-stat-dirs?
   (boolean #f)
   "By default LIST command returns all entries in maildir beginning
with a dot.  Enabling this option makes Dovecot return only entries
which are directories.  This is done by stat()ing each entry, so it
causes more disk I/O.
 (For systems setting struct @samp{dirent->d_type} this check is free
and it's done always regardless of this setting).")

  (maildir-copy-with-hardlinks?
   (boolean #t)
   "When copying a message, do it with hard links whenever possible.
This makes the performance much better, and it's unlikely to have any
side effects.")

  (maildir-very-dirty-syncs?
   (boolean #f)
   "Assume Dovecot is the only MUA accessing Maildir: Scan cur/
directory only when its mtime changes unexpectedly or when we can't find
the mail otherwise.")

  (mbox-read-locks
   (space-separated-string-list '("fcntl"))
   "Which locking methods to use for locking mbox.  There are four
available:

@table @code
@item dotlock
Create <mailbox>.lock file.  This is the oldest and most NFS-safe
solution.  If you want to use /var/mail/ like directory, the users will
need write access to that directory.
@item dotlock-try
Same as dotlock, but if it fails because of permissions or because there
isn't enough disk space, just skip it.
@item fcntl
Use this if possible.  Works with NFS too if lockd is used.
@item flock
May not exist in all systems.  Doesn't work with NFS. 
@item lockf
May not exist in all systems.  Doesn't work with NFS.
@end table

You can use multiple locking methods; if you do the order they're declared
in is important to avoid deadlocks if other MTAs/MUAs are using multiple
locking methods as well.  Some operating systems don't allow using some of
them simultaneously.")

  (mbox-write-locks
   (space-separated-string-list '("dotlock" "fcntl"))
   "")

  (mbox-lock-timeout
   (string "5 mins")
   "Maximum time to wait for lock (all of them) before aborting.")

  (mbox-dotlock-change-timeout
   (string "2 mins")
   "If dotlock exists but the mailbox isn't modified in any way,
override the lock file after this much time.")

  (mbox-dirty-syncs?
   (boolean #t)
   "When mbox changes unexpectedly we have to fully read it to find out
what changed.  If the mbox is large this can take a long time.  Since
the change is usually just a newly appended mail, it'd be faster to
simply read the new mails.  If this setting is enabled, Dovecot does
this but still safely fallbacks to re-reading the whole mbox file
whenever something in mbox isn't how it's expected to be.  The only real
downside to this setting is that if some other MUA changes message
flags, Dovecot doesn't notice it immediately.  Note that a full sync is
done with SELECT, EXAMINE, EXPUNGE and CHECK commands.")

  (mbox-very-dirty-syncs?
   (boolean #f)
   "Like @samp{mbox-dirty-syncs}, but don't do full syncs even with SELECT,
EXAMINE, EXPUNGE or CHECK commands.  If this is set,
@samp{mbox-dirty-syncs} is ignored.")

  (mbox-lazy-writes?
   (boolean #t)
   "Delay writing mbox headers until doing a full write sync (EXPUNGE
and CHECK commands and when closing the mailbox).  This is especially
useful for POP3 where clients often delete all mails.  The downside is
that our changes aren't immediately visible to other MUAs.")

  (mbox-min-index-size
   (non-negative-integer 0)
   "If mbox size is smaller than this (e.g. 100k), don't write index
files.  If an index file already exists it's still read, just not
updated.")

  (mdbox-rotate-size
   (non-negative-integer #e10e6)
   "Maximum dbox file size until it's rotated.")

  (mdbox-rotate-interval
   (string "1d")
   "Maximum dbox file age until it's rotated.  Typically in days.  Day
begins from midnight, so 1d = today, 2d = yesterday, etc.  0 = check
disabled.")

  (mdbox-preallocate-space?
   (boolean #f)
   "When creating new mdbox files, immediately preallocate their size to
@samp{mdbox-rotate-size}.  This setting currently works only in Linux
with some file systems (ext4, xfs).")

  (mail-attribute-dict
   (string "")
   "The location of a dictionary used to store @code{IMAP METADATA}
as defined by @uref{https://tools.ietf.org/html/rfc5464, RFC@tie{}5464}.

The IMAP METADATA commands are available only if the ``imap''
protocol configuration's @code{imap-metadata?} field is @samp{#t}.")

  (mail-attachment-dir
   (string "")
   "sdbox and mdbox support saving mail attachments to external files,
which also allows single instance storage for them.  Other backends
don't support this for now.

WARNING: This feature hasn't been tested much yet.  Use at your own risk.

Directory root where to store mail attachments.  Disabled, if empty.")

  (mail-attachment-min-size
   (non-negative-integer #e128e3)
   "Attachments smaller than this aren't saved externally.  It's also
possible to write a plugin to disable saving specific attachments
externally.")

  (mail-attachment-fs
   (string "sis posix")
   "File system backend to use for saving attachments:
@table @code
@item posix
No SiS done by Dovecot (but this might help FS's own deduplication)
@item sis posix
SiS with immediate byte-by-byte comparison during saving
@item sis-queue posix
SiS with delayed comparison and deduplication.
@end table")

  (mail-attachment-hash
   (string "%{sha1}")
   "Hash format to use in attachment filenames.  You can add any text and
variables: @code{%@{md4@}}, @code{%@{md5@}}, @code{%@{sha1@}},
@code{%@{sha256@}}, @code{%@{sha512@}}, @code{%@{size@}}.  Variables can be
truncated, e.g. @code{%@{sha256:80@}} returns only first 80 bits.")

  (default-process-limit
    (non-negative-integer 100)
    "")

  (default-client-limit
    (non-negative-integer 1000)
    "")

  (default-vsz-limit
    (non-negative-integer #e256e6)
    "Default VSZ (virtual memory size) limit for service processes.
This is mainly intended to catch and kill processes that leak memory
before they eat up everything.")

  (default-login-user
    (string "dovenull")
    "Login user is internally used by login processes.  This is the most
untrusted user in Dovecot system.  It shouldn't have access to anything
at all.")

  (default-internal-user
    (string "dovecot")
    "Internal user is used by unprivileged processes.  It should be
separate from login user, so that login processes can't disturb other
processes.")

  (ssl?
   (string "required")
   "SSL/TLS support: yes, no, required.  <doc/wiki/SSL.txt>.")

  (ssl-cert
   (string "</etc/dovecot/default.pem")
   "PEM encoded X.509 SSL/TLS certificate (public key).")

  (ssl-key
   (string "</etc/dovecot/private/default.pem")
   "PEM encoded SSL/TLS private key.  The key is opened before
dropping root privileges, so keep the key file unreadable by anyone but
root.")

  (ssl-key-password
   (string "")
   "If key file is password protected, give the password here.
Alternatively give it when starting dovecot with -p parameter.  Since
this file is often world-readable, you may want to place this setting
instead to a different.")

  (ssl-ca
   (string "")
   "PEM encoded trusted certificate authority.  Set this only if you
intend to use @samp{ssl-verify-client-cert? #t}.  The file should
contain the CA certificate(s) followed by the matching
CRL(s).  (e.g. @samp{ssl-ca </etc/ssl/certs/ca.pem}).")
  (ssl-require-crl?
   (boolean #t)
   "Require that CRL check succeeds for client certificates.")
  (ssl-verify-client-cert?
   (boolean #f)
   "Request client to send a certificate.  If you also want to require
it, set @samp{auth-ssl-require-client-cert? #t} in auth section.")

  (ssl-cert-username-field
   (string "commonName")
   "Which field from certificate to use for username.  commonName and
x500UniqueIdentifier are the usual choices.  You'll also need to set
@samp{auth-ssl-username-from-cert? #t}.")

  (ssl-min-protocol
   (string "TLSv1")
   "Minimum SSL protocol version to accept.")

  (ssl-cipher-list
   (string "ALL:!kRSA:!SRP:!kDHd:!DSS:!aNULL:!eNULL:!EXPORT:!DES:!3DES:!MD5:!PSK:!RC4:!ADH:!LOW@STRENGTH")
   "SSL ciphers to use.")

  (ssl-crypto-device
   (string "")
   "SSL crypto device to use, for valid values run \"openssl engine\".")

  (postmaster-address
   (string "postmaster@%d")
   "Address to use when sending rejection mails.
Default is postmaster@@<your domain>.  %d expands to recipient domain.")

  (hostname
   (string "")
   "Hostname to use in various parts of sent mails (e.g. in Message-Id)
and in LMTP replies.  Default is the system's real hostname@@domain.")

  (quota-full-tempfail?
   (boolean #f)
   "If user is over quota, return with temporary failure instead of
bouncing the mail.")

  (sendmail-path
   (file-name "/usr/sbin/sendmail")
   "Binary to use for sending mails.")

  (submission-host
   (string "")
   "If non-empty, send mails via this SMTP host[:port] instead of
sendmail.")

  (rejection-subject
   (string "Rejected: %s")
   "Subject: header to use for rejection mails.  You can use the same
variables as for @samp{rejection-reason} below.")

  (rejection-reason
   (string "Your message to <%t> was automatically rejected:%n%r")
   "Human readable error message for rejection mails.  You can use
variables:

@table @code
@item %n
CRLF
@item %r
reason
@item %s
original subject
@item %t
recipient
@end table")

  (recipient-delimiter
   (string "+")
   "Delimiter character between local-part and detail in email
address.")

  (lda-original-recipient-header
   (string "")
   "Header where the original recipient address (SMTP's RCPT TO:
address) is taken from if not available elsewhere.  With dovecot-lda -a
parameter overrides this.  A commonly used header for this is
X-Original-To.")

  (lda-mailbox-autocreate?
   (boolean #f)
   "Should saving a mail to a nonexistent mailbox automatically create
it?.")

  (lda-mailbox-autosubscribe?
   (boolean #f)
   "Should automatically created mailboxes be also automatically
subscribed?.")


  (imap-max-line-length
   (non-negative-integer #e64e3)
   "Maximum IMAP command line length.  Some clients generate very long
command lines with huge mailboxes, so you may need to raise this if you
get \"Too long argument\" or \"IMAP command line too large\" errors
often.")

  (imap-logout-format
   (string "in=%i out=%o deleted=%{deleted} expunged=%{expunged} trashed=%{trashed} hdr_count=%{fetch_hdr_count} hdr_bytes=%{fetch_hdr_bytes} body_count=%{fetch_body_count} body_bytes=%{fetch_body_bytes}")
   "IMAP logout format string:
@table @code
@item %i
total number of bytes read from client
@item %o
total number of bytes sent to client.
@end table
See @file{doc/wiki/Variables.txt} for a list of all the variables you can use.")

  (imap-capability
   (string "")
   "Override the IMAP CAPABILITY response.  If the value begins with '+',
add the given capabilities on top of the defaults (e.g. +XFOO XBAR).")

  (imap-idle-notify-interval
   (string "2 mins")
   "How long to wait between \"OK Still here\" notifications when client
is IDLEing.")

  (imap-id-send
   (string "")
   "ID field names and values to send to clients.  Using * as the value
makes Dovecot use the default value.  The following fields have default
values currently: name, version, os, os-version, support-url,
support-email.")

  (imap-id-log
   (string "")
   "ID fields sent by client to log.  * means everything.")

  (imap-client-workarounds
   (space-separated-string-list '())
   "Workarounds for various client bugs:

@table @code
@item delay-newmail
Send EXISTS/RECENT new mail notifications only when replying to NOOP and
CHECK commands.  Some clients ignore them otherwise, for example OSX
Mail (<v2.1).  Outlook Express breaks more badly though, without this it
may show user \"Message no longer in server\" errors.  Note that OE6
still breaks even with this workaround if synchronization is set to
\"Headers Only\".

@item tb-extra-mailbox-sep
Thunderbird gets somehow confused with LAYOUT=fs (mbox and dbox) and
adds extra @samp{/} suffixes to mailbox names.  This option causes Dovecot to
ignore the extra @samp{/} instead of treating it as invalid mailbox name.

@item tb-lsub-flags
Show \\Noselect flags for LSUB replies with LAYOUT=fs (e.g. mbox).
This makes Thunderbird realize they aren't selectable and show them
greyed out, instead of only later giving \"not selectable\" popup error.
@end table
")

  (imap-urlauth-host
   (string "")
   "Host allowed in URLAUTH URLs sent by client.  \"*\" allows all.")

  (protocols
   (protocol-configuration-list
    (list (protocol-configuration
           (name "imap"))))
   "List of protocols we want to serve.  Available protocols include
@samp{imap}, @samp{pop3}, and @samp{lmtp}.")

  (services
   (service-configuration-list
    (list
     (service-configuration
      (kind "imap-login")
      (client-limit 0)
      (process-limit 0)
      (listeners
       (list
        (inet-listener-configuration (protocol "imap") (port 143) (ssl? #f))
        (inet-listener-configuration (protocol "imaps") (port 993) (ssl? #t)))))
     (service-configuration
      (kind "pop3-login")
      (listeners
       (list
        (inet-listener-configuration (protocol "pop3") (port 110) (ssl? #f))
        (inet-listener-configuration (protocol "pop3s") (port 995) (ssl? #t)))))
     (service-configuration
      (kind "lmtp")
      (client-limit 1)
      (process-limit 0)
      (listeners
       (list (unix-listener-configuration (path "lmtp") (mode "0666")))))
     (service-configuration
      (kind "imap")
      (client-limit 1)
      (process-limit 1024))
     (service-configuration
      (kind "pop3")
      (client-limit 1)
      (process-limit 1024))
     (service-configuration
      (kind "auth")
      (service-count 0)
      (client-limit 0)
      (process-limit 1)
      (listeners
       (list (unix-listener-configuration (path "auth-userdb")))))
     (service-configuration
      (kind "auth-worker")
      (client-limit 1)
      (process-limit 0))
     (service-configuration
      (kind "dict")
      (client-limit 1)
      (process-limit 0)
      (listeners (list (unix-listener-configuration (path "dict")))))))
   "List of services to enable.  Available services include @samp{imap},
@samp{imap-login}, @samp{pop3}, @samp{pop3-login}, @samp{auth}, and
@samp{lmtp}."))

(define-configuration opaque-dovecot-configuration
  (dovecot
   (file-like dovecot)
   "The dovecot package.")

  (string
   (string (configuration-missing-field 'opaque-dovecot-configuration
                                        'string))
   "The contents of the @code{dovecot.conf} to use."))

(define %dovecot-accounts
  ;; Account and group for the Dovecot daemon.
  (list (user-group (name "dovecot") (system? #t))
        (user-account
         (name "dovecot")
         (group "dovecot")
         (system? #t)
         (comment "Dovecot daemon user")
         (home-directory "/var/empty")
         (shell (file-append shadow "/sbin/nologin")))

        (user-group (name "dovenull") (system? #t))
        (user-account
         (name "dovenull")
         (group "dovenull")
         (system? #t)
         (comment "Dovecot daemon login user")
         (home-directory "/var/empty")
         (shell (file-append shadow "/sbin/nologin")))))

(define (%dovecot-activation config)
  ;; Activation gexp.
  (let ((config-str
         (cond
          ((opaque-dovecot-configuration? config)
           (opaque-dovecot-configuration-string config))
          (else
           (with-output-to-string
             (lambda ()
               (serialize-configuration config
                                        dovecot-configuration-fields)))))))
    #~(begin
        (use-modules (guix build utils))
        (define (mkdir-p/perms directory owner perms)
          (mkdir-p directory)
          (chown "/var/run/dovecot" (passwd:uid owner) (passwd:gid owner))
          (chmod directory perms))
        (define (build-subject parameters)
          (string-concatenate
           (map (lambda (pair)
                  (let ((k (car pair)) (v (cdr pair)))
                    (define (escape-char str chr)
                      (string-join (string-split str chr) (string #\\ chr)))
                    (string-append "/" k "="
                                   (escape-char (escape-char v #\=) #\/))))
                (filter (lambda (pair) (cdr pair)) parameters))))
        (define* (create-self-signed-certificate-if-absent
                  #:key private-key public-key (owner (getpwnam "root"))
                  (common-name (gethostname))
                  (organization-name "Guix")
                  (organization-unit-name "Default Self-Signed Certificate")
                  (subject-parameters `(("CN" . ,common-name)
                                        ("O" . ,organization-name)
                                        ("OU" . ,organization-unit-name)))
                  (subject (build-subject subject-parameters)))
          ;; Note that by default, OpenSSL outputs keys in PEM format.  This
          ;; is what we want.
          (unless (file-exists? private-key)
            (cond
             ((zero? (system* (string-append #$openssl "/bin/openssl")
                              "genrsa" "-out" private-key "2048"))
              (chown private-key (passwd:uid owner) (passwd:gid owner))
              (chmod private-key #o400))
             (else
              (format (current-error-port)
                      "Failed to create private key at ~a.\n" private-key))))
          (unless (file-exists? public-key)
            (cond
             ((zero? (system* (string-append #$openssl "/bin/openssl")
                              "req" "-new" "-x509" "-key" private-key
                              "-out" public-key "-days" "3650"
                              "-batch" "-subj" subject))
              (chown public-key (passwd:uid owner) (passwd:gid owner))
              (chmod public-key #o444))
             (else
              (format (current-error-port)
                      "Failed to create public key at ~a.\n" public-key)))))
        (let ((user (getpwnam "dovecot")))
          (mkdir-p/perms "/var/run/dovecot" user #o755)
          (mkdir-p/perms "/var/lib/dovecot" user #o755)
          (mkdir-p/perms "/etc/dovecot" user #o755)
          (copy-file #$(plain-file "dovecot.conf" config-str)
                     "/etc/dovecot/dovecot.conf")
          (mkdir-p/perms "/etc/dovecot/private" user #o700)
          (create-self-signed-certificate-if-absent
           #:private-key "/etc/dovecot/private/default.pem"
           #:public-key "/etc/dovecot/default.pem"
           #:owner (getpwnam "root")
           #:common-name (format #f "Dovecot service on ~a" (gethostname)))))))

(define (dovecot-shepherd-service config)
  "Return a list of <shepherd-service> for CONFIG."
  (let ((dovecot (if (opaque-dovecot-configuration? config)
                     (opaque-dovecot-configuration-dovecot config)
                     (dovecot-configuration-dovecot config))))
    (list (shepherd-service
           (documentation "Run the Dovecot POP3/IMAP mail server.")
           (provision '(dovecot))
           (requirement '(networking))
           (start #~(make-forkexec-constructor
                     (list (string-append #$dovecot "/sbin/dovecot")
                           "-F")))
           (stop #~(lambda _
                     (invoke #$(file-append dovecot "/sbin/dovecot")
                             "stop")
                     #f))))))

(define %dovecot-pam-services
  (list (unix-pam-service "dovecot")))

(define dovecot-service-type
  (service-type (name 'dovecot)
                (extensions
                 (list (service-extension shepherd-root-service-type
                                          dovecot-shepherd-service)
                       (service-extension account-service-type
                                          (const %dovecot-accounts))
                       (service-extension pam-root-service-type
                                          (const %dovecot-pam-services))
                       (service-extension activation-service-type
                                          %dovecot-activation)))
                (description "Run Dovecot, a mail server that can run POP3,
IMAP, and LMTP.")))

(define* (dovecot-service #:key (config (dovecot-configuration)))
  "Return a service that runs @command{dovecot}, a mail server that can run
POP3, IMAP, and LMTP.  @var{config} should be a configuration object created
by @code{dovecot-configuration}.  @var{config} may also be created by
@code{opaque-dovecot-configuration}, which allows specification of the
@code{dovecot.conf} as a string."
  (validate-configuration config
                          (if (opaque-dovecot-configuration? config)
                              opaque-dovecot-configuration-fields
                              dovecot-configuration-fields))
  (service dovecot-service-type config))

;; A little helper to make it easier to document all those fields.
(define (generate-dovecot-documentation)
  (generate-documentation
    `((dovecot-configuration
       ,dovecot-configuration-fields
       (dict dict-configuration)
       (namespaces namespace-configuration)
       (plugin plugin-configuration)
       (passdbs passdb-configuration)
       (userdbs userdb-configuration)
       (services service-configuration)
       (protocols protocol-configuration))
      (dict-configuration ,dict-configuration-fields)
      (plugin-configuration ,plugin-configuration-fields)
      (passdb-configuration ,passdb-configuration-fields)
      (userdb-configuration ,userdb-configuration-fields)
      (unix-listener-configuration ,unix-listener-configuration-fields)
      (fifo-listener-configuration ,fifo-listener-configuration-fields)
      (inet-listener-configuration ,inet-listener-configuration-fields)
      (namespace-configuration
       ,namespace-configuration-fields
       (mailboxes mailbox-configuration))
      (mailbox-configuration ,mailbox-configuration-fields)
      (service-configuration
       ,service-configuration-fields
       (listeners unix-listener-configuration fifo-listener-configuration
                  inet-listener-configuration))
      (protocol-configuration ,protocol-configuration-fields))
  'dovecot-configuration))

\f
;;;
;;; OpenSMTPD.
;;;

;; some fieldnames have a default value of #f, which is ok.  They cannot have a value of #t.
;; for example opensmtpd-table-configuration-data can be #f, BUT NOT true.
;; my/sanitize procedure tests values to see if they are of the right kind.
;; procedure false? is needed to allow fields like 'values' to be blank, (empty), or #f BUT also
;; have a value like a list of strings.
(define (false? var)
  (eq? #f var))

;; this procedure takes in a var and a list of procedures.  It loops through list of procedures passing in var to each.
;; if one procedure returns #t, the function returns true.  Otherwise #f.
;; TODO for fun rewrite this using map
;; If I rewrote it in map, then it may help with sanitizing.
;; eg: I could then potentially easily sanitize vars with lambda procedures.
(define (is-value-right-type? var list-of-procedures record fieldname)
  (if (null? list-of-procedures)
        #f
        (cond [(procedure? (car list-of-procedures))
               (if ((car list-of-procedures) var)
                   #t
                   (is-value-right-type? var (cdr list-of-procedures) record fieldname))]
              [(and (sanitize-configuration? (car list-of-procedures))
                    (sanitize-configuration-error-if-proc-fails (car list-of-procedures))
                    (if ((sanitize-configuration-proc (car list-of-procedures)) var)
                        #t
                        (begin
                          (apply string-append
                                 (sanitize-configuration-error-message (car list-of-procedures)))
                          (throw 'bad! var))))]
              [else (if ((sanitize-configuration-proc (car list-of-procedures)) var)
                        #t
                        (is-value-right-type? var (cdr list-of-procedures) record fieldname))])))

;; converts strings like this:
;; "apple, ham, cherry" -> "apple, ham, or cherry"
;; "pineapple" -> "pinneapple".
;; "cheese, grapefruit, or jam" -> "cheese, grapefruit, or jam"
(define (add-comma-or string)
  (define last-comma-location (string-rindex string #\,))
  (if last-comma-location
      (if (string-contains string ", or" last-comma-location)
          string
          (string-replace string ", or" last-comma-location
                          (+ 1 last-comma-location)))
      string))

;; I could test for read-ability of a file, but then I would have to
;; test the program as root everytime instead of as a normal user...
(define (file-exists? file)
(if (string? file)
    (access? file F_OK)
    #f))

(define (list-of-procedures->string procedures)
  (define string
    (let loop ([procedures procedures])
      (if (null? procedures)
          ""
          (begin
            (string-append
             (cond [(eq? false? (car procedures))
                    "#f , "]
                   [(eq? boolean? (car procedures))
                    "boolean, "]
                   [(eq? string? (car procedures))
                    "string, "]
                   [(eq? integer? (car procedures))
                    "integer, "]
                   [(eq? list-of-strings? (car procedures))
                    "list of strings, "]
                   [(eq? assoc-list? (car procedures))
                    "an association list, "]
                   [(eq? opensmtpd-pki-configuration? (car procedures))
                    "an <opensmtpd-pki-configuration> record, "]
                   [(eq? opensmtpd-table-configuration? (car procedures))
                    "an <opensmtpd-table-configuration> record, "]
                   [(eq? list-of-unique-opensmtpd-match-configuration? (car procedures))
                    "a list of unique <opensmtpd-match-configuration> records, "]
                   [(eq? table-whose-data-are-assoc-list? (car procedures))
                    (string-append
                    "an <opensmtpd-table-configuration> record whose fieldname 'values' are an assoc-list \n"
                    "(eg: (opensmtpd-table-configuration (name \"table\") (data '(\"joshua\" . \"$encrypted$password\")))), ")]
                   [(eq? file-exists? (car procedures))
                    "file, "]
                   [else "has an incorrect value, "])
             (loop (cdr procedures)))))))
  (add-comma-or (string-append (string-drop-right string 2) ".\n")))

;; TODO can I M-x raise-sexp (string=? string var) in this procedure? and get rid of checking
;; if the var is a string?  The previous string-in-list? had that check.
;; (string-in-list? '("hello" 5 "cat")) currently works.  If I M-x raise-sexp (string=? string var)
;; then it will no longer work.
(define (string-in-list? string list)
  (primitive-eval (cons 'or (map (lambda (var) (and (string? var) (string=? string var))) list))))

(define (my/sanitize var record fieldname list-of-procedures)
  (if (is-value-right-type? var list-of-procedures record fieldname)
      var
      (begin
        (display (string-append "<" record "> fieldname: '" fieldname "' is of type "
                                (list-of-procedures->string list-of-procedures) "\n"))
        (throw 'bad! var))))

;; Some example opensmtpd-table-configurations:
;;
;;  (opensmtpd-table-configuration (name "root accounts") (data '(("joshua" . "root@dismail.de") ("joshua" . "postmaster@dismail.de"))))
;;  (opensmtpd-table-configuration (name "root accounts") (data (list "mysite.me" "your-site.com")))
;;  TODO should <opensmtpd-table-configuration> support have a fieldname 'file'?
;;  Or should I change name to name-or-file ?
(define-record-type* <opensmtpd-table-configuration>
  opensmtpd-table-configuration make-opensmtpd-table-configuration
  opensmtpd-table-configuration?
  this-record
  (name opensmtpd-table-configuration-name ;; string
        (default #f)
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-table-configuration" "name" (list string?)))))
  (file-db opensmtpd-table-configuration-file-db
           (default #f)
           (sanitize (lambda (var)
                       (my/sanitize var "opensmtpd-table-configuration" "file-db"
                                    (list boolean?)))))
  ;; FIXME support an aliasing table as described here:
  ;; https://man.openbsd.org/table.5
  ;; One may have to use the record file for this.  I don't think tables support a table like this:
  ;; table "name" { joshua = joshua@gnucode.me,joshua@gnu-hurd.com,joshua@propernaming.org, root = root@gnucode.me }
  ;; If values is an absolute filename, then it will use said filename to house the table info.
  ;; filename must be an absolute filename.
  (data opensmtpd-table-configuration-data
          (default #f)
          (sanitize (lambda (var)
                      (my/sanitize var "opensmtpd-table-configuration" "values"
                                   (list file-exists? list-of-strings? assoc-list?)))))
  ;; is a list of values or key values
  ;; eg: (list "mysite.me" "your-site.com")
  ;; eg: (list ("joshua" . "joshua@gnu.org") ("james" . "james@gnu.org"))
  ;; I am currently making these values be as assocation list of strings only.
  ;; FIXME should I allow a var like this?
  ;; (list (cons "gnucode.me" 234.949.392.23))
  ;; can be of type: (quote list-of-strings) or (quote assoc-list)
  ;; (opensmtpd-table-configuration-type record) returns the values' type.  The user SHOULD NEVER set the type.
  ;; TODO jpoiret: on irc reccomends that I just use an outside function to determine fieldname 'values', type.
  ;; it would be "simpler" and possibly easier for the next person working on this code to understand what is happening.
  (type opensmtpd-table-configuration-type
        (default #f)
        (thunked)
        (sanitize (lambda (var)
                    (cond [(opensmtpd-table-configuration-data this-record)
                           (if (list-of-strings? (opensmtpd-table-configuration-data this-record))
                               (quote list-of-strings)
                               (quote assoc-list))]
                          [(file-exists? (opensmtpd-table-configuration-data this-record))
                           (if (opensmtpd-table-configuration-file-db this-record)
                               (quote db)
                               (quote file))]
                          [else
                           (display "opensmtpd-table-configuration-type is broke\n")
                           (throw 'bad! var)])))))

(define-record-type* <opensmtpd-ca-configuration>
  opensmtpd-ca-configuration make-opensmtpd-ca-configuration
  opensmtpd-ca-configuration?
  (name opensmtpd-ca-configuration-name
        (default #f)
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-ca-configuration" "name" (list string?)))))
  (file opensmtpd-ca-configuration-file
        (default #f)
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-ca-configuration" "file" (list file-exists?))))))

(define-record-type* <opensmtpd-pki-configuration>
  opensmtpd-pki-configuration make-opensmtpd-pki-configuration
  opensmtpd-pki-configuration?
  (domain opensmtpd-pki-configuration-domain
          (default #f)
          (sanitize (lambda (var)
                      (my/sanitize var "opensmtpd-pki-configuration" "domain" (list string?)))))
  ;; TODO/FIXME this should probably be a list of files.  The opensmtpd documentation says
  ;; that you could have a list of files:
  ;;
  ;; pki pkiname cert certfile
  ;; Associate certificate file certfile with host pkiname, and use that file to prove
  ;; the identity of the mail server to clients.  pkiname is the server's name, de‐
  ;; rived from the default hostname or set using either
  ;; /gnu/store/2d13sdz76ldq8zgwv4wif0zx7hkr3mh2-opensmtpd-6.8.0p2/etc/mailname or us‐
  ;; ing the hostname directive.  If a fallback certificate or SNI is wanted, the ‘*’
  ;; wildcard may be used as pkiname.

  ;; A certificate chain may be created by appending one or many certificates, includ‐
  ;; ing a Certificate Authority certificate, to certfile.  The creation of certifi‐
  ;; cates is documented in starttls(8).
  (cert opensmtpd-pki-configuration-cert
        (default #f)
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-pki-configuration" "cert" (list file-exists?)))))
  (key opensmtpd-pki-configuration-key
       (default #f)
       (sanitize (lambda (var)
                   (my/sanitize var "opensmtpd-pki-configuration" "key" (list file-exists?)))))
  ; todo sanitize this. valid parameters are "none", "legacy", or "auto".
  (dhe opensmtpd-pki-configuration-dhe
       (default #f)
       (sanitize (lambda (var)
                   (my/sanitize var "opensmtpd-dhe" "dhe" (list false? string?))))))

(define-record-type* <opensmtpd-lmtp-configuration>
  opensmtpd-lmtp-configuration make-opensmtpd-lmtp-configuration
  opensmtpd-lmtp-configuration?
  (destination opensmtpd-lmtp-configuration-destination
               (default #f)
               (sanitize (lambda (var)
                           (my/sanitize var "opensmtpd-lmtp-configuration" "destination"
                                        (list string?)))))
  (rcpt-to opensmtpd-lmtp-configuration-rcpt-to
           (default #f)
           (sanitize (lambda (var)
                       (my/sanitize var "opensmtpd-lmtp-configuration" "rcpt-to"
                                    (list false? string?))))))

(define-record-type* <opensmtpd-mda-configuration>
  opensmtpd-mda-configuration make-opensmtpd-mda-configuration
  opensmtpd-mda-configuration?
  (name opensmtpd-mda-configuration-name
        (default #f)
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-mda-configuration" "name"
                                 (list string?)))))
  ;; TODO should I allow this command to be a gexp?
  (command opensmtpd-mda-configuration-command
           (default #f)
           (sanitize (lambda (var)
                       (my/sanitize var "opensmtpd-mda-configuration" "command"
                                    (list string?))))))

(define-record-type* <opensmtpd-maildir-configuration>
  opensmtpd-maildir-configuration make-opensmtpd-maildir-configuration
  opensmtpd-maildir-configuration?
  (pathname opensmtpd-maildir-configuration-pathname
            (default #f)
            (sanitize (lambda (var)
                        (my/sanitize var "opensmtpd-maildir-configuration" "pathname"
                                     (list false? string?)))))
  (junk opensmtpd-maildir-configuration-junk
        (default #f)
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-maildir-configuration" "junk"
                                 (list boolean?))))))

(define-record-type* <opensmtpd-action-local-delivery-configuration>
  opensmtpd-action-local-delivery-configuration make-opensmtpd-action-local-delivery-configuration
  opensmtpd-action-local-delivery-configuration?
  (name opensmtpd-action-local-delivery-configuration-name
        (default #f)
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-action-local-delivery-configuration" "name"
                                 (list string?)))))
  (method opensmtpd-action-local-delivery-configuration-method
          (default "mbox")
          (sanitize (lambda (var)
                      (cond
                       [(or (opensmtpd-lmtp-configuration? var)
                            (opensmtpd-maildir-configuration? var)
                            (opensmtpd-mda-configuration? var)
                            (string=? var "mbox")
                            (string=? var "expand-only")
                            (string=? var "forward-only"))
                        var]
                       [else
                        (begin
                          (display (string-append "<opensmtpd-action-local-delivery-configuration> fieldname 'method' must be of type \n"
                                                  "\"mbox\", \"expand-only\", \"forward-only\" \n"
                                                  "<opensmtpd-lmtp-configuration>, <opensmtpd-maildir-configuration>, \n"
                                                  "or <opensmtpd-mda-configuration>.\n"))
                          (throw 'bad! var))]))))
  (alias opensmtpd-action-local-delivery-configuration-alias
         (default #f)
         (sanitize (lambda (var)
                     (my/sanitize var "opensmtpd-action-local-delivery-configuration" "alias"
                                  (list false? opensmtpd-table-configuration?)))))
  (ttl opensmtpd-action-local-delivery-configuration-ttl
       (default #f)
       (sanitize (lambda (var)
                   (my/sanitize var "opensmtpd-action-local-delivery-configuration" "ttl"
                                (list false? string?)))))
  (user opensmtpd-action-local-delivery-configuration-user
        (default #f)
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-action-local-delivery-configuration" "user"
                                 (list false? string?)))))
  (userbase opensmtpd-action-local-delivery-configuration-userbase
            (default #f)
            (sanitize (lambda (var)
                        (my/sanitize var "opensmtpd-action-local-delivery-configuration" "userbase"
                                     (list false? opensmtpd-table-configuration?)))))
  (virtual opensmtpd-action-local-delivery-configuration-virtual
           (default #f)
           (sanitize (lambda (var)
                       (my/sanitize var "opensmtpd-action-local-delivery-configuration" "virtual"
                                    (list false? opensmtpd-table-configuration?)))))
  (wrapper opensmtpd-action-local-delivery-configuration-wrapper
           (default #f)
           (sanitize (lambda (var)
                       (my/sanitize var "opensmtpd-action-local-delivery-configuration" "wrapper"
                                    (list false? string?))))))

;; FIXME/TODO this is a valid opensmtpd-relay record
;; (opensmtpd-action-relay-configuration
;;  (pki (opensmtpd-pki-configuration
;;        (domain "gnucode.me")
;;        (cert "opensmtpd.scm")
;;        (key "opensmtpd.scm"))))
;; BUT how does it relay the email?  What host does it use?
;; I think opensmtpd-relay-configuration needs "method" field.
;; the method field might need to be another record...BUT basically the relay has to have a 'backup', 'backup-mx',
;; or 'domain', or 'host' defined.
(define-record-type* <opensmtpd-action-relay-configuration>
  opensmtpd-action-relay-configuration make-opensmtpd-action-relay-configuration
  opensmtpd-action-relay-configuration?
  (name opensmtpd-action-relay-configuration-name
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-action-relay-configuration" "name"
                                 (list string?))))
        (default #f))
  (backup opensmtpd-action-relay-configuration-backup ;; boolean
          (default #f)
          (sanitize (lambda (var)
                      (my/sanitize var "opensmtpd-action-relay-configuration" "backup"
                                   (list boolean?)))))
  (backup-mx opensmtpd-action-relay-configuration-backup-mx ;; string mx name
             (default #f)
             (sanitize (lambda (var)
                         (my/sanitize var "opensmtpd-action-relay-configuration" "backup-mx"
                                      (list false? string?)))))
  (helo opensmtpd-action-relay-configuration-helo
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-action-relay-configuration" "helo"
                                 (list false? string? opensmtpd-table-configuration?))))
        (default #f))
  (helo-src opensmtpd-action-relay-configuration-helo-src
        (sanitize (lambda (var)
                      (my/sanitize var "opensmtpd-action-relay-configuration" "helo-src"
                                   (list false? string? opensmtpd-table-configuration?))))
        (default #f))
  (domain opensmtpd-action-relay-configuration-domain
          (sanitize (lambda (var)
                      (my/sanitize var "opensmtpd-action-relay-configuration" "domain"
                                   (list false? opensmtpd-table-configuration?))))
          (default #f))
  (host opensmtpd-action-relay-configuration-host
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-action-relay-configuration" "host"
                                 (list false? string?))))
        (default #f))
  (pki opensmtpd-action-relay-configuration-pki
       (default #f)
       (sanitize (lambda (var)
                   (my/sanitize var "opensmtpd-action-relay-configuration" "pki"
                                (list false? opensmtpd-pki-configuration?)))))
  (srs opensmtpd-action-relay-configuration-srs
       (default #f)
       (lambda (var)
         (my/sanitize var "opensmtpd-action-relay-configuration" "srs"
                      (list boolean?))))
  (tls opensmtpd-action-relay-configuration-tls
       (default #f)
       (sanitize (lambda (var)
                   (my/sanitize var "opensmtpd-action-relay-configuration" "tls"
                                (list false? string?)))))
  (auth opensmtpd-action-relay-configuration-auth
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-action-relay-configuration" "auth"
                                 (list false? opensmtpd-table-configuration?))))
        (default #f))
  (mail-from opensmtpd-action-relay-configuration-mail-from
             (default #f))
  ;; string "127.0.0.1" or "<interface>" or "<table of IP addresses>"
  ;; TODO should I do some sanitizing to make sure that the string? here is actually an IP address or a valid interface?
  (src opensmtpd-action-relay-configuration-src
       (sanitize (lambda (var)
                   (my/sanitize var "opensmtpd-action-relay-configuration" "src"
                                (list false? string? opensmtpd-table-configuration?))))
       (default #f)))

;; this record is used by <opensmtpd-filter-phase-configuration> &
;; <opensmtpd-match-configuration>
(define-record-type* <opensmtpd-option-configuration>
  opensmtpd-option-configuration make-opensmtpd-option-configuration
  opensmtpd-option-configuration?
  (option opensmtpd-option-configuration-option
          (default #f)
          (sanitize (lambda (var)
                      (if (and (string? var)
                               (or (string-in-list? var (list "fcrdns" "rdns"
                                                          "src" "helo"
                                                          "auth" "mail-from"
                                                          "rcpt-to"
                                                          "for"
                                                          "for any" "for local"
                                                          "for domain" "for rcpt-to"
                                                          "from any" "from auth"
                                                          "from local" "from mail-from"
                                                          "from rdns" "from socket"
                                                          "from src" "auth"
                                                          "helo" "mail-from"
                                                          "rcpt-to" "tag" "tls"
                                                          ))))
                          var
                          (begin
                            (display (string-append "<opensmtpd-option-configuration> fieldname: 'option' is of type \n"
                                                    "string.  The string can be either 'fcrdns', \n"
                                                    " 'rdns', 'src', 'helo', 'auth', 'mail-from', or 'rcpt-to', \n"
                                                    "'for', 'for any', 'for local', 'for domain', 'for rcpt-to', \n"
                                                    "'from any', 'from auth', 'from local', 'from mail-from', 'from rdns', 'from socket', \n"
                                                    "'from src', 'auth helo', 'mail-from', 'rcpt-to', 'tag', or 'tls' \n"
                                                    ))
                            (throw 'bad! var))))))
  (not opensmtpd-option-configuration-not
       (default #f)
       (sanitize (lambda (var)
                   (my/sanitize var "opensmtpd-option-configuration" "not"
                                (list boolean?)))))
  (regex opensmtpd-option-configuration-regex
         (default #f)
         (sanitize (lambda (var)
                     (my/sanitize var "opensmtpd-option-configuration" "regex"
                                  (list boolean?)))))
  (data opensmtpd-option-configuration-data
         (default #f)
         (sanitize (lambda (var)
                     (my/sanitize var "opensmtpd-option-configuration" "data"
                                  (list false? string? opensmtpd-table-configuration?))))))

(define-record-type* <opensmtpd-filter-phase-configuration>
  opensmtpd-filter-phase-configuration make-opensmtpd-filter-phase-configuration
  opensmtpd-filter-phase-configuration?
  (name opensmtpd-filter-phase-configuration-name ;; string chain-name
        (default #f)
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-filter-phase-configuration" "name"
                                 (list string?)))))
  (phase opensmtpd-filter-phase-configuration-phase ;; string
              (default #f)
              (sanitize (lambda (var)
                          ;;(my/sanitize var "opensmtpd-filter-phase-configuration" "phase"
                          ;;             (list (sanitize-configuration
                          ;;                    (proc (lambda (value)
                          ;;                            (and (string? var)
                          ;;                                 (string-in-list? var (list "connect"
                          ;;                                                            "helo"
                          ;;                                                            "mail-from"
                          ;;                                                            "rcpt-to"
                          ;;                                                            "data"
                          ;;                                                            "commit")))))
                          ;;                    (error-message (list
                          ;;                                    "<opensmtpd-filter-phase-configuration> fieldname: 'phase' is of type \n"
                          ;;                                    "string.  The string can be either 'connect',"
                          ;;                                    " 'helo', 'mail-from', 'rcpt-to', 'data', or 'commit.'\n ")))))
                          (if (and (string? var)
                                   (string-in-list? var (list "connect"
                                                          "helo"
                                                          "mail-from"
                                                          "rcpt-to"
                                                          "data"
                                                          "commit")))
                              var
                              (begin
                                (display (string-append "<opensmtpd-filter-phase-configuration> fieldname: 'phase' is of type \n"
                                                        "string.  The string can be either 'connect',"
                                                        " 'helo', 'mail-from', 'rcpt-to', 'data', or 'commit.'\n "
                                                        ))
                                (throw 'bad! var)))
                          )))

  (options opensmtpd-filter-phase-configuration-options
              (default #f)
              (sanitize (lambda (var)
                          ;; returns #t if list is a unique list of <opensmtpd-option-configuration>
                          (define (list-of-opensmtpd-option-configuration? list)
                            (and (list-of-type? list opensmtpd-option-configuration?)
                                 (not (contains-duplicate? list))))

                          (define (list-has-duplicates-or-non-opensmtpd-option-configuration list)
                            (not (list-of-opensmtpd-option-configuration? list)))

                          ;; input <opensmtpd-option-configuration>
                          ;; return #t if <opensmtpd-option-configuration> fieldname 'option'
                          ;; that needs a corresponding table has one.  Otherwise #f
                          (define (opensmtpd-option-configuration-has-table? record)
                            (define decision (opensmtpd-option-configuration-option record))
                            (and (string? decision)
                                 ;; if option needs a table, check for a table
                                 (if (string-in-list? decision (list "src"
                                                                     "helo"
                                                                     "mail-from"
                                                                     "rcpt-to"))
                                     (opensmtpd-table-configuration? (opensmtpd-option-configuration-data record))
                                     #t)))

                          (define (list-of-opensmtpd-option-configuration-has-table? list)
                            (list-of-type? list opensmtpd-option-configuration-has-table?))

                          (define (some-opensmtpd-option-configuration-in-list-lack-table? list)
                            (not (list-of-opensmtpd-option-configuration-has-table? list)))

                          ;;each element in list is of type <opensmtpd-option-configuration>
                          (cond [(list-has-duplicates-or-non-opensmtpd-option-configuration var)
                                 (begin
                                   (display (string-append "<opensmtpd-filter-phase-configuration> fieldname: 'options' is a list of unique \n"
                                                           "<opensmtpd-option-configuration> records.\n"))
                                   (throw 'bad! var))]
                                ;; if fieldname 'option' is of string 'src', 'helo', 'mail-from', 'rcpt-to', then there should be a table
                                [(some-opensmtpd-option-configuration-in-list-lack-table? var)
                                 (begin
                                   (display (string-append "<opensmtpd-option-configuration>'s fieldname 'option' values of \n"
                                                           "'src', 'helo', 'mail-from', or 'rcpt-to' need a corresponding 'table' \n"
                                                           " of type <opensmtpd-table-configuration>. eg: \n"
                                                           "(opensmtpd-option-configuration \n"
                                                           "   (option \"src\")\n"
                                                           "   (table (opensmtpd-table-configuration \n"
                                                           "              (name \"src-table\")\n"
                                                           "              (data (list \"hello\" \"cat\")))))\n"))
                                   ;; TODO it would be nice if the var this error message throws in the bad
                                   ;; <opensmtpd-option-configuration>, instead of the list of records.
                                   (throw 'bad! var))]
                                [else var]))))
  (decision opensmtpd-filter-phase-configuration-decision
            (default #f)
            (sanitize (lambda (var)
                        (if (and (string? var)
                                 (string-in-list? var (list "bypass" "disconnect"
                                                            "reject" "rewrite" "junk")))
                            var
                            (begin
                              (display (string-append "<opensmtpd-filter-decision> fieldname: 'decision' is of type \n"
                                                      "string.  The string can be either 'bypass',"
                                                      " 'disconnect', 'reject', 'rewrite', or 'junk'.\n"))
                              (throw 'bad! var))))))
  (message opensmtpd-filter-phase-configuration-message
           (default #f)
           (sanitize (lambda (var)
                       (my/sanitize var "opensmtpd-filter-phase-configuration" "message"
                                    (list false? string?)))))
  (value opensmtpd-filter-phase-configuration-value
           (default #f)
           (sanitize (lambda (var)
                       (my/sanitize var "opensmtpd-filter-phase-configuration" "value"
                                    (list false? number?))))))

(define-record-type* <opensmtpd-filter-configuration>
  opensmtpd-filter-configuration make-opensmtpd-filter-configuration
  opensmtpd-filter-configuration?
  (name opensmtpd-filter-configuration-name
        (default #f)
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-filter" "name"
                                 (list string?)))))
  (exec opensmtpd-filter-exec
        (default #f)
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-filter" "exec"
                                 (list boolean?)))))
  (proc opensmtpd-filter-configuration-proc ; a string like "rspamd" or the command to start it like "/path/to/rspamd --option=arg --2nd-option=arg2"
             (default #f)
             (sanitize (lambda (var)
                         (my/sanitize var "opensmtpd-filter" "proc"
                                      (list string?))))))

;; There is another type of filter that opensmtpd supports, which is a filter chain.
;; A filter chain is a list of <opensmtpd-filter-phase-configuration> and <opensmtpd-filter-configuration>.
;; This lets you apply several filters under one filter name.  I could have defined
;; a record type for it, but the record would only have had two fields: name and list-of-filters.
;; Why write that as a record?  That's too simple.
;; returns #t if list is a unique list of <opensmtpd-filter-configuration> or <opensmtpd-filter-phase-configuration>
;; returns # otherwise
(define (opensmtpd-filter-chain? %filters)
  (and (list-of-unique-filter-or-filter-phase? %filters)
       (< 1 (length %filters))))

(define-record-type* <opensmtpd-listen-on-configuration>
  opensmtpd-listen-on-configuration make-opensmtpd-listen-on-configuration
  opensmtpd-listen-on-configuration?
  ;; interface may be an IP address, interface group, or domain name
  (interface opensmtpd-listen-on-configuration-interface
             (default "lo"))
  (family opensmtpd-listen-on-configuration-family
          (default #f)
          (sanitize (lambda (var)
                      (cond
                       [(eq? #f var) ;; var == #f
                        var]
                       [(and (string? var)
                             (string-in-list? var (list "inet4" "inet6")))
                        var]
                       [else
                        (begin
                          (display "<opensmtpd-listen-on-configuration> fieldname 'family' must be string \"inet4\" or \"inet6\".\n")
                          (throw 'bad! var))]))))
  (auth opensmtpd-listen-on-configuration-auth
        (default #f)
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-listen-on-configuration" "auth"
                                 (list boolean? table-whose-data-are-assoc-list?)))))
  (auth-optional opensmtpd-listen-on-configuration-auth-optional
                 (default #f)
                 (sanitize (lambda (var)
                             (my/sanitize var "opensmtpd-listen-on-configuration" "auth-optional"
                                          (list boolean?
                                                table-whose-data-are-assoc-list?)))))
  ;; TODO add a ca entry?
  ;; string FIXME/TODO sanitize this to support a gexp.  That way way the
  ;; includes directive can include my hacky scheme code that I use for opensmtpd-dkimsign.
  (filters opensmtpd-listen-on-configuration-filters
           (default #f)
           (sanitize (lambda (var)
                       (sanitize-filters var))))
  (hostname opensmtpd-listen-on-configuration-hostname
            (default #f)
            (sanitize (lambda (var)
                        (my/sanitize var "opensmtpd-listen-on-configuration" "hostname"
                                     (list false? string?)))))
  (hostnames opensmtpd-listen-on-configuration-hostnames
             (default #f)
             (sanitize (lambda (var)
                         (my/sanitize var "opensmtpd-listen-on-configuration" "hostnames"
                                      (list false? table-whose-data-are-assoc-list?)))))
  (mask-src opensmtpd-listen-on-configuration-mask-src
            (default #f)
            (sanitize (lambda (var)
                        (my/sanitize var "opensmtpd-listen-on-configuration" "mask-src"
                                     (list boolean?)))))
  (disable-dsn opensmtpd-listen-on-configuration-disable-dsn
          (default #f))
  (pki opensmtpd-listen-on-configuration-pki
       (default #f)
       (sanitize (lambda (var)
                   (my/sanitize var "opensmtpd-listen-on-configuration" "pki"
                                (list false? opensmtpd-pki-configuration?)))))
  (port opensmtpd-listen-on-configuration-port
        (default #f)
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-listen-on-configuration" "port"
                                 (list false? integer?)))))
  (proxy-v2 opensmtpd-listen-on-configuration-proxy-k2
            (default #f))
  (received-auth opensmtpd-listen-on-configuration-received-auth
                 (default #f))
  ;; TODO add in a senders option!
  ;; string or <opensmtpd-senders> record
  ;; (senders opensmtpd-listen-on-configuration-senders
  ;;          (sanitize (lambda (var)
  ;;                      (my/sanitize var "opensmtpd-listen-on-configuration" "port" (list false? integer?))))
  ;;          (default #f))
  (secure-connection opensmtpd-listen-on-configuration-secure-connection
                     (default #f)
                     (sanitize (lambda (var)
                                 (cond [(boolean? var)
                                        var]
                                       [(and (string? var)
                                             (string-in-list? var
                                                              (list "smtps" "tls"
                                                                    "tls-require"
                                                                    "tls-require-verify")))
                                        var]
                                       [else
                                        (begin
                                          (display (string-append "<opensmtd-listen-on> fieldname 'secure-connection' can be \n"
                                                                  "one of the following strings: \n'smtps', 'tls', 'tls-require', \n"
                                                                  "or 'tls-require-verify'.\n"))
                                          (throw 'bad! var))]))))
  (tag opensmtpd-listen-on-configuration-tag
       (sanitize (lambda (var)
                   (my/sanitize var "opensmtpd-listen-on-configuration" "tag"
                                (list false? string?))))
       (default #f)))

(define-record-type* <opensmtpd-listen-on-socket-configuration-configuration>
  opensmtpd-listen-on-socket-configuration-configuration make-opensmtpd-listen-on-socket-configuration-configuration
  opensmtpd-listen-on-socket-configuration-configuration?
  ;; false or <opensmtpd-filter-configuration> or list of <opensmtpd-filter-configuration>
  (filters opensmtpd-listen-on-socket-configuration-configuration-filters
           (sanitize (lambda (var)
                       (sanitize-filters var)))
          (default #f))
  (mask-src opensmtpd-listen-on-socket-configuration-configuration-mask-src
            (default #f))
  (tag opensmtpd-listen-on-socket-configuration-configuration-tag
       (sanitize (lambda (var)
                   (my/sanitize var "opensmtpd-listen-on-configuration" "tag"
                                (list false? string?))))
       (default #f)))


(define-record-type* <opensmtpd-match-configuration>
  opensmtpd-match-configuration make-opensmtpd-match-configuration
  opensmtpd-match-configuration?
  ;;TODO? Perhaps I should add in a reject fieldname.  If reject
  ;;is #t, then the match record will be a reject match record.
  ;; (opensmtpd-match (reject #t)) vs. (opensmtpd-match (action 'reject))
  ;; To do this, I will also have to  'reject' mutually exclusive. AND an match with 'reject' can have no action defined.
  (action opensmtpd-match-configuration-action
          (default #f)
          (sanitize (lambda (var)
                      (if (or (opensmtpd-action-relay-configuration? var)
                              (opensmtpd-action-local-delivery-configuration? var)
                              (eq? (quote reject) var))
                          var
                          (begin
                            (display
                             (string-append "<opensmtpd-match-configuration> fieldname 'action' is of type <opensmtpd-action-relay-configuration>, \n"
                                            "<opensmtpd-action-local-delivery-configuration>, or (quote reject).\n"
                                            "If its var is (quote reject), then the match rejects the incoming message\n"
                                            "during the SMTP dialogue.\n"))
                            (throw 'bad! var))))))
  (options opensmtpd-match-configuration-options
           (default #f)
           (sanitize (lambda (var)
                       (cond ((not var)
                              #f)
                             ((not (list-of-unique-opensmtpd-option-configuration? var))
                              (throw-error var '("<opensmtpd-match-configuration> fieldname 'options' is a list of unique \n"
                                                 "<opensmtpd-option-configuration> records. \n")))
                           (else (sanitize-list-of-options-for-match-configuration var)))))))

(define-record-type* <opensmtpd-smtp-configuration>
  opensmtpd-smtp-configuration make-opensmtpd-smtp-configuration
  opensmtpd-smtp-configuration?
  (ciphers opensmtpd-smtp-configuration-ciphers
           (default #f)
           (sanitize (lambda (var)
                       (my/sanitize var "opensmtpd-smtp-configuration" "ciphers"
                                    (list false? string?)))))
  (limit-max-mails opensmtpd-smtp-configuration-limit-max-mails
                   (default #f)
                   (sanitize (lambda (var)
                               (my/sanitize var "opensmtpd-smtp-configuration" "limit-max-mails"
                                            (list false? integer?)))))
  (limit-max-rcpt opensmtpd-smtp-configuration-limit-max-rcpt
                  (default #f)
                  (sanitize (lambda (var)
                              (my/sanitize var "opensmtpd-smtp-configuration" "limit-max-rcpt"
                                           (list false? integer?)))))
  (max-message-size opensmtpd-smtp-configuration-max-message-size
                    (default #f)
                    (sanitize (lambda (var)
                                (my/sanitize var "opensmtpd-smtp-configuration" "max-message-size"
                                             (list false? integer? string?)))))
  ;; FIXME/TODO the sanitize function of sub-addr-delim should accept a string of length one not string?
  (sub-addr-delim opensmtpd-smtp-configuration-sub-addr-delim
                  (default #f)
                  (sanitize (lambda (var)
                              (my/sanitize var "opensmtpd-smtp-configuration" "sub-addr-delim"
                                           (list false? integer? string?))))))

(define-record-type* <opensmtpd-srs-configuration>
  opensmtpd-srs-configuration make-opensmtpd-srs-configuration
  opensmtpd-srs-configuration?
  ;; TODO should this be a file?
  (key opensmtpd-srs-configuration-key
       (default #f)
       (sanitize (lambda (var)
                   (my/sanitize var "opensmtpd-srs-configuration" "key"
                                (list false? boolean? string?)))))
  ;; TODO should this also be a file?
  (backup-key opensmtpd-srs-configuration-backup-key
              (default #f)
              (sanitize (lambda (var)
                          (my/sanitize var "opensmtpd-srs-configuration" "backup-key"
                                       (list false? integer?)))))
  (ttl-delay opensmtpd-srs-configuration-ttl-delay
             (default #f)
             (sanitize (lambda (var)
                         (my/sanitize var "opensmtpd-srs-configuration" "ttl-delay"
                                      (list false? string?))))))

(define-record-type* <opensmtpd-queue-configuration>
  opensmtpd-queue-configuration make-opensmtpd-queue-configuration
  opensmtpd-queue-configuration?
  (compression opensmtpd-queue-configuration-compression
               (default #f)
               (sanitize (lambda (var)
                           (my/sanitize var "opensmtpd-queue-configuration" "compression"
                                        (list boolean?)))))
  (encryption opensmtpd-queue-configuration-encryption
              (default #f)
              (sanitize (lambda (var)
                          (my/sanitize var "opensmtpd-queue-configuration" "encryption"
                                       (list boolean? file-exists? string?)))))
  (ttl-delay opensmtpd-queue-configuration-ttl-delay
             (default #f)
             (sanitize (lambda (var)
                         (my/sanitize var "opensmtpd-queue-configuration" "ttl-delay"
                                      (list false? string?))))))

(define-record-type* <opensmtpd-configuration>
  opensmtpd-configuration make-opensmtpd-configuration
  opensmtpd-configuration?
  (package opensmtpd-configuration-package
           (default opensmtpd))
  (config-file opensmtpd-configuration-config-file
               (default #f))
  ;; FIXME/TODO should I include a admd authservid entry?

  ;; TODO sanitize this properly with perhaps a <sanitize-configuration>.
  (bounce opensmtpd-configuration-bounce
          (default #f)
          (sanitize (lambda (var)
                      (my/sanitize var "opensmtpd-configuration" "bounce"
                                   (list false? list?)))))
  (cas opensmtpd-configuration-cas
       (default #f)
       (sanitize (lambda (var)
                   (my/sanitize var "opensmtpd-configuration" "cas"
                                (list false? list-of-opensmtpd-ca-configuration?)))))
  ;; list of many records of type opensmtpd-listen-on-configuration
  (listen-ons opensmtpd-configuration-listen-ons
              (default (list (opensmtpd-listen-on-configuration)))
              (sanitize (lambda (var)
                          (if (list-of-opensmtpd-listen-on-configuration? var)
                              var
                              (begin
                                (display "<opensmtpd-configuration> fieldname 'listen-ons' expects a list of records ")
                                (display "of one or more unique <opensmtpd-listen-on-configuration> records.\n")
                                (throw 'bad! var))))))
  ;; accepts type <opensmtpd-listen-on-socket-configuration-configuration>
  (listen-on-socket opensmtpd-configuration-listen-on-socket
                    (default (opensmtpd-listen-on-socket-configuration-configuration)))
  (includes opensmtpd-configuration-includes ;; list of strings of absolute path names
            (default #f)
            (sanitize (lambda (var)
                        (my/sanitize var "opensmtpd-configuration" "includes"
                                     (list false? list-of-strings?)))))
  (matches opensmtpd-configuration-matches
           (default (list (opensmtpd-match-configuration
                           (action (opensmtpd-action-local-delivery-configuration
                                    (name "local")
                                    (method "mbox")))
                           (options (list
                                     (opensmtpd-option-configuration
                                      (option "for local")))))
                          (opensmtpd-match-configuration
                           (action (opensmtpd-action-relay-configuration
                                    (name "outbound")))
                           (options (list
                                     (opensmtpd-option-configuration
                                      (option "from local"))
                                     (opensmtpd-option-configuration
                                      (option "for any")))))))
           ;; TODO perhaps I should sanitize this function like I sanitized the 'filters'.
           ;; I definitely should sanitize this function a bit more.  For example, you could have two different
           ;; actions, one for local delivery and one for remote, with the same name.  I should make sure that
           ;; I have no two different actions with the same name.
           (sanitize (lambda (var)
                       ;; Should we do more sanitizing here?  eg: "from socket" should NOT have a table or value
                       var
                       (my/sanitize var "opensmtpd-configuration" "matches"
                                    (list list-of-unique-opensmtpd-match-configuration?)))))
  ;; list of many records of type mda-wrapper
  ;; TODO/FIXME support using gexps here
  ;; eg (list "name" gexp)
  (mda-wrappers opensmtpd-configuration-mda-wrappers
                (default #f)
                (sanitize (lambda (var)
                            (my/sanitize var
                                         "opensmtpd-configuration"
                                         "mda-wrappers"
                                         (list false? string?)))))
  (mta-max-deferred opensmtpd-configuration-mta-max-deferred
                    (default 100)
                    (sanitize (lambda (var)
                                (my/sanitize var "opensmtpd-configuration" "mta-max-deferred"
                                             (list number?)))))

  ;; TODO should I add a fieldname proc _proc-name_ _command_ as found in the man 5 smtpd.conf ?

  (queue opensmtpd-configuration-queue
         (default #f)
         (sanitize (lambda (var)
                     (my/sanitize var "opensmtpd-configuration" "queue"
                                  (list false? opensmtpd-queue-configuration?)))))
  (smtp opensmtpd-configuration-smtp
        (default #f)
        (sanitize (lambda (var)
                    (my/sanitize var "opensmtpd-configuration" "smtp"
                                 (list false? opensmtpd-smtp-configuration?)))))
  (srs opensmtpd-configuration-srs
       (default #f)
       (sanitize (lambda (var)
                   (my/sanitize var "opensmtpd-configuration" "srs"
                                (list false? opensmtpd-srs-configuration?))))))

;; This is a non-exported record for passing around sanitize procedures.
;; As of 5/2/2022 I am not using it.  I should probably just delete it.
(define-record-type* <sanitize-configuration>
  sanitize-configuration make-sanitize-configuration
  sanitize-configuration?
  (proc sanitize-configuration-proc
          (default #f)
          ;;(sanitize (lambda (var) (procedure? var)))
          )
  (args sanitize-configuration-args
       (default #f)
       ;;(sanitize (lambda (var) (lambda (var) (list? var))))
       )
  (error-message sanitize-configuration-error-message
         (default #f)
         ;;(sanitize (lambda (var) (list? var)))
         )
  (error-if-proc-fails sanitize-configuration-error-if-proc-fails
                       (default #f)))

;; this help procedure is used 3 or 4 times by sanitize-list-of-options-for-match-configuration
(define (throw-error-duplicate-option option error-arg)
  (throw-error error-arg
               (list "<opensmtpd-match-configuration>'s fieldname 'options' has two\n"
                     (string-append "<opensmtpd-option-configuration> records with fieldname 'option' with value '" option "'. \n")
                     (string-append "You can only have one option with value '" option "' in the options list.\n"))))

;; this procedure sanitizes the fieldname opensmtpd-match-configuration-options
(define* (sanitize-list-of-options-for-match-configuration %options)
  (let loop ([%traversing-options %options]
             [%sanitized-options '()])
    (if (null? %traversing-options)
           (remove false?
                   (list
                    (assoc-ref %sanitized-options "for")
                    (assoc-ref %sanitized-options "from")
                    (assoc-ref %sanitized-options "auth")
                    (assoc-ref %sanitized-options "helo")
                    (assoc-ref %sanitized-options "mail-from")
                    (assoc-ref %sanitized-options "rcpt-to")
                    (assoc-ref %sanitized-options "tag")
                    (assoc-ref %sanitized-options "tls")))
          (let* ((option-record (car %traversing-options))
                 (option-string (opensmtpd-option-configuration-option option-record)))
            (cond [(string=? "auth" option-string)
                   (if (assoc-ref %sanitized-options "auth")
                       (throw-error-duplicate-option "auth" %traversing-options)
                       (loop (cdr %traversing-options) (alist-cons "auth" option-record %sanitized-options)))]
                  [(string=? "helo" option-string)
                   (cond [(assoc-ref %sanitized-options "helo")
                          (throw-error-duplicate-option "helo" %traversing-options)]
                         [(not (opensmtpd-option-configuration-data option-record))
                          (throw-error option-record
                                       (list "<opensmtpd-option-configuration> with fieldname 'option' with value 'helo' \n"
                                             "must have a 'data' of type string or <opensmtpd-table-configuration>.\n"))]
                         [else (loop (cdr %traversing-options) (alist-cons "helo" option-record %sanitized-options))])]
                  [(string=? "mail-from" option-string)
                   (cond ((assoc-ref %sanitized-options "mail-from")
                          (throw-error-duplicate-option "mail-from" %traversing-options))
                         ((not (opensmtpd-option-configuration-data option-record))
                          (throw-error option-record
                                       (list "<opensmtpd-option-configuration> with fieldname 'option' with value 'mail-from' \n"
                                             "must have a 'data' of type string or <opensmtpd-table-configuration>.\n")))
                         (else (loop (cdr %traversing-options) (alist-cons "mail-from" option-record %sanitized-options))))]
                  [(string=? "rcpt-to" option-string)
                   (cond [(assoc-ref %sanitized-options "rcpt-to")
                          (throw-error-duplicate-option "rcpt-to" %traversing-options)]
                         [(not (opensmtpd-option-configuration-data option-record))
                          (throw-error option-record
                                       (list "<opensmtpd-option-configuration> with fieldname 'option' with value 'rcpt-to' \n"
                                             "must have a 'data' of type string or <opensmtpd-table-configuration>.\n"))]
                         [else (loop (cdr %traversing-options) (alist-cons "rcpt-to" option-record %sanitized-options))])]
                  [(string=? "tag" option-string)
                   (cond ((assoc-ref %sanitized-options "tag")
                          (throw-error-duplicate-option "tag" %traversing-options))
                         ((not (string? (opensmtpd-option-configuration-data option-record)))
                          (throw-error option-record
                                       (list "<opensmtpd-option-configuration> with fieldname 'option' with value 'tag' \n"
                                             "must have a 'data' of type string.\n")))
                         (else (loop (cdr %traversing-options) (alist-cons "tag" option-record %sanitized-options))))]
                  [(string=? "tls" option-string)
                   (cond [(assoc-ref %sanitized-options "tls")
                          (throw-error-duplicate-option "tls" %traversing-options)]
                         [(or (opensmtpd-option-configuration-data option-record)
                              (opensmtpd-option-configuration-regex option-record))
                          (throw-error option-record
                                       (list "<opensmtpd-option-configuration> with fieldname 'option' with value 'tls' \n"
                                             "cannot have a string or table 'data'.\n"))]
                         [else (loop (cdr %traversing-options) (alist-cons "tls" option-record %sanitized-options))])]
                  [(string=? "for" (substring option-string 0 3))
                   (cond ((assoc-ref %sanitized-options "for")
                          (throw-error %options
                                       `("<opensmtpd-match-configuration>'s fieldname 'options' can only have one 'for' option. \n"
                                         "But '" ,option-string "' and '"
                                         ,(opensmtpd-option-configuration-option (assoc-ref %sanitized-options "for")) "' are present.\n")))
                         ((and (string-in-list? option-string (list "for any" "for local")) ; for any cannot have a data field.
                               (or (opensmtpd-option-configuration-data option-record)
                                   (opensmtpd-option-configuration-regex option-record)))
                          (throw-error option-record
                                       (list "When <openmstpd-option-configuration>'s fieldname 'options' value is 'for any' \n"
                                             "or 'for local', then its 'data' and 'regex' field must be #f. \n")))
                         ((and (string-in-list? option-string (list "for domain" "for rcpt-to")) ; for domain must have a data field.
                               (not (opensmtpd-option-configuration-data option-record)))
                          (throw-error option-record
                                       (list "When <openmstpd-option-configuration>'s fieldname 'options' value is 'for domain' \n"
                                             "or 'for rcpt-to', then its 'data' field must be a string or an \n"
                                             "<opensmtpd-table-configuration> record.\n")))
                         (else (loop (cdr %traversing-options) (alist-cons "for" option-record %sanitized-options))))]
                  [(string=? "from" (substring option-string 0 4))
                   (cond ((assoc-ref %sanitized-options "from")
                          (throw-error %options
                                       `("<opensmtpd-match-configuration>'s fieldname 'options' can only have one 'from' option. \n"
                                         "But '" ,option-string "' and '"
                                         ,(opensmtpd-option-configuration-option (assoc-ref %sanitized-options "from")) "' are present.\n")))
                         ((and (string-in-list? option-string (list "from any" "from local" "from socket")) ; for any cannot have a data field.
                               (or (opensmtpd-option-configuration-data option-record)
                                   (opensmtpd-option-configuration-regex option-record)))
                          (throw-error option-record
                                       (list "When <openmstpd-option-configuration>'s fieldname 'options' value is 'from any', \n"
                                             " 'from local', or 'from socket', then its 'data' and 'regex' field must be #f. \n")))
                         ((and (string-in-list? option-string (list "from mail-from" "from src")) ; for domain must have a data field.
                               (not (opensmtpd-option-configuration-data option-record)))
                          (throw-error option-record
                                       (list "When <openmstpd-option-configuration>'s fieldname 'options' value is 'from mail-from' \n"
                                             "or 'from src', then its 'data' field must be a string or an \n"
                                             "<opensmtpd-table-configuration> record.\n")))
                         (else (loop (cdr %traversing-options) (alist-cons "from" option-record %sanitized-options))))])))))

;; some procedures for <opensmtpd-listen-on-configuration> and
;; <opensmtpd-listen-on-socket-configuration-configuration>.
(define (sanitize-filters %list)
  ;; the order of the first two tests in this cond is important.
  ;; (false?) has to be 1st and (list-has-duplicates-or-non-filters?) has to be second.
  ;; You may optionally re-order the other alternates in the cond.
  (cond [(false? %list)
         #f]
        [(list-has-duplicates-or-non-filters? %list)
         (begin
           (display (string-append "<opensmtpd-listen-on-configuration> fieldname: 'filters' is a list, in which each unique element \n"
                                   "is of type <opensmtpd-filter-configuration> or <opensmtpd-filter-phase-configuration>.\n"))
           (throw 'bad! %list))]
        [else
         (let loop ([%traversing-list %list]
                    [%original-list %list])
           (if (null? %traversing-list)
               %original-list
               (cond
                [(opensmtpd-filter-configuration? (car %traversing-list))
                 (loop (cdr %traversing-list) %original-list)]
                [(filter-phase-has-message-and-value? (car %traversing-list))
                 (begin
                   (display (string-append "<opensmtpd-filter-phase-configuration> cannot have defined fieldnames 'value' \n"
                                           "and 'message'.\n"))
                   (throw 'bad! (car %traversing-list)))]
                [(filter-phase-decision-lacks-proper-message? (car %traversing-list))
                 (begin
                   (display (string-append "<opensmtpd-filter-phase-configuration> fieldname: 'decision' options \n"
                                           "\"disconnect\" and \"reject\" require fieldname 'message' to have a string.\n"
                                           "The 'message' string must be RFC commpliant, which means that the string \n"
                                           "must begin with a 4xx or 5xx status code.\n"))
                   (throw 'bad! (car %traversing-list)))]
                [(filter-phase-lacks-proper-value? (car %traversing-list))
                 (begin
                   (display (string-append "<opensmtpd-filter-phase-configuration> fieldname: 'decision' option \n"
                                           "\"rewrite\" requires fieldname 'value' to have a number.\n"))
                   (throw 'bad! (car %traversing-list)))]
                [(filter-phase-has-incorrect-junk-or-bypass? (car %traversing-list))
                 (begin
                   (display (string-append "<opensmtpd-filter-phase-configuration> fieldname 'decision' option \n"
                                           "\"junk\" or 'bypass' cannot have a defined fieldnames 'message' or 'value'.\n"))
                   (throw 'bad! (car %traversing-list)))]
                [(filter-phase-junks-after-commit? (car %traversing-list))
                 (begin
                   (display (string-append "<opensmtpd-filter-phase-configuration> fieldname 'decision' option \n"
                                           "\"junk\" cannot junk an email during 'phase' \"commit\".\n"))
                   (throw 'bad! (car %traversing-list)))]
                [else (loop (cdr %traversing-list) %original-list)])))]))

(define (list-has-duplicates-or-non-filters? list)
  (not (list-of-unique-filter-or-filter-phase? list)))

(define (filter-phase-has-message-and-value? record)
  (and (opensmtpd-filter-phase-configuration-message record)
       (opensmtpd-filter-phase-configuration-value record)))

;; return #t if phase needs a message. Or if the message did not start with a 4xx or 5xx status code.
;; otherwise #f
(define (filter-phase-decision-lacks-proper-message? record)
  (define decision (opensmtpd-filter-phase-configuration-decision record))
  (if (string-in-list? decision (list "disconnect" "reject"))
      ;; this message needs to be RFC compliant, meaning
      ;; that it need to start with 4xx or 5xx status code
      (cond [(eq? #f (opensmtpd-filter-phase-configuration-message record))
             #t]
            [(string? (opensmtpd-filter-phase-configuration-message record))
             (let ((number (string->number
                            (substring
                             (opensmtpd-filter-phase-configuration-message record) 0 3))))
               (if (and (number? number)
                        (and (< number 600) (> number 399)))
                   #f
                   #t))])
      #f))

;; 'decision' "rewrite" requires 'value' to be a number.
(define (filter-phase-lacks-proper-value? record)
  (define decision (opensmtpd-filter-phase-configuration-decision record))
  (if (string=? "rewrite" decision)
      (if (and (number? (opensmtpd-filter-phase-configuration-value record))
               (eq? #f (opensmtpd-filter-phase-configuration-message record)))
          #f
          #t)
      #f))

;; 'decision' "junk" or "bypass" cannot have a message or a value.
(define (filter-phase-has-incorrect-junk-or-bypass? record)
  (and
   (string-in-list?
    (opensmtpd-filter-phase-configuration-decision record)
    (list "junk" "bypass"))
   (or
    (opensmtpd-filter-phase-configuration-value record)
    (opensmtpd-filter-phase-configuration-message record))))

(define (filter-phase-junks-after-commit? record)
  (and (string=? (opensmtpd-filter-phase-configuration-decision record) "junk")
       (string=? (opensmtpd-filter-phase-configuration-phase record) "commit")))

;; returns #t if list is a unique list of <opensmtpd-filter-configuration> or <opensmtpd-filter-phase-configuration>
;; returns # otherwise
(define (list-of-unique-filter-or-filter-phase? %filters)
  (and (list? %filters)
       (not (null? %filters))
       ;; this list is made up of only <opensmtpd-filter-phase-configuration> or <opensmtpd-filter-configuration>
       (primitive-eval
        (cons 'and (map (lambda (filter)
                          (or (opensmtpd-filter-configuration? filter)
                              (opensmtpd-filter-phase-configuration? filter)))
                        %filters)))
       (not (contains-duplicate? %filters))))

(define (throw-error var %strings)
  (display (apply string-append %strings))
  (throw 'bad! var))

;; this is used for sanitizing <opensmtpd-filter-phase-configuration> fieldname 'options'
(define (contains-duplicate? list)
  (if (null? list)
      #f
      (or
      ;; check if (car list) is in (cdr list)
       (primitive-eval (cons 'or
                                (map (lambda (var) (equal? var (car list)))
                                     (cdr list))))
       ;; check if (cdr list) contains duplicate
       (contains-duplicate? (cdr list)))))

;; given a list and procedure, this tests that each element of list is of type
;; ie: (list-of-type? list string?) tests each list is of type string.
(define (list-of-type? list proc?)
  (if (and (list? list)
           (not (null? list)))
      (let loop ([list list])
        (if (null? list)
            #t
            (if (proc? (car list))
                (loop (cdr list))
                #f)))
      #f))

(define (list-of-strings? list)
  (list-of-type? list string?))

(define (list-of-unique-opensmtpd-option-configuration? list)
  (and (list-of-type?
        list opensmtpd-option-configuration?)
       (not (contains-duplicate? list))))

(define (list-of-opensmtpd-ca-configuration? list)
  (list-of-type? list opensmtpd-ca-configuration?))

(define (list-of-opensmtpd-pki-configuration? list)
  (list-of-type? list opensmtpd-pki-configuration?))

(define (list-of-opensmtpd-listen-on-configuration? list)
  (and (list-of-type? list opensmtpd-listen-on-configuration?)
       (not (contains-duplicate? list))))

(define (list-of-unique-opensmtpd-match-configuration? list)
  (and (list-of-type? list opensmtpd-match-configuration?)
       (not (contains-duplicate? list))))

(define* (list-of-strings->string list
                                  #:key
                                  (string-delimiter ", ")
                                  (postpend "")
                                  (append "")
                                  (drop-right-number 2))
  (string-drop-right
   (string-append (let loop ([list list])
                    (if (null? list)
                        ""
                        (string-append append (car list) postpend
                                       string-delimiter
                                       (loop (cdr list)))))
                  append)
   drop-right-number))

;; at the moment I cannot define this by using list-of-type?
;; the first (not (null? assoc-list)) prevents that.
(define (assoc-list? assoc-list)
  (list-of-type? assoc-list (lambda (pair)
                              (if (and (pair? pair)
                                       (string? (car pair))
                                       (string? (cdr pair)))
                                  #t
                                  #f))))

(define* (variable->string var #:key (append "") (postpend " "))
  (let ([var (if (number? var)
                 (number->string var)
                 var)])
    (if var
        (string-append append var postpend)
        "")))

;; this procedure takes in one argument.
;; if that argument is an <opensmtpd-table-configuration> whose fieldname 'values' is an assoc-list, then it returns
;; #t, #f if otherwise.
;; TODO should I remove these two functions?  And instead use the (opensmtpd-table-configuration-type) procedure?
(define (table-whose-data-are-assoc-list? table)
  (if (not (opensmtpd-table-configuration? table))
      #f
      (assoc-list? (opensmtpd-table-configuration-data table))))

;; this procedure takes in one argument
;; if that argument is an <opensmtpd-table-configuration> whose fieldname 'values' is a list of strings, then it returns
;; #t, #f if otherwise.
(define (table-whose-data-are-a-list-of-strings? table)
  (if (not (opensmtpd-table-configuration? table))
      #f
      (list-of-strings? (opensmtpd-table-configuration-data table))))

;; these next few functions help me to turn <table>s
;; into strings suitable to fit into "opensmtpd.conf".
(define (assoc-list->string assoc-list)
  (string-drop-right
   (let loop ([assoc-list assoc-list])
     (if (null? assoc-list)
         ""
         ;; pair is (cons "hello" "world") -> ("hello" . "world")
         (let ([pair (car assoc-list)])
           (string-append
            "\"" (car pair)  "\""
            " = "
            "\"" (cdr pair) "\""
            ", "
            (loop (cdr assoc-list))))))
   2))

;; can be of type: (quote list-of-strings) or (quote assoc-list)
(define (opensmtpd-table-configuration->string table)
  (string-append "table " (opensmtpd-table-configuration-name table) " "
                 (let ([type (opensmtpd-table-configuration-type table)])
                   (cond [(eq? type (quote list-of-strings))
                          (string-append "{ " (list-of-strings->string (opensmtpd-table-configuration-data table)
                                                                       #:append "\""
                                                                       #:drop-right-number 3
                                                                       #:postpend "\"") " }")]
                         [(eq? type (quote assoc-list))
                          (string-append "{ " (assoc-list->string (opensmtpd-table-configuration-data table)) " }")]
                         [(eq? type (quote db))
                          (string-append "db:" (opensmtpd-table-configuration-data table))]
                         [(eq? type (quote file))
                          (string-append "file:" (opensmtpd-table-configuration-data table))]
                         [else (throw 'youMessedUp table)]))
                 " \n"))

;;  The following functions convert various records into strings.

(define (opensmtpd-listen-on-configuration->string record)
  (string-append "listen on "
                 (opensmtpd-listen-on-configuration-interface record) " "
                 (let* ([hostname (opensmtpd-listen-on-configuration-hostname record)]
                        [hostnames (if (opensmtpd-listen-on-configuration-hostnames record)
                                       (opensmtpd-table-configuration-name (opensmtpd-listen-on-configuration-hostnames record))
                                       #f)]
                        [filters (opensmtpd-listen-on-configuration-filters record)]
                        [filter-name (if filters
                                         (if (< 1 (length filters))
                                             (generate-filter-chain-name filters)
                                             (if (opensmtpd-filter-configuration? (car filters))
                                                 (opensmtpd-filter-configuration-name (car filters))
                                                 (opensmtpd-filter-phase-configuration-name (car filters))))
                                         #f)]
                        [mask-src (opensmtpd-listen-on-configuration-mask-src record)]
                        [tag (opensmtpd-listen-on-configuration-tag record)]
                        [secure-connection (opensmtpd-listen-on-configuration-secure-connection record)]
                        [port (opensmtpd-listen-on-configuration-port record)]
                        [pki (opensmtpd-listen-on-configuration-pki record)]
                        [auth (opensmtpd-listen-on-configuration-auth record)]
                        [auth-optional (opensmtpd-listen-on-configuration-auth-optional record)])
                   (string-append
                    (if mask-src
                        (string-append "mask-src ")
                        "")
                    (variable->string hostname #:append "hostname ")
                    (variable->string hostnames #:append "hostnames <" #:postpend "> ")
                    (variable->string filter-name #:append "filter \"" #:postpend "\" ")
                    (variable->string tag #:append "tag \"" #:postpend "\" ")
                    (if secure-connection
                        (cond [(string=? "smtps" secure-connection)
                               "smtps "]
                              [(string=? "tls" secure-connection)
                               "tls "]
                              [(string=? "tls-require" secure-connection)
                               "tls-require "]
                              [(string=? "tls-require-verify" secure-connection)
                               "tls-require verify "])
                        "")
                    (variable->string port #:append "port " #:postpend " ")
                    (if pki
                        (variable->string (opensmtpd-pki-configuration-domain pki) #:append "pki ")
                        "")
                    (if auth
                        (string-append "auth "
                                       (if (opensmtpd-table-configuration? auth)
                                           (string-append "<" (opensmtpd-table-configuration-name auth) "> ")
                                           ""))
                        "")
                    (if auth-optional
                        (string-append "auth-optional "
                                       (if (opensmtpd-table-configuration? auth-optional)
                                           (string-append "<" (opensmtpd-table-configuration-name auth-optional) "> ")
                                           ""))
                        "")
                    "\n"))))

(define (opensmtpd-listen-on-socket-configuration->string record)
  (string-append "listen on socket "
                 (let* ([filters (opensmtpd-listen-on-socket-configuration-configuration-filters record)]
                        [filter-name (if filters
                                         (if (< 1 (length filters))
                                             (generate-filter-chain-name filters)
                                             (if (opensmtpd-filter-configuration? (car filters))
                                                 (opensmtpd-filter-configuration-name (car filters))
                                                 (opensmtpd-filter-phase-configuration-name (car filters))))
                                         #f)]
                        [mask-src (opensmtpd-listen-on-socket-configuration-configuration-mask-src record)]
                        [tag (opensmtpd-listen-on-socket-configuration-configuration-tag record)])
                   (string-append
                    (if mask-src
                        (string-append "mask-src ")
                        "")
                    (variable->string filter-name #:append "filter \"" #:postpend "\" ")
                    (variable->string tag #:append "tag \"" #:postpend "\" ")
                    "\n"))))

(define (opensmtpd-action-relay-configuration->string record)
  (let ([backup (opensmtpd-action-relay-configuration-backup record)]
        [backup-mx (opensmtpd-action-relay-configuration-backup-mx record)]
        [helo (opensmtpd-action-relay-configuration-helo record)]
        ;; helo-src can either be a string IP address or an <opensmtpd-table-configuration>
        [helo-src (if (opensmtpd-action-relay-configuration-helo-src record)
                      (if (string? (opensmtpd-action-relay-configuration-helo-src record))
                          (opensmtpd-action-relay-configuration-helo-src record)
                          (string-append "<\""
                                         (opensmtpd-table-configuration-name
                                          (opensmtpd-action-relay-configuration-src record))
                                         "\">"))
                      #f)]
        [domain (if (opensmtpd-action-relay-configuration-domain record)
                    (opensmtpd-table-configuration-name
                     (opensmtpd-action-relay-configuration-domain record))
                    #f)]
        [host (opensmtpd-action-relay-configuration-host record)]
        [name (opensmtpd-action-relay-configuration-name record)]
        [pki (if (opensmtpd-action-relay-configuration-pki record)
                 (opensmtpd-pki-configuration-domain (opensmtpd-action-relay-configuration-pki record))
                 #f)]
        [srs (opensmtpd-action-relay-configuration-srs record)]
        [tls (opensmtpd-action-relay-configuration-tls record)]
        [auth (if (opensmtpd-action-relay-configuration-auth record)
                  (opensmtpd-table-configuration-name
                   (opensmtpd-action-relay-configuration-auth record))
                  #f)]
        [mail-from (opensmtpd-action-relay-configuration-mail-from record)]
        ;; src can either be a string IP address or an <opensmtpd-table-configuration>
        [src (if (opensmtpd-action-relay-configuration-src record)
                 (if (string? (opensmtpd-action-relay-configuration-src record))
                     (opensmtpd-action-relay-configuration-src record)
                     (string-append "<\""
                                    (opensmtpd-table-configuration-name
                                     (opensmtpd-action-relay-configuration-src record))
                                    "\">"))
                 #f)]
        )
    (string-append
     "\""
     name
     "\" " "relay "
     ;;FIXME should I always quote the host fieldname? do I need to quote localhost via "localhost" ?
     (variable->string host #:append "host \"" #:postpend "\" ")
     (variable->string backup)
     (variable->string backup-mx #:append "backup mx ")
     (variable->string helo #:append "helo ")
     (variable->string helo-src #:append "helo-src ")
     (variable->string domain #:append "domain <\"" #:postpend "\"> ")
     (variable->string host #:append "host ")
     (variable->string pki #:append "pki ")
     (variable->string srs)
     (variable->string tls #:append "tls ")
     (variable->string auth #:append "auth <" #:postpend "> ")
     (variable->string mail-from #:append "mail-from ")
     (variable->string src #:append "src ")
     "\n")))

(define (opensmtpd-lmtp-configuration->string record)
  (string-append "lmtp "
                 (opensmtpd-lmtp-configuration-destination record)
                 (if (opensmtpd-lmtp-configuration-rcpt-to record)
                     (begin
                       " " (opensmtpd-lmtp-configuration-rcpt-to record))
                     "")))

(define (opensmtpd-mda-configuration->string record)
  (string-append "mda "
                 (opensmtpd-mda-configuration-command record) " "))

(define (opensmtpd-maildir-configuration->string record)
  (string-append "maildir "
                 "\""
                 (if (opensmtpd-maildir-configuration-pathname record)
                     (opensmtpd-maildir-configuration-pathname record)
                     "~/Maildir")
                 "\""
                 (if (opensmtpd-maildir-configuration-junk record)
                     " junk "
                     " ")))

(define (opensmtpd-action-local-delivery-configuration->string record)
  (let ([name (opensmtpd-action-local-delivery-configuration-name record)]
        [method (opensmtpd-action-local-delivery-configuration-method record)]
        [alias (if (opensmtpd-action-local-delivery-configuration-alias record)
                   (opensmtpd-table-configuration-name
                    (opensmtpd-action-local-delivery-configuration-alias record))
                   #f)]
        [ttl (opensmtpd-action-local-delivery-configuration-ttl record)]
        [user (opensmtpd-action-local-delivery-configuration-user record)]
        [userbase (if (opensmtpd-action-local-delivery-configuration-userbase record)
                      (opensmtpd-table-configuration-name
                       (opensmtpd-action-local-delivery-configuration-userbase record))
                      #f)]
        [virtual (if (opensmtpd-action-local-delivery-configuration-virtual record)
                     (opensmtpd-table-configuration-name
                      (opensmtpd-action-local-delivery-configuration-virtual record))
                     #f)]
        [wrapper (opensmtpd-action-local-delivery-configuration-wrapper record)])
    (string-append
     "\"" name "\" "
     (cond [(string? method)
            (string-append method " ")]
           [(opensmtpd-mda-configuration? method)
            (opensmtpd-mda-configuration->string method)]
           [(opensmtpd-lmtp-configuration? method)
            (opensmtpd-lmtp-configuration->string method)]
           [(opensmtpd-maildir-configuration? method)
            (opensmtpd-maildir-configuration->string method)])
     ;; FIXME/TODO support specifying alias file:/path/to/alias-file  ?
     ;; I do not think that is something that I can do...
     (variable->string alias #:append "alias <\"" #:postpend "\"> ")
     (variable->string ttl #:append "ttl ")
     (variable->string user #:append "user ")
     (variable->string userbase #:append "userbase <\"" #:postpend "\"> ")
     (variable->string virtual #:append "virtual <" #:postpend "> ")
     (variable->string wrapper #:append "wrapper "))))

;; this function turns both opensmtpd-action-local-delivery-configuration and
;; opensmtpd-action-relay-configuration into strings.
(define (opensmtpd-action->string record)
  (string-append "action "
                 (cond [(opensmtpd-action-local-delivery-configuration? record)
                        (opensmtpd-action-local-delivery-configuration->string record)]
                       [(opensmtpd-action-relay-configuration? record)
                        (opensmtpd-action-relay-configuration->string record)])
                 " \n"))

;; this turns option records found in <opensmtpd-match-configuration> into strings.
(define* (opensmtpd-option-configuration->string record
                                                 #:key
                                                 (space-after-! #f))
  (let ([not (opensmtpd-option-configuration-not record)]
        [option (opensmtpd-option-configuration-option record)]
        [regex (opensmtpd-option-configuration-regex record)]
        [data (opensmtpd-option-configuration-data record)])
    (string-append
     (if not
         (if space-after-!
             "! "
             "!")
         "")
     option " "
     (if regex
         "regex "
         "")
     (if data
         (if (opensmtpd-table-configuration? data)
             (string-append "<" (opensmtpd-table-configuration-name data) "> ")
             (string-append data " "))
         ""))))

(define (opensmtpd-match-configuration->string record)
  (string-append "match "
                 (let* ([action (opensmtpd-match-configuration-action record)]
                        [name (cond [(opensmtpd-action-relay-configuration? action)
                                     (opensmtpd-action-relay-configuration-name action)]
                                    [(opensmtpd-action-local-delivery-configuration? action)
                                     (opensmtpd-action-local-delivery-configuration-name action)]
                                    [else 'reject])]
                        [options (opensmtpd-match-configuration-options record)])
                   (string-append
                    (if options
                        (apply string-append
                               (map opensmtpd-option-configuration->string options))
                        "")
                    (if (string? name)
                        (string-append "action " "\"" name "\" ")
                        "reject ")
                    "\n"))))

(define (opensmtpd-ca-configuration->string record)
  (string-append "ca " (opensmtpd-ca-configuration-name record) " "
                 "cert \"" (opensmtpd-ca-configuration-file record) "\"\n"))

(define (opensmtpd-pki-configuration->string record)
  (let ([domain (opensmtpd-pki-configuration-domain record)]
        [cert (opensmtpd-pki-configuration-cert record)]
        [key (opensmtpd-pki-configuration-key record)]
        [dhe (opensmtpd-pki-configuration-dhe record)])
    (string-append "pki " domain " " "cert \"" cert "\" \n"
                   "pki " domain " " "key \"" key "\" \n"
                   (if dhe
                       (string-append
                        "pki " domain " " "dhe " dhe "\n")
                       ""))))

(define (generate-filter-chain-name list-of-filters)
  (string-drop-right (apply string-append
                            (flatten
                             (map (lambda (filter)
                                    (list
                                     (if (opensmtpd-filter-configuration? filter)
                                         (opensmtpd-filter-configuration-name filter)
                                         (opensmtpd-filter-phase-configuration-name filter))
                                     "-"))
                                  list-of-filters)))
                     1))

;; this procedure takes in a list of <opensmtpd-filter-configuration> and <opensmtpd-filter-phase-configuration>,
;; returns a string of the form:
;; filter "uniquelyGeneratedName" chain chain { "filter-name", "filter-name2" [, ...]}
(define (opensmtpd-filter-chain->string list-of-filters)
  (string-append "filter \""
                 (generate-filter-chain-name list-of-filters)
                 "\" "
                 "chain {"
                 (string-drop-right
                  (apply string-append
                         (flatten
                          (map (lambda (filter)
                                 (list
                                  "\""
                                  (if (opensmtpd-filter-configuration? filter)
                                      (opensmtpd-filter-configuration-name filter)
                                      (opensmtpd-filter-phase-configuration-name filter))
                                  "\", "))
                               list-of-filters))
                         ) 2)
                 "}\n"))

(define (opensmtpd-filter-phase-configuration->string record)
  (let ([name (opensmtpd-filter-phase-configuration-name record)]
        [phase (opensmtpd-filter-phase-configuration-phase record)]
        [decision (opensmtpd-filter-phase-configuration-decision record)]
        [options (opensmtpd-filter-phase-configuration-options record)]
        [message (opensmtpd-filter-phase-configuration-message record)]
        [value (opensmtpd-filter-phase-configuration-value record)])
    (string-append "filter "
                   "\"" name "\" "
                   "phase " phase " "
                   "match "
                   (apply string-append ; turn the options into a string
                          (flatten
                           (map (lambda (option)
                                  (opensmtpd-option-configuration->string option #:space-after-! #f))
                                options)))
                   " "
                   decision " "
                   (if (string-in-list? decision (list "reject" "disconnect"))
                       (string-append "\"" message "\"")
                       "")
                   (if (string=? "rewrite" decision)
                       (string-append "rewrite " (number->string value))
                       "")
                   "\n")))

;; filters elements may be <opensmtpd-filter-configuration>, <opensmtpd-filter-phase-configuration>,
;; and lists that look like (list (opensmtpd-filter-configuration...) (opensmtpd-filter-phase-configuration ...)
;; ...)
;; this function converts it to a string.
;; Consider if a user passed in a valid <opensmtpd-configuration>, whose total valid filters
;; so that (get-opensmtpd-filters (opensmtpd-configuration)) returns
;; look like this: (we will call this list "total filters"):
;; (list (opensmtpd-filter
;;         (name "rspamd")
;;         (proc "rspamd"))
;;       (list (opensmtpd-filter-phase-configuration ; this is a listen-on, with a filter-chain.
;;               (name "dkimsign")
;;               ...)
;;               (opensmtpd-filter
;;                 (name "rspamd")
;;                 (proc "rspamd"))))
;;
;; did you notice that filter "rspamd" is listed twice?  How do you make sure that it is NOT
;; printed twice in smtpd.conf?
;; 1st flatten "total filters", then remove its duplicates.  Then print all of those filters.
;; 2nd now we go through "total filters", and we only print the non-filter-chains.
(define (opensmtpd-filters->string filters)
  ;; first display the unique <opensmtpd-filter-configuration>s. and <opensmtpd-filter-phase-configuration>s.
  ;; to do this: flatten filters, then remove duplicates.
  (string-append
   (apply string-append
          (map (lambda (filter)
                 (cond ((opensmtpd-filter-phase-configuration? filter)
                        (opensmtpd-filter-phase-configuration->string filter))
                       (else            ; you are a <opensmtpd-filter-configuration>
                        (string-append "filter "
                                       "\"" (opensmtpd-filter-configuration-name filter) "\" "
                                       (if (opensmtpd-filter-exec filter)
                                           "proc-exec "
                                           "proc ")
                                       "\"" (opensmtpd-filter-configuration-proc filter) "\""
                                       "\n"))))
               (delete-duplicates (flatten filters))))
   ;; now we have to print the filter chains.
   (apply string-append
          (remove boolean?
                  (map (lambda (filter)
                         (cond ((list? filter)
                                (opensmtpd-filter-chain->string filter))
                               (else    ; you are a <opensmtpd-filter-configuration>
                                #f)))
                       filters)))))

(define (opensmtpd-configuration-listen->string string)
  (string-append
   "include \"" string "\"\n"))

(define (opensmtpd-configuration-srs->string record)
  (let ([key (opensmtpd-srs-configuration-key record)]
        [backup-key (opensmtpd-srs-configuration-backup-key record)]
        [ttl-delay (opensmtpd-srs-configuration-ttl-delay record)])
    (string-append
     (variable->string key #:append "srs key " #:postpend "\n")
     (variable->string backup-key #:append "srs key backup " #:postpend "\n")
     (variable->string ttl-delay #:append "srs ttl " #:postpend "\n")
     "\n")))

;; TODO make sure all options here work!  I just fixed limit-max-rcpt!
(define (opensmtpd-smtp-configuration->string record)
  (let ([ciphers (opensmtpd-smtp-configuration-ciphers record)]
        [limit-max-mails (opensmtpd-smtp-configuration-limit-max-mails record)]
        [limit-max-rcpt (opensmtpd-smtp-configuration-limit-max-rcpt record)]
        [max-message-size (opensmtpd-smtp-configuration-max-message-size record)]
        [sub-addr-delim (opensmtpd-smtp-configuration-sub-addr-delim record)])
    (string-append
     (variable->string ciphers #:append "smtp ciphers " #:postpend "\n")
     (variable->string limit-max-mails #:append "smtp limit max-mails " #:postpend "\n")
     (variable->string limit-max-rcpt #:append "smtp limit max-rcpt " #:postpend "\n")
     (variable->string max-message-size #:append "smtp max-message-size " #:postpend "\n")
     (variable->string sub-addr-delim #:append "smtp sub-addr-delim " #:postpend "\n")
     "\n")))

(define (opensmtpd-configuration-queue->string record)
  (let ([compression (opensmtpd-queue-configuration-compression record)]
        [encryption (opensmtpd-queue-configuration-encryption record)]
        [ttl-delay (opensmtpd-queue-configuration-ttl-delay record)])
    (string-append
     (if compression
         "queue compression\n"
         "")
     (if encryption
         (string-append
          "queue encryption "
          (if (not (boolean? encryption))
              encryption
              "")
          "\n")
         "")
     (if ttl-delay
         (string-append "queue ttl" ttl-delay "\n")
         ""))))

;; build a list of <opensmtpd-action> from
;; opensmtpd-configuration-matches, which is a list of <opensmtpd-match-configuration>.
;; Each <opensmtpd-match-configuration> has a fieldname 'action', which accepts an <opensmtpd-action>.
(define (get-opensmtpd-actions record)
  (define opensmtpd-actions
    (let loop ([list (opensmtpd-configuration-matches record)])
      (if (null? list)
          '()
          (cons (opensmtpd-match-configuration-action (car list))
                (loop (cdr list))))))
  (delete-duplicates (append opensmtpd-actions)))

;; build a list of opensmtpd-pki-configurations from
;; opensmtpd-configuration-listen-ons and
;; get-opensmtpd-actions
(define (get-opensmtpd-pki-configurations record)
  ;; TODO/FIXME/maybe/wishlist could get-opensmtpd-actions -> NOT have an opensmtpd-action-relay-configuration?
  ;; I think so.  And if it did NOT have a relay configuration, then action-pkis would be '() when
  ;; it needs to be #f.  because if the opensmtpd-configuration has NO pkis, then this function will
  ;; return '(), when it should return #f.  If it returns '(), then opensmtpd-configuration-fieldname->string will
  ;; print the string "\n" instead of ""
  (define action-pkis
    (let loop1 ([list (get-opensmtpd-actions record)])
      (if (null? list)
          '()
          (if (and (opensmtpd-action-relay-configuration? (car list))
                   (opensmtpd-action-relay-configuration-pki (car list)))
              (cons (opensmtpd-action-relay-configuration-pki (car list))
                    (loop1 (cdr list)))
              (loop1 (cdr list))))))
  ;; FIXME/TODO/maybe/wishlist
  ;; this could be #f aka left blank. aka there are no listen-ons records with pkis.
  ;; aka there are no lines in the configuration like:
  ;; listen on eth0 tls pki smtp.gnucode.me in that case the smtpd.conf will have an extra "\n"
  (define listen-on-pkis
    (let loop2 ([list (opensmtpd-configuration-listen-ons record)])
      (if (null? list)
          '()
          (if (opensmtpd-listen-on-configuration-pki (car list))
              (cons (opensmtpd-listen-on-configuration-pki (car list))
                    (loop2 (cdr list)))
              (loop2 (cdr list))))))
  (delete-duplicates (append action-pkis listen-on-pkis)))

;; takes in a <opensmtpd-configuration> and returns a list whose elements are <opensmtpd-filter-configuration>,
;; <opensmtpd-filter-phase-configuration>, and a filter-chain.
;; It returns a list of <opensmtpd-filter-configuration> and/or <opensmtpd-filter-phase-configuration>
;; here's an example of what this procedure might return:
;; (list (opensmtpd-filter-configuration...) (opensmtpd-filter-phase-configuration ...)
;;       (openmstpd-filter ...) (opensmtpd-filter-phase-configuration ...)
;;       ;; this next list is a filter-chain.
;;       (list (opensmtpd-filter-phase-configuration ...) (opensmtpd-filter-configuration...)))
;;
;; This procedure handles filter chains a little odd.
(define (get-opensmtpd-filters record)
  (define list-of-listen-on-records (if (opensmtpd-configuration-listen-ons record)
                                        (opensmtpd-configuration-listen-ons record)
                                        '()))

  (define listen-on-socket-filters
    (if (opensmtpd-listen-on-socket-configuration-configuration-filters (opensmtpd-configuration-listen-on-socket record))
        (opensmtpd-listen-on-socket-configuration-configuration-filters (opensmtpd-configuration-listen-on-socket record))
        '()))

    (delete-duplicates
     (append (remove boolean?
                     (map-in-order (lambda (listen-on-record) ; get the filters found in the <listen-on-record>s
                                     (if (and (opensmtpd-listen-on-configuration-filters listen-on-record)
                                              (= 1 (length (opensmtpd-listen-on-configuration-filters
                                                            listen-on-record))))
                                         (car (opensmtpd-listen-on-configuration-filters listen-on-record))
                                         (opensmtpd-listen-on-configuration-filters listen-on-record)))
                                   list-of-listen-on-records))
             listen-on-socket-filters)))

(define (flatten . lst)
  "Return a list that recursively concatenates all sub-lists of LST."
  (define (flatten1 head out)
    (if (list? head)
        (fold-right flatten1 out head)
        (cons head out)))
  (fold-right flatten1 '() lst))

;; This function takes in a record, or list, or anything, and returns
;; a list of <opensmtpd-table-configuration>s assuming the thing you passed into it had
;; any <opensmtpd-table-configuration>s.
;;
;; is object record? call func on it's fieldnames
;; is object list? loop through it's fieldnames calling func on it's records
;; is object #f or string? or '()? -> #f
(define (get-opensmtpd-tables value)
  (delete-duplicates
   (remove boolean? (flatten ;; turn (list '(1) '(2 '(3))) -> '(1 2 3)
               (cond ((opensmtpd-table-configuration? value)
                      value)
                     ((record? value)
                      (let* ([record-type (record-type-descriptor value)]
                             [list-of-record-fieldnames (record-type-fields record-type)])
                        (map (lambda (fieldname)
                               (get-opensmtpd-tables ((record-accessor record-type fieldname) value)))
                             list-of-record-fieldnames)))
                     ((and (list? value) (not (null? value)))
                      (map get-opensmtpd-tables value))
                     (else #f))))))

(define (opensmtpd-configuration-fieldname->string record fieldname-accessor record->string)
  (if (fieldname-accessor record)
      (begin
        (string-append
         (list-of-records->string (fieldname-accessor record) record->string) "\n"))
      ""))

(define (list-of-records->string list-of-records record->string)
  (string-append
   (cond [(not (list? list-of-records))
          (record->string list-of-records)]
         [else
          (let loop ([list list-of-records])
            (if (null? list)
                ""
                (string-append
                 (record->string (car list))
                 (loop (cdr list)))))])))


;; FIXME/TODO should I use format here srfi-28 ?
;; web.scm nginx does a (format #f "string" "another string")
;; this could be a list like (list (file-append opensmtpd-dkimsign "/libexec/filter") "-d gnucode.me -s /path/to/selector.cert")
;; Then opensmtpd-configuration->mixed-text-file could be rewritten to be something like
;; (mixed-text-file (eval `(string-append (opensmtpd-configuration-fieldname->string ...)) (gnu services mail)))
(define (opensmtpd-configuration->mixed-text-file record)
  ;; should I use this named let, or should I give this a name, or not use it at all...
  ;; eg: (write-all-fieldnames (list (cons fieldname fieldname->string) (cons fieldname2 fieldname->string)))
  ;; (let loop ([list (list (cons opensmtpd-configuration-includes (lambda (string)
  ;;                                                                 (string-append
  ;;                                                                  "include \"" string "\"\n")))
  ;;                        (cons opensmtpd-configuration-smtp opensmtpd-smtp->string)
  ;;                        (cons opensmtpd-configuration-srs opensmtpd-srs->string))])
  ;;   (if (null? list)
  ;;       ""
  ;;       (string-append (opensmtpd-configuration-fieldname->string record
  ;;                                                                 (caar list)
  ;;                                                                 (cdar list))
  ;;                      (loop (cdr list)))))

  ;;(mixed-text-file "opensmtpd.conf")
  (string-append
   ;; write out the includes
   (opensmtpd-configuration-fieldname->string record opensmtpd-configuration-includes
                                              opensmtpd-configuration-listen->string)
   (opensmtpd-configuration-fieldname->string record opensmtpd-configuration-bounce
                                              (lambda (%bounce)
                                                (if %bounce
                                                    (list-of-strings->string %bounce)
                                                    "")))
   (opensmtpd-configuration-fieldname->string record opensmtpd-configuration-smtp
                                              opensmtpd-smtp-configuration->string)
   (opensmtpd-configuration-fieldname->string record opensmtpd-configuration-srs
                                              opensmtpd-configuration-srs->string)
   (opensmtpd-configuration-fieldname->string record opensmtpd-configuration-queue
                                              opensmtpd-configuration-queue->string)
   ;; write out the mta-max-deferred
   (opensmtpd-configuration-fieldname->string
    record opensmtpd-configuration-mta-max-deferred
    (lambda (var)
      (string-append "mta max-deferred "
                     (number->string (opensmtpd-configuration-mta-max-deferred record)) "\n")))
   ;;write out all the tables
   (opensmtpd-configuration-fieldname->string record get-opensmtpd-tables opensmtpd-table-configuration->string)
   ;; TODO should I change the below line of code into these two lines of code?
   ;;(opensmtpd-configuration-fieldname->string record get-opensmtpd-filters-and-filter-phases opensmtpd-filter-and-filter-phase->string)
   ;;(opensmtpd-configuration-fieldname->string record get-opensmtpd-filter-chains opensmtpd-filter-chain->string)
   ;; write out all the filters
   (opensmtpd-filters->string (get-opensmtpd-filters record))
   ;; write out all the cas
   (opensmtpd-configuration-fieldname->string record opensmtpd-configuration-cas opensmtpd-ca-configuration->string)
   ;; write out all the pkis
   (opensmtpd-configuration-fieldname->string record get-opensmtpd-pki-configurations opensmtpd-pki-configuration->string)
   ;; write all of the listen-on-records
   (opensmtpd-configuration-fieldname->string record opensmtpd-configuration-listen-ons
                                              opensmtpd-listen-on-configuration->string)
   (opensmtpd-configuration-fieldname->string record opensmtpd-configuration-listen-on-socket
                                              opensmtpd-listen-on-socket-configuration->string)
   ;; write all the actions
   (opensmtpd-configuration-fieldname->string record get-opensmtpd-actions
                                              opensmtpd-action->string)
   ;; write all of the matches
   (opensmtpd-configuration-fieldname->string record opensmtpd-configuration-matches opensmtpd-match-configuration->string)))


(define %default-opensmtpd-config-file
  (plain-file "smtpd.conf" "
listen on lo

action inbound mbox
match for local action inbound

action outbound relay
match from local for any action outbound
"))

(define opensmtpd-shepherd-service
  (match-lambda
    (($ <opensmtpd-configuration> package config-file)
     (list (shepherd-service
            (provision '(smtpd))
            (requirement '(loopback))
            (documentation "Run the OpenSMTPD daemon.")
            (start (let ((smtpd (file-append package "/sbin/smtpd")))
                     #~(make-forkexec-constructor
                        (list #$smtpd "-f" #$config-file)
                        #:pid-file "/var/run/smtpd.pid")))
            (stop #~(make-kill-destructor)))))))

(define %opensmtpd-accounts
  (list (user-group
         (name "smtpq")
         (system? #t))
        (user-account
         (name "smtpd")
         (group "nogroup")
         (system? #t)
         (comment "SMTP Daemon")
         (home-directory "/var/empty")
         (shell (file-append shadow "/sbin/nologin")))
        (user-account
         (name "smtpq")
         (group "smtpq")
         (system? #t)
         (comment "SMTPD Queue")
         (home-directory "/var/empty")
         (shell (file-append shadow "/sbin/nologin")))))

(define opensmtpd-activation
  (match-lambda
    (($ <opensmtpd-configuration> package config-file)
     (let ((smtpd (file-append package "/sbin/smtpd")))
       #~(begin
           (use-modules (guix build utils))
           ;; Create mbox and spool directories.
           (mkdir-p "/var/mail")
           (mkdir-p "/var/spool/smtpd")
           (chmod "/var/spool/smtpd" #o711)
           (mkdir-p "/var/spool/mail")
           (chmod "/var/spool/mail" #o711))))))

(define %opensmtpd-pam-services
  (list (unix-pam-service "smtpd")))

(define opensmtpd-service-type
  (service-type
   (name 'opensmtpd)
   (extensions
    (list (service-extension account-service-type
                             (const %opensmtpd-accounts))
          (service-extension activation-service-type
                             opensmtpd-activation)
          (service-extension pam-root-service-type
                             (const %opensmtpd-pam-services))
          (service-extension profile-service-type
                             (compose list opensmtpd-configuration-package))
          (service-extension shepherd-root-service-type
                             opensmtpd-shepherd-service)))
   (description "Run the OpenSMTPD, a lightweight @acronym{SMTP, Simple Mail
Transfer Protocol} server.")))

\f
;;;
;;; mail aliases.
;;;

(define (mail-aliases-etc aliases)
  `(("aliases" ,(plain-file "aliases"
                            ;; Ideally we'd use a format string like
                            ;; "~:{~a: ~{~a~^,~}\n~}", but it gives a
                            ;; warning that I can't figure out how to fix,
                            ;; so we'll just use string-join below instead.
                            (format #f "~:{~a: ~a\n~}"
                                    (map (match-lambda
                                           ((alias addresses ...)
                                            (list alias (string-join addresses ","))))
                                         aliases))))))

(define mail-aliases-service-type
  (service-type
   (name 'mail-aliases)
   (extensions
    (list (service-extension etc-service-type mail-aliases-etc)))
   (compose concatenate)
   (extend append)
   (description "Provide a @file{/etc/aliases} file---an email alias
database---computed from the given alias list.")))

\f
;;;
;;; Exim.
;;;

(define-record-type* <exim-configuration> exim-configuration
  make-exim-configuration
  exim-configuration?
  (package       exim-configuration-package ;file-like
                 (default exim))
  (config-file   exim-configuration-config-file ;file-like
                 (default #f)))

(define %exim-accounts
  (list (user-group
         (name "exim")
         (system? #t))
        (user-account
         (name "exim")
         (group "exim")
         (system? #t)
         (comment "Exim Daemon")
         (home-directory "/var/empty")
         (shell (file-append shadow "/sbin/nologin")))))

(define (exim-computed-config-file package config-file)
  (computed-file "exim.conf"
                 #~(call-with-output-file #$output
                     (lambda (port)
                       (format port "
exim_user = exim
exim_group = exim
.include ~a"
                               #$(or config-file
                                     (file-append package "/etc/exim.conf")))))))

(define exim-shepherd-service
  (match-lambda
    (($ <exim-configuration> package config-file)
     (list (shepherd-service
            (provision '(exim mta))
            (documentation "Run the exim daemon.")
            (requirement '(networking))
            (start #~(make-forkexec-constructor
                      '(#$(file-append package "/bin/exim")
                        "-bd" "-v" "-C"
                        #$(exim-computed-config-file package config-file))))
            (stop #~(make-kill-destructor)))))))

(define exim-activation
  (match-lambda
    (($ <exim-configuration> package config-file)
     (with-imported-modules '((guix build utils))
       #~(begin
           (use-modules (guix build utils))

           (let ((uid (passwd:uid (getpw "exim")))
                 (gid (group:gid (getgr "exim"))))
             (mkdir-p "/var/spool/exim")
             (chown "/var/spool/exim" uid gid))

           (zero? (system* #$(file-append package "/bin/exim")
                           "-bV" "-C" #$(exim-computed-config-file package config-file))))))))

(define exim-profile
  (compose list exim-configuration-package))

(define exim-service-type
  (service-type
   (name 'exim)
   (extensions
    (list (service-extension shepherd-root-service-type exim-shepherd-service)
          (service-extension account-service-type (const %exim-accounts))
          (service-extension activation-service-type exim-activation)
          (service-extension profile-service-type exim-profile)
          (service-extension mail-aliases-service-type (const '()))))
   (description "Run the Exim mail transfer agent (MTA).")))

\f
;;;
;;; GNU Mailutils IMAP4 Daemon.
;;;

(define %default-imap4d-config-file
  (plain-file "imap4d.conf" "server localhost {};\n"))

(define-record-type* <imap4d-configuration>
  imap4d-configuration make-imap4d-configuration imap4d-configuration?
  (package     imap4d-configuration-package
               (default mailutils))
  (config-file imap4d-configuration-config-file
               (default %default-imap4d-config-file)))

(define imap4d-shepherd-service
  (match-lambda
    (($ <imap4d-configuration> package config-file)
     (list (shepherd-service
            (provision '(imap4d))
            (requirement '(networking syslogd))
            (documentation "Run the imap4d daemon.")
            (start (let ((imap4d (file-append package "/sbin/imap4d")))
                     #~(make-forkexec-constructor
                        (list #$imap4d "--daemon" "--foreground"
                              "--config-file" #$config-file))))
            (stop #~(make-kill-destructor)))))))

(define imap4d-service-type
  (service-type
   (name 'imap4d)
   (description
    "Run the GNU @command{imap4d} to serve e-mail messages through IMAP.")
   (extensions
    (list (service-extension
           shepherd-root-service-type imap4d-shepherd-service)))
   (default-value (imap4d-configuration))))

\f
;;;
;;; Radicale.
;;;

(define-record-type* <radicale-configuration>
  radicale-configuration make-radicale-configuration
  radicale-configuration?
  (package     radicale-configuration-package
               (default radicale))
  (config-file radicale-configuration-config-file
               (default %default-radicale-config-file)))

(define %default-radicale-config-file
  (plain-file "radicale.conf" "
[auth]
type = htpasswd
htpasswd_filename = /var/lib/radicale/users
htpasswd_encryption = plain

[server]
hosts = localhost:5232"))

(define %radicale-accounts
  (list (user-group
         (name "radicale")
         (system? #t))
        (user-account
         (name "radicale")
         (group "radicale")
         (system? #t)
         (comment "Radicale Daemon")
         (home-directory "/var/empty")
         (shell (file-append shadow "/sbin/nologin")))))

(define radicale-shepherd-service
  (match-lambda
    (($ <radicale-configuration> package config-file)
     (list (shepherd-service
            (provision '(radicale))
            (documentation "Run the radicale daemon.")
            (requirement '(networking))
            (start #~(make-forkexec-constructor
                      (list #$(file-append package "/bin/radicale")
                        "-C" #$config-file)
                      #:user "radicale"
                      #:group "radicale"))
            (stop #~(make-kill-destructor)))))))

(define radicale-activation
  (match-lambda
    (($ <radicale-configuration> package config-file)
     (with-imported-modules '((guix build utils))
       #~(begin
           (use-modules (guix build utils))
           (let ((uid (passwd:uid (getpw "radicale")))
                 (gid (group:gid (getgr "radicale"))))
             (mkdir-p "/var/lib/radicale/collections")
             (chown "/var/lib/radicale" uid gid)
             (chown "/var/lib/radicale/collections" uid gid)
             (chmod "/var/lib/radicale" #o700)))))))

(define radicale-service-type
  (service-type
   (name 'radicale)
   (description "Run radicale, a small CalDAV and CardDAV server.")
   (extensions
    (list (service-extension shepherd-root-service-type radicale-shepherd-service)
          (service-extension account-service-type (const %radicale-accounts))
          (service-extension activation-service-type radicale-activation)))
   (default-value (radicale-configuration))))

debug log:

solving bdc0ee3bf7 ...
found bdc0ee3bf7 in https://yhetil.org/guix-patches/20220617214618.12377-1-jbranso@dismail.de/
found d99743ac31 in https://git.savannah.gnu.org/cgit/guix.git
preparing index
index prepared:
100644 d99743ac3111771278e1771afe20f5afa1b6a1d6	gnu/services/mail.scm

applying [1/1] https://yhetil.org/guix-patches/20220617214618.12377-1-jbranso@dismail.de/
diff --git a/gnu/services/mail.scm b/gnu/services/mail.scm
index d99743ac31..bdc0ee3bf7 100644

Checking patch gnu/services/mail.scm...
Applied patch gnu/services/mail.scm cleanly.

index at:
100644 bdc0ee3bf71eff9fd17edd1597b1a3aa1a5629c6	gnu/services/mail.scm

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this public inbox

	https://git.savannah.gnu.org/cgit/guix.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).