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
|
// <copyright file="Options.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ Copyright (c) JP Dillingham.
// │
// │ This program is free software: you can redistribute it and/or modify
// │ it under the terms of the GNU Affero General Public License as published
// │ by the Free Software Foundation, version 3.
// │
// │ This program 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 Affero General Public License for more details.
// │
// │ You should have received a copy of the GNU Affero General Public License
// │ along with this program. If not, see https://www.gnu.org/licenses/.
// │
// │ This program is distributed with Additional Terms pursuant to Section 7
// │ of the AGPLv3. See the LICENSE file in the root directory of this
// │ project for the complete terms and conditions.
// │
// │ https://slskd.org
// │
// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
// │ SPDX-FileCopyrightText: JP Dillingham
// │ SPDX-License-Identifier: AGPL-3.0-only
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
// </copyright>
using Microsoft.Extensions.Options;
namespace slskd
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using FluentFTP;
using NetTools;
using slskd.Authentication;
using slskd.Configuration;
using slskd.Events;
using slskd.Relay;
using slskd.Shares;
using slskd.Transfers;
using slskd.Validation;
using Utility.CommandLine;
using Utility.EnvironmentVariables;
using YamlDotNet.Serialization;
using SoulseekDiagnostics = Soulseek.Diagnostics;
/// <summary>
/// Disambiguates options derived at startup from options that may update at run time.
/// </summary>
/// <remarks>
/// This class is added directly to dependency injection, but <see cref="Options"/> is not, so consumers must inject <see cref="OptionsAtStartup"/>
/// instead of <see cref="Options"/> to make it clear that these options will not change. Options that may change should be accessed by injecting
/// <see cref="IOptionsMonitor{T}"/> or <see cref="IOptionsSnapshot{T}"/>, depending on the lifetime of the component.
/// </remarks>
public class OptionsAtStartup : Options
{
}
/// <summary>
/// Application options.
/// </summary>
/// <remarks>
/// <para>
/// This class contains all application options, which may be sourced from (in order of precedence):
/// <list type="bullet">
/// <item>
/// <term>Defaults</term>
/// <description>Default values, statically defined in this class.</description>
/// </item>
/// <item>
/// <term>Environment Variables</term>
/// <description>Environment variables set at either the system or user scope.</description>
/// </item>
/// <item>
/// <term>YAML Configuration File</term>
/// <description>A YAML file containing a mapping of this class.</description>
/// </item>
/// <item>
/// <term>Command Line</term>
/// <description>Options provided via the command line when starting the application.</description>
/// </item>
/// </list>
/// </para>
/// <para>
/// Only the YAML configuration source can change at runtime and consumers of this class must be aware of this, either injecting
/// <see cref="IOptionsMonitor{T}"/> in components with a singleton lifetime, or <see cref="IOptionsSnapshot{T}"/> for transient or scoped lifetimes.
/// </para>
/// <para>
/// To obtain the Options specified at startup (discarding any updates that may have been applied since), inject <see cref="OptionsAtStartup"/>.
/// </para>
/// <para>
/// Options specified via the command line can not be overwritten by changes to the YAML file. This is by design due to the immutable
/// nature of the command line string after the application is started.
/// </para>
/// </remarks>
public class Options : IValidatableObject
{
/// <summary>
/// Gets a value indicating whether to display the application version.
/// </summary>
[Argument('v', "version")]
[Description("display version information")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
[YamlIgnore]
public bool ShowVersion { get; init; } = false;
/// <summary>
/// Gets a value indicating whether to display a list of command line arguments.
/// </summary>
[Argument('h', "help")]
[Description("display command line usage")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
[YamlIgnore]
public bool ShowHelp { get; init; } = false;
/// <summary>
/// Gets a value indicating whether to display a list of configuration environment variables.
/// </summary>
[Argument(default, "envars")]
[Description("display environment variables")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
[YamlIgnore]
public bool ShowEnvironmentVariables { get; init; } = false;
/// <summary>
/// Gets a value indicating whether to generate an X509 certificate and password.
/// </summary>
[Argument(default, "generate-cert")]
[Description("generate X509 certificate and password for HTTPS")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
[YamlIgnore]
public bool GenerateCertificate { get; init; } = false;
/// <summary>
/// Gets a value indicating whether to generate a random secret.
/// </summary>
[Argument(default, "generate-secret")]
[Description("generate random secret of the specified length")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
[YamlIgnore]
public bool GenerateSecret { get; init; } = false;
/// <summary>
/// Gets a value indicating whether the application should run in debug mode.
/// </summary>
[Argument('d', "debug")]
[EnvironmentVariable("DEBUG")]
[Description("run in debug mode")]
[RequiresRestart]
public bool Debug { get; init; } = Debugger.IsAttached;
/// <summary>
/// Gets a value indicating whether the application should run in headless (no web UI) mode.
/// </summary>
[Argument('H', "headless")]
[EnvironmentVariable("HEADLESS")]
[Description("run in headless (no web UI) mode")]
[RequiresRestart]
public bool Headless { get; init; } = false;
/// <summary>
/// Gets a value indicating whether remote configuration of options is allowed.
/// </summary>
[Argument(default, "remote-configuration")]
[EnvironmentVariable("REMOTE_CONFIGURATION")]
[Description("allow remote configuration")]
public bool RemoteConfiguration { get; init; } = false;
/// <summary>
/// Gets a value indicating whether remote file management is allowed.
/// </summary>
[Argument(default, "remote-file-management")]
[EnvironmentVariable("REMOTE_FILE_MANAGEMENT")]
[Description("allow remote file management")]
public bool RemoteFileManagement { get; init; } = false;
/// <summary>
/// Gets the unique name for this instance.
/// </summary>
[Argument('i', "instance-name")]
[EnvironmentVariable("INSTANCE_NAME")]
[Description("optional; a unique name for this instance")]
[RequiresRestart]
public string InstanceName { get; init; } = "default";
/// <summary>
/// Gets optional flags.
/// </summary>
[Validate]
public FlagsOptions Flags { get; init; } = new FlagsOptions();
/// <summary>
/// Gets the path where application data is saved.
/// </summary>
[Argument('a', "app-dir")]
[EnvironmentVariable("APP_DIR")]
[Description("path where application data is saved")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
[YamlIgnore]
public string AppDirectory { get; init; } = Program.DefaultAppDirectory;
/// <summary>
/// Gets the path where application data is saved.
/// </summary>
[Argument('c', "config")]
[EnvironmentVariable("CONFIG")]
[Description("path to configuration file")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
[YamlIgnore]
public string ConfigurationFile { get; init; } = Program.DefaultConfigurationFile;
/// <summary>
/// Gets relay options.
/// </summary>
[Validate]
public RelayOptions Relay { get; init; } = new RelayOptions();
[Obsolete("temporary sentinel to warn users about breaking change. use Transfers.Download.Destination.Permissions instead.")]
public object Permissions { get; init; } = null;
/// <summary>
/// Gets directory options.
/// </summary>
[Validate]
[RequiresRestart]
public DirectoriesOptions Directories { get; init; } = new DirectoriesOptions();
/// <summary>
/// Gets share options.
/// </summary>
[Validate]
public SharesOptions Shares { get; init; } = new SharesOptions();
[Obsolete("temporary sentinel to warn users about breaking change. use Transfers instead.")]
public object Global { get; init; } = null;
[Obsolete("temporary sentinel to warn users about breaking change. use Transfers instead.")]
public object Groups { get; init; } = null;
/// <summary>
/// Gets transfer options.
/// </summary>
[Validate]
public TransfersOptions Transfers { get; init; } = new TransfersOptions();
/// <summary>
/// Gets blacklist options.
/// </summary>
[Validate]
public BlacklistOptions Blacklist { get; init; } = new BlacklistOptions();
/// <summary>
/// Gets filter options.
/// </summary>
[Validate]
public FiltersOptions Filters { get; init; } = new FiltersOptions();
/// <summary>
/// Gets a list of rooms to automatically join upon connection.
/// </summary>
[Argument(default, "rooms")]
[EnvironmentVariable("ROOMS")]
[Description("a list of rooms to automatically join")]
public string[] Rooms { get; init; } = Array.Empty<string>();
/// <summary>
/// Gets options for the web UI.
/// </summary>
[Validate]
public WebOptions Web { get; init; } = new WebOptions();
/// <summary>
/// Gets retention options.
/// </summary>
[Validate]
public RetentionOptions Retention { get; init; } = new RetentionOptions();
/// <summary>
/// Gets throttling options.
/// </summary>
[Validate]
public ThrottlingOptions Throttling { get; init; } = new ThrottlingOptions();
/// <summary>
/// Gets logger options.
/// </summary>
[Validate]
[RequiresRestart]
public LoggerOptions Logger { get; init; } = new LoggerOptions();
/// <summary>
/// Gets metrics options.
/// </summary>
[Validate]
[RequiresRestart]
public MetricsOptions Metrics { get; init; } = new MetricsOptions();
/// <summary>
/// Gets feature options.
/// </summary>
[Validate]
[RequiresRestart]
public FeatureOptions Feature { get; init; } = new FeatureOptions();
/// <summary>
/// Gets options for the Soulseek client.
/// </summary>
[Validate]
public SoulseekOptions Soulseek { get; init; } = new SoulseekOptions();
[Obsolete("temporary sentinel to warn users about breaking change. use Integrations instead.")]
public object Integration { get; init; } = null;
/// <summary>
/// Gets options for external integrations.
/// </summary>
[Validate]
public IntegrationsOptions Integrations { get; init; } = new IntegrationsOptions();
/// <summary>
/// Handles top-level validation that doesn't fit anywhere else.
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (InstanceName == Program.LocalHostName && Relay.Mode.ToEnum<RelayMode>() == RelayMode.Agent)
{
results.Add(new ValidationResult($"Instance name must be something other than '{Program.LocalHostName}' when operating in Relay Agent mode"));
}
#pragma warning disable CS0618 // Type or member is obsolete
if (Groups is not null || Global is not null)
{
results.Add(new ValidationResult("The 'global' and 'groups' keys have been moved under a new 'transfers' key. See https://github.com/slskd/slskd/pull/1672 for details, and make the necessary changes to remove this error"));
}
if (Integration is not null)
{
results.Add(new ValidationResult("The 'integration' key has been renamed to 'integrations'. Add an 's' to the end of the key to remove this error (no other changes were made)"));
}
if (Permissions is not null)
{
results.Add(new ValidationResult("The 'permissions' keys have been moved under a new 'destination' key under transfers -> download, and the behavior has changed. See https://github.com/slskd/slskd/pull/1756 for details"));
}
#pragma warning restore CS0618 // Type or member is obsolete
return results;
}
/// <summary>
/// Optional flags.
/// </summary>
public class FlagsOptions
{
/// <summary>
/// Gets a value indicating whether the logo should be suppressed on startup.
/// </summary>
[Argument('n', "no-logo")]
[EnvironmentVariable("NO_LOGO")]
[Description("suppress logo on startup")]
[RequiresRestart]
public bool NoLogo { get; init; } = false;
/// <summary>
/// Gets a value indicating whether the application should quit after initialization.
/// </summary>
[Argument('x', "no-start")]
[EnvironmentVariable("NO_START")]
[Description("quit the application after initialization")]
[RequiresRestart]
public bool NoStart { get; init; } = false;
/// <summary>
/// Gets a value indicating whether the application should watch the configuration file for changes.
/// </summary>
[Argument(default, "no-config-watch")]
[EnvironmentVariable("NO_CONFIG_WATCH")]
[Description("do not watch the config file for changes")]
[RequiresRestart]
public bool NoConfigWatch { get; init; } = false;
/// <summary>
/// Gets a value indicating whether the application should connect to the Soulseek network on startup.
/// </summary>
[Argument(default, "no-connect")]
[EnvironmentVariable("NO_CONNECT")]
[Description("do not connect to the Soulseek network on startup")]
[RequiresRestart]
public bool NoConnect { get; init; } = false;
/// <summary>
/// Gets a value indicating whether the application should scan shared directories on startup.
/// </summary>
[Argument(default, "no-share-scan")]
[EnvironmentVariable("NO_SHARE_SCAN")]
[Description("do not scan shares on startup")]
[RequiresRestart]
public bool NoShareScan { get; init; } = false;
/// <summary>
/// Gets a value indicating whether shares should be forcibly re-scanned on startup.
/// </summary>
[Argument(default, "force-share-scan")]
[EnvironmentVariable("FORCE_SHARE_SCAN")]
[Description("force a share scan on startup")]
[RequiresRestart]
public bool ForceShareScan { get; init; } = false;
/// <summary>
/// Gets a value indicating whether to force database migrations to be applied on startup.
/// </summary>
[Argument(default, "force-migrations")]
[EnvironmentVariable("FORCE_MIGRATIONS")]
[Description("force database migrations to be applied on startup")]
public bool ForceMigrations { get; init; } = false;
/// <summary>
/// Gets a value indicating whether the application should check for a newer version on startup.
/// </summary>
[Argument(default, "no-version-check")]
[EnvironmentVariable("NO_VERSION_CHECK")]
[Description("do not check for newer version at startup")]
[RequiresRestart]
public bool NoVersionCheck { get; init; } = false;
/// <summary>
/// Gets a value indicating whether Entity Framework queries should be logged.
/// </summary>
[Argument(default, "log-sql")]
[EnvironmentVariable("LOG_SQL")]
[Description("log SQL queries generated by Entity Framework")]
[RequiresRestart]
public bool LogSQL { get; init; } = false;
/// <summary>
/// Gets a value indicating whether to log unobserved Exceptions.
/// </summary>
[Argument(default, "log-unobserved-exceptions")]
[EnvironmentVariable("LOG_UNOBSERVED_EXCEPTIONS")]
[Description("log unobserved exceptions (caution: verbose)")]
[RequiresRestart]
public bool LogUnobservedExceptions { get; init; } = false;
/// <summary>
/// Gets a value indicating whether the application should run in experimental mode.
/// </summary>
[Argument(default, "experimental")]
[EnvironmentVariable("EXPERIMENTAL")]
[Description("run in experimental mode")]
[RequiresRestart]
public bool Experimental { get; init; } = false;
/// <summary>
/// Gets a value indicating whether the application should run in volatile mode.
/// </summary>
[Argument(default, "volatile")]
[EnvironmentVariable("VOLATILE")]
[Description("use volatile data storage (all data will be lost at shutdown)")]
[RequiresRestart]
public bool Volatile { get; init; } = false;
/// <summary>
/// Gets a value indicating whether user-defined regular expressions are case sensitive.
/// </summary>
[Argument(default, "case-sensitive-regex")]
[EnvironmentVariable("CASE_SENSITIVE_REGEX")]
[Description("user-defined regular expressions are case sensitive")]
[RequiresRestart]
public bool CaseSensitiveRegEx { get; init; } = false;
/// <summary>
/// Gets a value indicating whether to use legacy TCP keepalive options, for Windows
/// versions prior to Windows 10, version 1709 (and associated Server SKUs).
/// </summary>
[Argument(default, "legacy-windows-tcp-keepalive")]
[EnvironmentVariable("LEGACY_WINDOWS_TCP_KEEPALIVE")]
[Description("use a legacy TCP keepalive strategy for older Windows versions")]
public bool LegacyWindowsTcpKeepalive { get; init; } = false;
/// <summary>
/// Gets a value indicating whether to use the uploaded shares from Relay agents as the source of
/// truth for file existence and size, instead of querying the agent prior to enqueueing the file.
/// </summary>
[Argument(default, "optimistic-relay-file-info")]
[EnvironmentVariable("OPTIMISTIC_RELAY_FILE_INFO")]
[Description("use uploaded relay shares as source of truth for file existence and size")]
public bool OptimisticRelayFileInfo { get; init; } = false;
/// <summary>
/// Gets a value indicating whether SQLite pooling should be disabled.
/// </summary>
[Argument(default, "no-sqlite-pooling")]
[EnvironmentVariable("NO_SQLITE_POOLING")]
[Description("disable SQLite pooling")]
public bool NoSqlitePooling { get; init; } = false;
}
/// <summary>
/// Relay options.
/// </summary>
public class RelayOptions : IValidatableObject
{
/// <summary>
/// Gets a value indicating whether the relay is enabled.
/// </summary>
[Argument('r', "relay")]
[EnvironmentVariable("RELAY")]
[Description("enable relay")]
[RequiresRestart]
public bool Enabled { get; init; } = false;
/// <summary>
/// Gets the relay mode.
/// </summary>
[Argument('m', "relay-mode")]
[EnvironmentVariable("RELAY_MODE")]
[Description("relay mode; controller, agent")]
[RequiresRestart]
[Enum(typeof(RelayMode))]
public string Mode { get; init; } = RelayMode.Controller.ToString().ToLowerInvariant();
/// <summary>
/// Gets the controller configuration.
/// </summary>
public RelayControllerConfigurationOptions Controller { get; init; } = new RelayControllerConfigurationOptions();
/// <summary>
/// Gets the agent configuration.
/// </summary>
public Dictionary<string, RelayAgentConfigurationOptions> Agents { get; init; } = new();
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var mode = Mode.ToEnum<RelayMode>();
var results = new List<ValidationResult>();
var modeResults = new List<ValidationResult>();
if (mode == RelayMode.Agent && !Validator.TryValidateObject(Controller, new ValidationContext(Controller), modeResults, validateAllProperties: true))
{
results.Add(new CompositeValidationResult("Controller", modeResults));
}
else
{
// determine whether any InstanceName is used more than once
var instanceNames = Agents.Values.Select(a => a.InstanceName);
if (instanceNames.Count() != instanceNames.Distinct().Count())
{
modeResults.Add(new ValidationResult("One or more Agent instance names are duplicated. Ensure instance names are unique."));
}
foreach (var (name, agent) in Agents)
{
var res = new List<ValidationResult>();
if (!Validator.TryValidateObject(agent, new ValidationContext(agent), res, validateAllProperties: true))
{
modeResults.Add(new CompositeValidationResult(name, res));
}
}
if (modeResults.Any())
{
results.Add(new CompositeValidationResult("Agents", modeResults));
}
}
return results;
}
/// <summary>
/// Relay controller configuration options.
/// </summary>
public class RelayControllerConfigurationOptions
{
/// <summary>
/// Gets the controller address.
/// </summary>
[Argument(default, "controller-address")]
[EnvironmentVariable("CONTROLLER_ADDRESS")]
[Description("controller address url")]
[Url]
[NotNullOrWhiteSpace]
public string Address { get; init; }
/// <summary>
/// Gets a value indicating whether controller certificate errors should be ignored.
/// </summary>
[Argument(default, "controller-ignore-certificate-errors")]
[EnvironmentVariable("CONTROLLER_IGNORE_CERTIFICATE_ERRORS")]
[Description("ignore controller certificate errors")]
public bool IgnoreCertificateErrors { get; init; } = false;
/// <summary>
/// Gets the controller API key.
/// </summary>
[Argument(default, "controller-api-key")]
[EnvironmentVariable("CONTROLLER_API_KEY")]
[Description("controller api key")]
[StringLength(255, MinimumLength = 16)]
[NotNullOrWhiteSpace]
[Secret]
public string ApiKey { get; init; }
/// <summary>
/// Gets the controller secret.
/// </summary>
[Argument(default, "controller-secret")]
[EnvironmentVariable("CONTROLLER_SECRET")]
[Description("shared secret")]
[StringLength(255, MinimumLength = 16)]
[NotNullOrWhiteSpace]
[Secret]
public string Secret { get; init; }
/// <summary>
/// Gets a value indicating whether to receive completed downloads from the controller.
/// </summary>
[Argument(default, "controller-downloads")]
[EnvironmentVariable("CONTROLLER_DOWNLOADS")]
[Description("receive completed downloads from the controller")]
public bool Downloads { get; init; } = false;
}
/// <summary>
/// Relay agent configuration options.
/// </summary>
public class RelayAgentConfigurationOptions : IValidatableObject
{
/// <summary>
/// Gets the agent instance name.
/// </summary>
[Description("the name for this agent")]
[StringLength(255, MinimumLength = 1)]
[NotNullOrWhiteSpace]
[Secret]
public string InstanceName { get; init; }
/// <summary>
/// Gets the agent secret.
/// </summary>
[Description("shared secret for this agent")]
[StringLength(255, MinimumLength = 16)]
[NotNullOrWhiteSpace]
[Secret]
public string Secret { get; init; }
/// <summary>
/// Gets the comma separated list of CIDRs that are authorized to connect as this agent.
/// </summary>
[Description("optional; comma separated list of CIDRs that are authorized to connect as this agent")]
public string Cidr { get; init; } = "0.0.0.0/0,::/0";
/// <summary>
/// Extended validation.
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
foreach (var cidr in Cidr.Split(','))
{
try
{
if (cidr.StartsWith("::ffff", StringComparison.OrdinalIgnoreCase))
{
throw new Exception("IPv4 mapped IPv6 addresses are not allowed");
}
_ = IPAddressRange.Parse(cidr);
}
catch (Exception ex)
{
results.Add(new ValidationResult($"CIDR {cidr} is invalid: {ex.Message}"));
}
}
return results;
}
}
}
/// <summary>
/// Directory options.
/// </summary>
public class DirectoriesOptions
{
/// <summary>
/// Gets the path where incomplete downloads are saved.
/// </summary>
[Argument(default, "incomplete")]
[EnvironmentVariable("INCOMPLETE_DIR")]
[Description("path where incomplete downloads are saved")]
[AbsolutePath(OperatingSystem.Current)]
[NonTraversingPath]
[DirectoryExists(ensureWriteable: true)]
[RequiresRestart]
public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory;
/// <summary>
/// Gets the path where downloaded files are saved.
/// </summary>
[Argument('o', "downloads")]
[EnvironmentVariable("DOWNLOADS_DIR")]
[Description("path where downloaded files are saved")]
[AbsolutePath(OperatingSystem.Current)]
[NonTraversingPath]
[DirectoryExists(ensureWriteable: true)]
[RequiresRestart]
public string Downloads { get; init; } = Program.DefaultDownloadsDirectory;
}
/// <summary>
/// Share options.
/// </summary>
public class SharesOptions : IValidatableObject
{
/// <summary>
/// Gets the list of paths to shared files.
/// </summary>
[Argument('s', "shared")]
[EnvironmentVariable("SHARED_DIR")]
[Description("paths to shared files")]
public string[] Directories { get; init; } = Array.Empty<string>();
/// <summary>
/// Gets the list of shared file filters.
/// </summary>
[Argument(default, "share-filter")]
[EnvironmentVariable("SHARE_FILTER")]
[Description("regular expressions to filter files from shares")]
public string[] Filters { get; init; } = Array.Empty<string>();
/// <summary>
/// Share caching options.
/// </summary>
[Validate]
public ShareCacheOptions Cache { get; init; } = new ShareCacheOptions();
/// <summary>
/// Extended validation.
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
results.AddRange(ValidateShares());
results.AddRange(ValidateFilters());
return results;
}
private IEnumerable<ValidationResult> ValidateShares()
{
var results = new List<ValidationResult>();
var directories = Directories ?? Enumerable.Empty<string>();
bool IsBlankPath(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])$");
directories?.Where(share => IsBlankPath(share)).ToList()
.ForEach(blank => results.Add(new ValidationResult($"Share {blank} does not specify a path")));
bool IsRootMount(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])/$");
directories?.Where(share => IsRootMount(share)).ToList()
.ForEach(blank => results.Add(new ValidationResult($"Share {blank} specifies a root mount, which is not supported.")));
// starts with '/', 'X:', or '\\'
bool IsAbsolutePath(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$");
directories?.Where(share => !IsAbsolutePath(share)).ToList()
.ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported.")));
// contains /./ or /../ or \.\ or \..\ or ..\ or ../ or \.. or /..
// which is resolved by some OS and will cause weird, unintended side effects
bool ContainsTraversalSegments(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$");
directories?.Where(share => ContainsTraversalSegments(share)).ToList()
.ForEach(badPath => results.Add(new ValidationResult($"Share {badPath} contains an unsafe path traversal segment.")));
(string Raw, string Alias, string Path) Digest(string share)
{
var matches = Regex.Matches(share, @"^(!|-){0,1}\[([^\]]*)\](.*)$");
if (matches.Any())
{
return (share, matches[0].Groups[2].Value, matches[0].Groups[3].Value);
}
#pragma warning disable S3878 // Arrays should not be created for params parameters
return (share, share.Split(new[] { '/', '\\' }).Last(), share);
#pragma warning restore S3878 // Arrays should not be created for params parameters
}
var digestedShared = directories
.Select(share => Digest(share.TrimEnd('/', '\\')))
.ToHashSet();
// make sure all aliases are distinct
digestedShared.GroupBy(share => share.Alias).Where(group => group.Count() > 1).ToList()
.ForEach(overlap => results.Add(new ValidationResult($"Shares {string.Join(", ", overlap.Select(s => $"'{s.Raw}'"))} collide. Specify an alias for one or both to disambiguate them.")));
// make sure the same path hasn't been specified twice, under different aliases
digestedShared.GroupBy(share => share.Path).Where(group => group.Count() > 1).ToList()
.ForEach(dupe => results.Add(new ValidationResult($"Shares {string.Join(", ", dupe.Select(s => $"'{s.Raw}'"))} alias the same path")));
// make sure each share has an alias, or is alias-able, and that the alias is valid
foreach (var share in digestedShared)
{
if (string.IsNullOrWhiteSpace(share.Alias))
{
results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; alias may not be null, empty or consist of only whitespace"));
}
else if (share.Alias.Contains('\\') || share.Alias.Contains('/'))
{
results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; aliases may not contain path separators '/' or '\\'"));
}
}
return results;
}
private IEnumerable<ValidationResult> ValidateFilters()
{
var results = new List<ValidationResult>();
foreach (var filter in Filters)
{
if (!filter.IsValidRegex())
{
results.Add(new ValidationResult($"Share filter '{filter}' is not a valid regular expression"));
}
}
return results;
}
/// <summary>
/// Share caching options.
/// </summary>
public class ShareCacheOptions
{
/// <summary>
/// Gets the type of storage to use for the share cache.
/// </summary>
[Argument(default, "share-cache-storage-mode")]
[EnvironmentVariable("SHARE_CACHE_STORAGE_MODE")]
[Description("the type of storage to use for the cache")]
[Enum(typeof(StorageMode))]
[RequiresRestart]
public string StorageMode { get; init; } = slskd.Shares.StorageMode.Memory.ToString().ToLowerInvariant();
/// <summary>
/// Gets the number of workers to use while scanning shares.
/// </summary>
[Argument(default, "share-cache-workers")]
[EnvironmentVariable("SHARE_CACHE_WORKERS")]
[Description("the number of workers to use while scanning shares")]
[Range(1, 128)]
[RequiresRestart]
public int Workers { get; init; } = Environment.ProcessorCount;
/// <summary>
/// Gets the time to retain the cache (the interval on which to re-scan automatically), in minutes.
/// </summary>
[Argument(default, "share-cache-retention")]
[EnvironmentVariable("SHARE_CACHE_RETENTION")]
[Description("the time to retain the cache (re-scan interval), in minutes")]
[Range(60, int.MaxValue)]
public int? Retention { get; init; } = null;
}
}
/// <summary>
/// Transfer options.
/// </summary>
public class TransfersOptions
{
/// <summary>
/// Gets global upload options.
/// </summary>
[Validate]
public GlobalUploadOptions Upload { get; init; } = new GlobalUploadOptions();
/// <summary>
/// Gets global download options.
/// </summary>
[Validate]
public GlobalDownloadOptions Download { get; init; } = new GlobalDownloadOptions();
/// <summary>
/// Gets user groups.
/// </summary>
[Validate]
public GroupsOptions Groups { get; init; } = new GroupsOptions();
/// <summary>
/// Global upload options.
/// </summary>
public class GlobalUploadOptions
{
/// <summary>
/// Gets the limit for the total number of upload slots.
/// </summary>
[Argument(default, "upload-slots")]
[EnvironmentVariable("UPLOAD_SLOTS")]
[Description("the total number of upload slots")]
[RequiresRestart]
[Range(1, int.MaxValue)]
public int Slots { get; init; } = 10;
/// <summary>
/// Gets the total upload speed limit, in kibibytes.
/// </summary>
[Argument(default, "upload-speed-limit")]
[EnvironmentVariable("UPLOAD_SPEED_LIMIT")]
[Description("the total upload speed limit")]
[Range(1, int.MaxValue)]
public int SpeedLimit { get; init; } = int.MaxValue;
/// <summary>
/// Gets global limits.
/// </summary>
[Validate]
public LimitsOptions Limits { get; init; } = new LimitsOptions();
}
/// <summary>
/// Gets global download options.
/// </summary>
public class GlobalDownloadOptions
{
/// <summary>
/// Gets the limit for the total number of download slots.
/// </summary>
[Argument(default, "download-slots")]
[EnvironmentVariable("DOWNLOAD_SLOTS")]
[Description("the total number of download slots")]
[RequiresRestart]
[Range(1, int.MaxValue)]
public int Slots { get; init; } = int.MaxValue;
/// <summary>
/// Gets the total download speed limit, in kibibytes.
/// </summary>
[Argument(default, "download-speed-limit")]
[EnvironmentVariable("DOWNLOAD_SPEED_LIMIT")]
[Description("the total download speed limit")]
[Range(1, int.MaxValue)]
public int SpeedLimit { get; init; } = int.MaxValue;
/// <summary>
/// Gets download retry options.
/// </summary>
[Validate]
public RetryOptions Retry { get; init; } = new RetryOptions();
/// <summary>
/// Gets download destination options.
/// </summary>
[Validate]
public DestinationOptions Destination { get; init; } = new DestinationOptions();
/// <summary>
/// Download retry options.
/// </summary>
public class RetryOptions
{
/// <summary>
/// Gets the maximum number of times to retry a failed transfer.
/// </summary>
[Range(1, int.MaxValue)]
public int Attempts { get; init; } = 3;
/// <summary>
/// Gets the base time to wait between retry attempts, in milliseconds.
/// </summary>
[Range(1000, int.MaxValue)]
public int Delay { get; init; } = 5000;
/// <summary>
/// Gets the maximum time to wait between retry attempts, in milliseconds.
/// </summary>
[Range(30_000, int.MaxValue)]
public int MaxDelay { get; init; } = 60_000;
/// <summary>
/// Gets the strategy for handling partial files upon retry.
/// </summary>
[Enum(typeof(RetryPartialStrategy))]
public string Partial { get; init; } = RetryPartialStrategy.Resume.ToString().ToLowerInvariant();
}
/// <summary>
/// Download destination options.
/// </summary>
public class DestinationOptions
{
/// <summary>
/// Gets the destination subdirectory for the files in the batch.
/// </summary>
[RelativePath(OperatingSystem.All)]
[NonTraversingPath]
[String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)]
public string Subdirectory { get; init; } = "${SOURCE_DIRECTORY}";
/// <summary>
/// Gets the strategy for handling existing files on disk.
/// </summary>
[Enum(typeof(DestinationExistsStrategy))]
public string Exists { get; init; } = DestinationExistsStrategy.Rename.ToString().ToLowerInvariant();
/// <summary>
/// Gets the permissions to apply to downloaded files and directories.
/// </summary>
[Validate]
public DestinationPermissionsOptions Permissions { get; init; } = new DestinationPermissionsOptions();
/// <summary>
/// Download destination permission options.
/// </summary>
public class DestinationPermissionsOptions : IValidatableObject
{
/// <summary>
/// Gets the permissions to apply to newly created files.
/// </summary>
/// <remarks>
/// Applicable to non-Windows operating systems, only.
/// </remarks>
public string Mode { get; init; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (!string.IsNullOrEmpty(Mode))
{
var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled);
if (!regEx.IsMatch(Mode))
{
results.Add(new ValidationResult($"Field {nameof(Mode)} is invalid. Specify a three- or four-character string consisting of only 0-7 (chmod syntax, [0]000-[7]777, inclusive)"));
}
}
return results;
}
}
}
}
/// <summary>
/// User groups.
/// </summary>
public class GroupsOptions : IValidatableObject
{
/// <summary>
/// Gets options for the default user group.
/// </summary>
/// <remarks>
/// These options apply to users that are not privileged, have not been identified as leechers,
/// and have not been added as a member of any group.
/// </remarks>
[Validate]
public BaseGroupOptions Default { get; init; } = new BaseGroupOptions();
/// <summary>
/// Gets options for the leecher user group.
/// </summary>
/// <remarks>
/// These options apply to users that have been identified as leechers, and have not been added as a member of any group.
/// </remarks>
[Validate]
public LeecherOptions Leechers { get; init; } = new LeecherOptions();
/// <summary>
/// Gets options for the blacklisted user group.
/// </summary>
[Validate]
public BlacklistedOptions Blacklisted { get; init; } = new BlacklistedOptions();
/// <summary>
/// Gets user defined groups and options.
/// </summary>
[Validate]
public Dictionary<string, UserDefinedOptions> UserDefined { get; init; } = new Dictionary<string, UserDefinedOptions>();
/// <summary>
/// Extended validation.
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var builtInGroups = new[] { Application.PrivilegedGroup, Application.DefaultGroup, Application.LeecherGroup };
var intersection = UserDefined.Keys.Intersect(builtInGroups);
return intersection.Select(group => new ValidationResult($"User defined group '{group}' collides with a built in group. Choose a different name."));
}
/// <summary>
/// Options that are common to all groups.
/// </summary>
public class BaseGroupOptions
{
/// <summary>
/// Gets upload options.
/// </summary>
[Validate]
public GroupUploadOptions Upload { get; init; } = new GroupUploadOptions();
/// <summary>
/// User group upload options.
/// </summary>
public class GroupUploadOptions
{
/// <summary>
/// Gets the priority of the group.
/// </summary>
[Range(1, int.MaxValue)]
public int Priority { get; init; } = 1;
/// <summary>
/// Gets the queue strategy for the group.
/// </summary>
[Enum(typeof(Transfers.QueueStrategy))]
public string Strategy { get; init; } = slskd.Transfers.QueueStrategy.RoundRobin.ToString().ToLowerInvariant();
/// <summary>
/// Gets the limit for the total number of upload slots for the group.
/// </summary>
[Range(1, int.MaxValue)]
public int Slots { get; init; } = int.MaxValue;
/// <summary>
/// Gets the total upload speed limit for the group, in kibibytes.
/// </summary>
[Range(1, int.MaxValue)]
public int SpeedLimit { get; init; } = int.MaxValue;
/// <summary>
/// Gets limit options.
/// </summary>
[Validate]
public LimitsOptions Limits { get; init; } = new LimitsOptions();
}
}
/// <summary>
/// Built in leecher group options.
/// </summary>
public class LeecherOptions : BaseGroupOptions
{
/// <summary>
/// Gets leecher threshold options.
/// </summary>
[Validate]
public ThresholdOptions Thresholds { get; init; } = new ThresholdOptions();
/// <summary>
/// Leecher threshold options.
/// </summary>
public class ThresholdOptions
{
/// <summary>
/// Gets the minimum number of shared files required to avoid being classified as a leecher.
/// </summary>
[Range(1, int.MaxValue)]
public int Files { get; init; } = 1;
/// <summary>
/// Gets the minimum number of shared directories required to avoid being classified as a leecher.
/// </summary>
[Range(1, int.MaxValue)]
public int Directories { get; init; } = 1;
}
}
/// <summary>
/// Built in blacklisted group options.
/// </summary>
public class BlacklistedOptions : IValidatableObject
{
/// <summary>
/// Gets the list of group member usernames.
/// </summary>
public string[] Members { get; init; } = Array.Empty<string>();
/// <summary>
/// Gets the list of regular expression patterns matched against usernames.
/// </summary>
public string[] Patterns { get; init; } = Array.Empty<string>();
/// <summary>
/// Gets the list of group CIDRs.
/// </summary>
public string[] Cidrs { get; init; } = Array.Empty<string>();
/// <summary>
/// Extended validation.
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
foreach (var pattern in Patterns ?? Array.Empty<string>())
{
if (!pattern.IsValidRegex())
{
results.Add(new ValidationResult($"Pattern '{pattern}' is not a valid regular expression"));
}
}
foreach (var cidr in Cidrs ?? Array.Empty<string>())
{
try
{
if (cidr.StartsWith("::ffff", StringComparison.OrdinalIgnoreCase))
{
throw new Exception("IPv4 mapped IPv6 addresses are not allowed");
}
_ = IPAddressRange.Parse(cidr);
}
catch (Exception ex)
{
results.Add(new ValidationResult($"CIDR {cidr} is invalid: {ex.Message}"));
}
}
return results;
}
}
/// <summary>
/// User defined user group options.
/// </summary>
public class UserDefinedOptions : BaseGroupOptions
{
/// <summary>
/// Gets the list of group member usernames.
/// </summary>
public string[] Members { get; init; } = Array.Empty<string>();
}
}
/// <summary>
/// Limit options.
/// </summary>
public class LimitsOptions
{
/// <summary>
/// Gets limits for queued transfers.
/// </summary>
[Validate]
public Limits Queued { get; init; } = new Limits();
/// <summary>
/// Gets daily limits for transfers.
/// </summary>
[Validate]
public Limits Daily { get; init; } = new Limits();
/// <summary>
/// Gets weekly limits for transfers.
/// </summary>
[Validate]
public Limits Weekly { get; init; } = new Limits();
/// <summary>
/// Limits.
/// </summary>
public class Limits
{
/// <summary>
/// Gets the limit for number of files.
/// </summary>
[Range(1, int.MaxValue)]
public int? Files { get; init; } = null;
/// <summary>
/// Gets the limit for number of megabytes.
/// </summary>
[Range(1, int.MaxValue)]
public int? Megabytes { get; init; } = null;
/// <summary>
/// Gets the limit for number of failures.
/// </summary>
[Range(1, int.MaxValue)]
public int? Failures { get; init; } = null;
}
}
}
/// <summary>
/// Feature options.
/// </summary>
public class FeatureOptions
{
/// <summary>
/// Gets a value indicating whether swagger documentation and UI should be enabled.
/// </summary>
[Argument(default, "swagger")]
[EnvironmentVariable("SWAGGER")]
[Description("enable swagger documentation and UI")]
[RequiresRestart]
public bool Swagger { get; init; } = false;
}
/// <summary>
/// Blacklist options.
/// </summary>
public class BlacklistOptions : IValidatableObject
{
/// <summary>
/// Gets a value indicating whether blacklist file support should be enabled.
/// </summary>
[Argument(default, "enable-blacklist")]
[EnvironmentVariable("BLACKLIST")]
[Description("enable blacklist file support")]
[RequiresRestart]
public bool Enabled { get; init; }
/// <summary>
/// Gets the path to the blacklist file.
/// </summary>
[Argument(default, "blacklist-file")]
[EnvironmentVariable("BLACKLIST_FILE")]
[Description("path to blacklist file")]
[FileExists(FileAccess.Read)]
public string File { get; init; }
/// <summary>
/// Extended validation.
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (!Enabled)
{
return results;
}
if (string.IsNullOrWhiteSpace(File))
{
results.Add(new ValidationResult("The Enabled field is true, but no File has been specified."));
return results;
}
// loading/validating the entire list will be costly on low spec systems
// just make sure that we can detect a valid format and leave it at that
// if there's a problem with any of the entries, the load will fail and
// kill the application
try
{
// async not supported here, .Result is all we have
_ = slskd.Blacklist.DetectFormat(File).Result;
}
catch
{
results.Add(new ValidationResult("Failed to detect blacklist format. Only CIDR, P2P and DAT formats are supported"));
}
return results;
}
}
/// <summary>
/// Filter options.
/// </summary>
public class FiltersOptions
{
/// <summary>
/// Gets search filter options.
/// </summary>
[Validate]
public SearchOptions Search { get; init; } = new SearchOptions();
/// <summary>
/// Search filter options.
/// </summary>
public class SearchOptions : IValidatableObject
{
/// <summary>
/// Gets the list of search request filters.
/// </summary>
[Argument(default, "search-request-filter")]
[EnvironmentVariable("SEARCH_REQUEST_FILTER")]
[Description("regular expressions to filter incoming search requests")]
public string[] Request { get; init; } = Array.Empty<string>();
/// <summary>
/// Extended validation.
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
foreach (var filter in Request)
{
if (!filter.IsValidRegex())
{
results.Add(new ValidationResult($"Search request filter '{filter}' is not a valid regular expression"));
}
}
return results;
}
}
}
/// <summary>
/// Logger options.
/// </summary>
public class LoggerOptions
{
/// <summary>
/// Gets the URL to a Grafana Loki instance to which to log.
/// </summary>
[Argument(default, "loki")]
[EnvironmentVariable("LOKI")]
[Description("optional; url to a Grafana Loki instance to which to log")]
[RequiresRestart]
[Secret]
public string Loki { get; init; } = null;
/// <summary>
/// Gets a value indicating whether to write logs to disk.
/// </summary>
[Argument(default, "no-disk-logger")]
[EnvironmentVariable("NO_DISK_LOGGER")]
[Description("disable logging to disk")]
[RequiresRestart]
public bool NoDisk { get; init; } = false;
/// <summary>
/// Gets a value indicating whether to suppress colorization of console logs.
/// </summary>
[Argument(default, "no-color")]
[EnvironmentVariable("NO_COLOR")]
[Description("disable console log colors")]
[RequiresRestart]
public bool NoColor { get; init; } = false;
}
/// <summary>
/// Retention options.
/// </summary>
public class RetentionOptions
{
/// <summary>
/// Gets the time to retain searches, in minutes.
/// </summary>
[Range(5, maximum: int.MaxValue)]
public int? Search { get; init; } = null;
/// <summary>
/// Gets transfer retention options.
/// </summary>
[Validate]
public TransferRetentionOptions Transfers { get; init; } = new TransferRetentionOptions();
/// <summary>
/// Gets file retention options.
/// </summary>
[Validate]
public FileRetentionOptions Files { get; init; } = new FileRetentionOptions();
/// <summary>
/// Gets the time to retain logs, in days.
/// </summary>
[Range(2, maximum: int.MaxValue)]
public int Logs { get; init; } = 14;
/// <summary>
/// Transfer retention options.
/// </summary>
public class TransferRetentionOptions
{
/// <summary>
/// Gets upload retention options.
/// </summary>
[Validate]
public TransferTypeRetentionOptions Upload { get; init; } = new TransferTypeRetentionOptions();
/// <summary>
/// Gets download retention options.
/// </summary>
[Validate]
public TransferTypeRetentionOptions Download { get; init; } = new TransferTypeRetentionOptions();
/// <summary>
/// Transfer retention options.
/// </summary>
public class TransferTypeRetentionOptions
{
/// <summary>
/// Gets the time to retain successful transfers, in minutes.
/// </summary>
[Range(5, maximum: int.MaxValue)]
public int? Succeeded { get; init; } = null;
/// <summary>
/// Gets the time to retain errored transfers, in minutes.
/// </summary>
[Range(5, maximum: int.MaxValue)]
public int? Errored { get; init; } = null;
/// <summary>
/// Gets the time to retain cancelled transfers, in minutes.
/// </summary>
[Range(5, maximum: int.MaxValue)]
public int? Cancelled { get; init; } = null;
/// <summary>
/// Gets the time to retain unsuccessful (including errored and cancelled) transfers, in minutes.
/// </summary>
[Range(5, maximum: int.MaxValue)]
public int? Failed { get; init; } = null;
}
}
/// <summary>
/// File retention options.
/// </summary>
public class FileRetentionOptions
{
/// <summary>
/// Gets the time to retain completed files, in minutes.
/// </summary>
[Range(30, maximum: int.MaxValue)]
public int? Complete { get; init; } = null;
/// <summary>
/// Gets the time to retain incomplete files, in minutes.
/// </summary>
[Range(30, maximum: int.MaxValue)]
public int? Incomplete { get; init; } = null;
}
}
/// <summary>
/// Throttling options.
/// </summary>
public class ThrottlingOptions
{
/// <summary>
/// Gets search throttling options.
/// </summary>
[Validate]
public SearchThrottlingOptions Search { get; init; } = new SearchThrottlingOptions();
/// <summary>
/// Search throttling options.
/// </summary>
public class SearchThrottlingOptions
{
/// <summary>
/// Gets incoming search throttling options.
/// </summary>
[Validate]
public IncomingSearchThrottlingOptions Incoming { get; init; } = new IncomingSearchThrottlingOptions();
/// <summary>
/// Search response throttling options.
/// </summary>
public class IncomingSearchThrottlingOptions
{
/// <summary>
/// Gets the limit for the number of concurrent search response operations.
/// </summary>
[Argument(default, "throttling-search-incoming-concurrency")]
[EnvironmentVariable("THROTTLING_SEARCH_INCOMING_CONCURRENCY")]
[Range(1, 100)]
[RequiresRestart]
public int Concurrency { get; init; } = 10;
/// <summary>
/// Gets the limit for the number of queued search response operations, after which requests will be discarded.
/// </summary>
[Argument(default, "throttling-search-incoming-circuit-breaker")]
[EnvironmentVariable("THROTTLING_SEARCH_INCOMING_CIRCUIT_BREAKER")]
[Range(100, 10000)]
public int CircuitBreaker { get; init; } = 500;
/// <summary>
/// Gets the limit for the number of files that can be returned in a single search request.
/// </summary>
[Argument(default, "throttling-search-incoming-response-file-limit")]
[EnvironmentVariable("THROTTLING_SEARCH_INCOMING_RESPONSE_FILE_LIMIT")]
[Range(100, 5000)]
public int ResponseFileLimit { get; init; } = 500;
}
}
}
/// <summary>
/// Metrics options.
/// </summary>
public class MetricsOptions
{
/// <summary>
/// Gets a value indicating whether the metrics endpoint should be enabled.
/// </summary>
[Argument(default, "metrics")]
[EnvironmentVariable("METRICS")]
[Description("enable metrics")]
[RequiresRestart]
public bool Enabled { get; init; } = false;
/// <summary>
/// Gets the url for the metrics endpoint.
/// </summary>
[Argument(default, "metrics-url")]
[EnvironmentVariable("METRICS_URL")]
[Description("url for metrics")]
[RequiresRestart]
public string Url { get; init; } = "/metrics";
/// <summary>
/// Gets metrics endpoint authentication options.
/// </summary>
[Validate]
public MetricsAuthenticationOptions Authentication { get; init; } = new MetricsAuthenticationOptions();
/// <summary>
/// Metrics endpoint authentication options.
/// </summary>
public class MetricsAuthenticationOptions
{
/// <summary>
/// Gets a value indicating whether authentication should be disabled.
/// </summary>
[Argument(default, "metrics-no-auth")]
[EnvironmentVariable("METRICS_NO_AUTH")]
[Description("disable authentication for metrics requests")]
[RequiresRestart]
public bool Disabled { get; init; } = false;
/// <summary>
/// Gets the username for the metrics endpoint.
/// </summary>
[Argument(default, "metrics-username")]
[EnvironmentVariable("METRICS_USERNAME")]
[Description("username for metrics")]
[StringLength(255, MinimumLength = 1)]
[RequiresRestart]
public string Username { get; init; } = Program.AppName;
/// <summary>
/// Gets the password for the metrics endpoint.
/// </summary>
[Argument(default, "metrics-password")]
[EnvironmentVariable("METRICS_PASSWORD")]
[Description("password for metrics")]
[StringLength(255, MinimumLength = 1)]
[Secret]
[RequiresRestart]
public string Password { get; init; } = Program.AppName;
}
}
/// <summary>
/// Soulseek client options.
/// </summary>
public class SoulseekOptions
{
/// <summary>
/// Gets the address of the Soulseek server.
/// </summary>
[Argument(default, "slsk-address")]
[EnvironmentVariable("SLSK_ADDRESS")]
[Description("address of the Soulseek server")]
[RequiresReconnect]
public string Address { get; init; } = "vps.slsknet.org";
/// <summary>
/// Gets the port of the Soulseek server.
/// </summary>
[Argument(default, "slsk-port")]
[EnvironmentVariable("SLSK_PORT")]
[Description("port of the Soulseek server")]
[RequiresReconnect]
[Range(1024, 65535)]
public int Port { get; init; } = 2271;
/// <summary>
/// Gets the username for the Soulseek network.
/// </summary>
[Argument(default, "slsk-username")]
[EnvironmentVariable("SLSK_USERNAME")]
[Description("username for the Soulseek network")]
[RequiresReconnect]
public string Username { get; init; } = null;
/// <summary>
/// Gets the password for the Soulseek network.
/// </summary>
[Argument(default, "slsk-password")]
[EnvironmentVariable("SLSK_PASSWORD")]
[Description("password for the Soulseek network")]
[Secret]
[RequiresReconnect]
public string Password { get; init; } = null;
/// <summary>
/// Gets the description of the Soulseek user.
/// </summary>
[Argument(default, "slsk-description")]
[EnvironmentVariable("SLSK_DESCRIPTION")]
[Description("user description for the Soulseek network")]
public string Description { get; init; } = "A slskd user. https://github.com/slskd/slskd";
/// <summary>
/// Gets the file path for the user's profile picture.
/// </summary>
[Argument(default, "slsk-picture")]
[EnvironmentVariable("SLSK_PICTURE")]
[Description("user picture for the Soulseek network")]
[FileExists(FileAccess.Read)]
public string Picture { get; init; } = null;
/// <summary>
/// Gets the local IP address on which to listen for incoming connections.
/// </summary>
[Argument(default, "slsk-listen-ip-address")]
[EnvironmentVariable("SLSK_LISTEN_IP_ADDRESS")]
[Description("local IP address on which to listen for incoming connections")]
[IPAddress]
public string ListenIpAddress { get; init; } = "0.0.0.0";
/// <summary>
/// Gets the port on which to listen for incoming connections.
/// </summary>
[Argument(default, "slsk-listen-port")]
[EnvironmentVariable("SLSK_LISTEN_PORT")]
[Description("port on which to listen for incoming connections")]
[Range(1024, 65535)]
public int ListenPort { get; init; } = 50300;
/// <summary>
/// Gets the minimum diagnostic level.
/// </summary>
[Argument(default, "slsk-diag-level")]
[EnvironmentVariable("SLSK_DIAG_LEVEL")]
[Description("minimum diagnostic level (None, Warning, Info, Debug)")]
[Enum(typeof(SoulseekDiagnostics.DiagnosticLevel))]
[RequiresRestart]
public string DiagnosticLevel { get; init; } = SoulseekDiagnostics.DiagnosticLevel.Info.ToString().ToLowerInvariant();
/// <summary>
/// Gets options for the distributed network.
/// </summary>
[Validate]
public DistributedNetworkOptions DistributedNetwork { get; init; } = new DistributedNetworkOptions();
/// <summary>
/// Gets connection options.
/// </summary>
[Validate]
public ConnectionOptions Connection { get; init; } = new ConnectionOptions();
/// <summary>
/// Connection options.
/// </summary>
public class ConnectionOptions
{
/// <summary>
/// Gets connection timeout options.
/// </summary>
[Validate]
public TimeoutOptions Timeout { get; init; } = new TimeoutOptions();
/// <summary>
/// Gets connection buffer options.
/// </summary>
[Validate]
public BufferOptions Buffer { get; init; } = new BufferOptions();
/// <summary>
/// Gets connection proxy options.
/// </summary>
[Validate]
public ProxyOptions Proxy { get; init; } = new ProxyOptions();
/// <summary>
/// Gets the MTU to use for the server connection, or null to use the OS default.
/// </summary>
[Argument(default, "slsk-server-mtu")]
[EnvironmentVariable("SLSK_SERVER_MTU")]
[Description("MTU to use for the server connection")]
[Range(576, 65535)]
[RequiresReconnect]
public int? Mtu { get; init; } = null;
/// <summary>
/// Connection buffer options.
/// </summary>
public class BufferOptions
{
/// <summary>
/// Gets the connection read buffer size, in bytes.
/// </summary>
[Argument(default, "slsk-read-buffer")]
[EnvironmentVariable("SLSK_READ_BUFFER")]
[Description("read buffer size for connections")]
[Range(1024, int.MaxValue)]
public int Read { get; init; } = 16384;
/// <summary>
/// Gets the connection write buffer size, in bytes.
/// </summary>
[Argument(default, "slsk-write-buffer")]
[EnvironmentVariable("SLSK_WRITE_BUFFER")]
[Description("write buffer size for connections")]
[Range(1024, int.MaxValue)]
public int Write { get; init; } = 16384;
/// <summary>
/// Gets the read/write buffer size for transfers, in bytes.
/// </summary>
[Argument(default, "slsk-transfer-buffer")]
[EnvironmentVariable("SLSK_TRANSFER_BUFFER")]
[Description("read/write buffer size for transfers")]
[Range(81920, int.MaxValue)]
public int Transfer { get; init; } = 262144;
/// <summary>
/// Gets the size of the queue for double buffered writes.
/// </summary>
[Argument(default, "slsk-write-queue")]
[EnvironmentVariable("SLSK_WRITE_QUEUE")]
[Description("queue size for double buffered writes")]
[Range(5, 5000)]
public int WriteQueue { get; init; } = 50;
}
/// <summary>
/// Connection timeout options.
/// </summary>
public class TimeoutOptions
{
/// <summary>
/// Gets the connection timeout value, in milliseconds.
/// </summary>
[Argument(default, "slsk-connection-timeout")]
[EnvironmentVariable("SLSK_CONNECTION_TIMEOUT")]
[Description("connection timeout, in milliseconds")]
[Range(1000, int.MaxValue)]
public int Connect { get; init; } = 10000;
/// <summary>
/// Gets the connection inactivity timeout, in milliseconds.
/// </summary>
[Argument(default, "slsk-inactivity-timeout")]
[EnvironmentVariable("SLSK_INACTIVITY_TIMEOUT")]
[Description("connection inactivity timeout, in milliseconds")]
[Range(1000, int.MaxValue)]
public int Inactivity { get; init; } = 15000;
/// <summary>
/// Gets the transfer connection timeout, in milliseconds.
/// </summary>
[Argument(default, "slsk-transfer-timeout")]
[EnvironmentVariable("SLSK_TRANSFER_TIMEOUT")]
[Description("transfer connection timeout, in milliseconds")]
[Range(30_000, int.MaxValue)]
public int Transfer { get; init; } = 60000;
}
/// <summary>
/// Connection proxy options.
/// </summary>
public class ProxyOptions : IValidatableObject
{
/// <summary>
/// Gets a value indicating whether the proxy is enabled.
/// </summary>
[Argument(default, "slsk-proxy")]
[EnvironmentVariable("SLSK_PROXY_ENABLED")]
[Description("enable connection proxy")]
public bool Enabled { get; init; } = false;
/// <summary>
/// Gets the proxy address.
/// </summary>
[Argument(default, "slsk-proxy-address")]
[EnvironmentVariable("SLSK_PROXY_ADDRESS")]
[Description("connection proxy address")]
[StringLength(255, MinimumLength = 1)]
public string Address { get; init; }
/// <summary>
/// Gets the proxy port.
/// </summary>
[Argument(default, "slsk-proxy-port")]
[EnvironmentVariable("SLSK_PROXY_PORT")]
[Description("connection proxy port")]
[Range(1, 65535)]
public int? Port { get; init; }
/// <summary>
/// Gets the proxy username, if applicable.
/// </summary>
[Argument(default, "slsk-proxy-username")]
[EnvironmentVariable("SLSK_PROXY_USERNAME")]
[Description("connection proxy username")]
[StringLength(255, MinimumLength = 1)]
public string Username { get; init; }
/// <summary>
/// Gets the proxy password, if applicable.
/// </summary>
[Argument(default, "slsk-proxy-password")]
[EnvironmentVariable("SLSK_PROXY_PASSWORD")]
[Description("connection proxy password")]
[StringLength(255, MinimumLength = 1)]
[Secret]
public string Password { get; init; }
/// <summary>
/// Extended validation.
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (Enabled && string.IsNullOrWhiteSpace(Address))
{
results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified."));
}
if (Enabled && !Port.HasValue)
{
results.Add(new ValidationResult($"The Enabled field is true, but no Port has been specified."));
}
return results;
}
}
}
/// <summary>
/// Distributed network options.
/// </summary>
public class DistributedNetworkOptions
{
/// <summary>
/// Gets a value indicating whether the distributed network should be disabled.
/// </summary>
[Argument(default, "slsk-no-dnet")]
[EnvironmentVariable("SLSK_NO_DNET")]
[Description("disable the distributed network")]
public bool Disabled { get; init; } = false;
/// <summary>
/// Gets a value indicating whether to accept distributed child connections.
/// </summary>
[Argument(default, "slsk-dnet-no-children")]
[EnvironmentVariable("SLSK_DNET_NO_CHILDREN")]
[Description("do not accept distributed children")]
public bool DisableChildren { get; init; } = false;
/// <summary>
/// Gets the distributed child connection limit.
/// </summary>
[Argument(default, "slsk-dnet-children")]
[EnvironmentVariable("SLSK_DNET_CHILDREN")]
[Description("max number of distributed children")]
[Range(1, int.MaxValue)]
public int ChildLimit { get; init; } = 25;
/// <summary>
/// Gets a value indicating whether distributed network logging should be enabled.
/// </summary>
[Argument(default, "slsk-dnet-logging")]
[EnvironmentVariable("SLSK_DNET_LOGGING")]
[Description("enable distributed network logging")]
public bool Logging { get; init; } = false;
}
}
/// <summary>
/// Web server options.
/// </summary>
public class WebOptions
{
/// <summary>
/// Gets the HTTP listen port.
/// </summary>
[Argument('l', "http-port")]
[EnvironmentVariable("HTTP_PORT")]
[Description("HTTP listen port for web UI")]
[Range(1, 65535)]
[RequiresRestart]
public int Port { get; init; } = 5030;
/// <summary>
/// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTP requests.
/// </summary>
[Argument(default, "http-ip-address")]
[EnvironmentVariable("HTTP_IP_ADDRESS")]
[Description("IP addresses on which to listen for HTTP requests")]
[IPAddress(allowCommaSeparatedValues: true)]
[RequiresRestart]
public string IpAddress { get; init; }
/// <summary>
/// Gets the HTTP listen unix domain socket (UDS) path.
/// </summary>
[Argument(default, "http-socket")]
[EnvironmentVariable("HTTP_SOCKET")]
[Description("HTTP listen unix domain socket (UDS) path for web UI")]
[AbsolutePath(OperatingSystem.Current)]
[NonTraversingPath]
[RequiresRestart]
public string Socket { get; init; }
/// <summary>
/// Gets HTTPS options.
/// </summary>
[Validate]
[RequiresRestart]
public HttpsOptions Https { get; init; } = new HttpsOptions();
/// <summary>
/// Gets the base url for web requests.
/// </summary>
[Argument(default, "url-base")]
[EnvironmentVariable("URL_BASE")]
[Description("base url for web requests")]
[RequiresRestart]
public string UrlBase { get; init; } = "/";
/// <summary>
/// Gets the path to static web content.
/// </summary>
[Argument(default, "content-path")]
[EnvironmentVariable("CONTENT_PATH")]
[Description("path to static web content")]
[StringLength(255, MinimumLength = 1)]
[DirectoryExists(relativeToApplicationDirectory: true)]
[RequiresRestart]
public string ContentPath { get; init; } = "wwwroot";
/// <summary>
/// Gets a value indicating whether HTTP request logging should be enabled.
/// </summary>
[Argument(default, "http-logging")]
[EnvironmentVariable("HTTP_LOGGING")]
[Description("enable http request logging")]
[RequiresRestart]
public bool Logging { get; init; } = false;
/// <summary>
/// Gets CORS options.
/// </summary>
[Validate]
[RequiresRestart]
public CorsOptions Cors { get; init; } = new CorsOptions();
/// <summary>
/// Gets authentication options.
/// </summary>
[Validate]
public WebAuthenticationOptions Authentication { get; init; } = new WebAuthenticationOptions();
/// <summary>
/// Authentication options.
/// </summary>
public class WebAuthenticationOptions : IValidatableObject
{
/// <summary>
/// Gets a value indicating whether authentication should be disabled.
/// </summary>
[Argument('X', "no-auth")]
[EnvironmentVariable("NO_AUTH")]
[Description("disable authentication for web requests")]
[RequiresRestart]
public bool Disabled { get; init; } = false;
/// <summary>
/// Gets the username for the web UI.
/// </summary>
[Argument('u', "username")]
[EnvironmentVariable("USERNAME")]
[Description("username for web UI")]
[StringLength(255, MinimumLength = 1)]
public string Username { get; init; } = Program.AppName;
/// <summary>
/// Gets the password for the web UI.
/// </summary>
[Argument('p', "password")]
[EnvironmentVariable("PASSWORD")]
[Description("password for web UI")]
[StringLength(255, MinimumLength = 1)]
[Secret]
public string Password { get; init; } = Program.AppName;
/// <summary>
/// Gets JWT options.
/// </summary>
[Validate]
[RequiresRestart]
public JwtOptions Jwt { get; init; } = new JwtOptions();
/// <summary>
/// Gets the primary API key. Defaults to 'Administrator' role and CIDR '0.0.0.0/0,::/0'.
/// role and CIDR can be supplied by prefixing the key with 'role=[role];cidr=[cidrs];[key]'.
/// </summary>
[Argument('k', "api-key")]
[EnvironmentVariable("API_KEY")]
[Description("primary API key value")]
[Secret]
[RequiresRestart]
public string ApiKey { get; init; }
/// <summary>
/// Gets API keys.
/// </summary>
[Validate]
public Dictionary<string, ApiKeyOptions> ApiKeys { get; init; } = new Dictionary<string, ApiKeyOptions>();
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (string.IsNullOrWhiteSpace(ApiKey))
{
return results;
}
var tuples = ApiKey.Split(';');
// if only one tuple is supplied, it's just the key, no role or list of CIDRs
if (tuples.Length == 1)
{
var key = tuples.FirstOrDefault();
if (key?.Length < 16 || key?.Length > 255)
{
results.Add(new ValidationResult("API key must be between 16 and 255 characters"));
}
return results;
}
/*
if multiple tuples are supplied, verify that:
* if a tuple starts with 'role=', it's defining a role and it must match one of the Role enum values
* if a tuple starts with 'cidr=', it's defining a list of CIDRs which need to be valid
* if a tuple doesn't start with a prefix, it's the API key itself and it must be between 16 and 255 characters
*/
foreach (var tuple in tuples)
{
if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase))
{
var role = tuple.Split('=').LastOrDefault();
var roleResult = new EnumAttribute(typeof(Role), ignoreCase: true)
.GetValidationResult(role, new ValidationContext(this) { MemberName = nameof(ApiKey), DisplayName = "API key role" });
if (roleResult != ValidationResult.Success)
{
results.Add(new ValidationResult(roleResult.ErrorMessage));
}
}
else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase))
{
var cidrs = tuple.Split('=').LastOrDefault();
foreach (var cidr in cidrs.Split(','))
{
try
{
if (cidr.StartsWith("::ffff", StringComparison.OrdinalIgnoreCase))
{
throw new Exception("IPv4 mapped IPv6 addresses are not allowed");
}
_ = IPAddressRange.Parse(cidr);
}
catch (Exception ex)
{
results.Add(new ValidationResult($"API key CIDR {cidr} is invalid: {ex.Message}"));
}
}
}
else if (tuple?.Length < 16 || tuple?.Length > 255)
{
results.Add(new ValidationResult("API key must be between 16 and 255 characters"));
}
}
return results;
}
/// <summary>
/// JWT options.
/// </summary>
public class JwtOptions
{
/// <summary>
/// Gets the key with which to sign JWTs.
/// </summary>
[Argument(default, "jwt-key")]
[EnvironmentVariable("JWT_KEY")]
[Description("JWT signing key")]
[StringLength(255, MinimumLength = 32)]
[Secret]
[RequiresRestart]
public string Key { get; init; } = Cryptography.Random.GetBytes(32).ToBase62();
/// <summary>
/// Gets the TTL for JWTs, in milliseconds.
/// </summary>
[Argument(default, "jwt-ttl")]
[EnvironmentVariable("JWT_TTL")]
[Description("TTL for JWTs")]
[Range(3600000, int.MaxValue)]
[RequiresRestart]
public int Ttl { get; init; } = 604800000;
}
/// <summary>
/// API key options.
/// </summary>
public class ApiKeyOptions : IValidatableObject
{
/// <summary>
/// Gets the API key value.
/// </summary>
[Description("API key value")]
[StringLength(255, MinimumLength = 16)]
[Secret]
public string Key { get; init; }
/// <summary>
/// Gets the role for the key.
/// </summary>
[Description("user role for the key; readonly, readwrite, administrator")]
[Enum(typeof(Role))]
public string Role { get; init; } = slskd.Authentication.Role.ReadOnly.ToString();
/// <summary>
/// Gets the comma separated list of CIDRs that are authorized to use the key.
/// </summary>
[Description("optional; comma separated list of CIDRs that are authorized to use the key")]
public string Cidr { get; init; } = "0.0.0.0/0,::/0";
/// <summary>
/// Extended validation.
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
foreach (var cidr in Cidr.Split(','))
{
try
{
if (cidr.StartsWith("::ffff", StringComparison.OrdinalIgnoreCase))
{
throw new Exception("IPv4 mapped IPv6 addresses are not allowed");
}
_ = IPAddressRange.Parse(cidr);
}
catch (Exception ex)
{
results.Add(new ValidationResult($"CIDR {cidr} is invalid: {ex.Message}"));
}
}
return results;
}
}
}
/// <summary>
/// HTTPS options.
/// </summary>
public class HttpsOptions
{
/// <summary>
/// Gets a value indicating whether HTTPS should be disabled.
/// </summary>
[Argument(default, "no-https")]
[EnvironmentVariable("NO_HTTPS")]
[Description("disable HTTPS")]
[RequiresRestart]
public bool Disabled { get; init; } = false;
/// <summary>
/// Gets the HTTPS listen port.
/// </summary>
[Argument('L', "https-port")]
[EnvironmentVariable("HTTPS_PORT")]
[Description("HTTPS listen port for web UI")]
[Range(1, 65535)]
[RequiresRestart]
public int Port { get; init; } = 5031;
/// <summary>
/// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTPS requests.
/// </summary>
[Argument(default, "https-ip-address")]
[EnvironmentVariable("HTTPS_IP_ADDRESS")]
[Description("IP addresses on which to listen for HTTPS requests")]
[IPAddress(allowCommaSeparatedValues: true)]
[RequiresRestart]
public string IpAddress { get; init; }
/// <summary>
/// Gets a value indicating whether HTTP requests should be redirected to HTTPS.
/// </summary>
[Argument('f', "force-https")]
[EnvironmentVariable("HTTPS_FORCE")]
[Description("redirect HTTP to HTTPS")]
[RequiresRestart]
public bool Force { get; init; } = false;
/// <summary>
/// Gets certificate options.
/// </summary>
[Validate]
[RequiresRestart]
public CertificateOptions Certificate { get; init; } = new CertificateOptions();
/// <summary>
/// Certificate options.
/// </summary>
[X509Certificate]
public class CertificateOptions
{
/// <summary>
/// Gets the path to the the X509 certificate .pfx file.
/// </summary>
[Argument(default, "https-cert-pfx")]
[EnvironmentVariable("HTTPS_CERT_PFX")]
[Description("path to X509 certificate .pfx")]
[FileExists(FileAccess.Read)]
[RequiresRestart]
public string Pfx { get; init; }
/// <summary>
/// Gets the password for the X509 certificate.
/// </summary>
[Argument(default, "https-cert-password")]
[EnvironmentVariable("HTTPS_CERT_PASSWORD")]
[Description("X509 certificate password")]
[RequiresRestart]
[Secret]
public string Password { get; init; }
}
}
/// <summary>
/// CORS options.
/// </summary>
public class CorsOptions : IValidatableObject
{
/// <summary>
/// Gets the list of CORS allowed origins.
/// </summary>
[Argument(default, "cors-allowed-origins")]
[EnvironmentVariable("CORS_ALLOWED_ORIGINS")]
[Description("list of allowed CORS origins")]
public string[] AllowedOrigins { get; init; } = Array.Empty<string>();
/// <summary>
/// Gets a value indicating whether CORS requests may include credentials.
/// </summary>
[Argument(default, "cors-allow-credentials")]
[EnvironmentVariable("CORS_ALLOW_CREDENTIALS")]
[Description("allow CORS credentials for allowed origins")]
public bool AllowCredentials { get; init; } = false;
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
var origins = AllowedOrigins
.Where(origin => !string.IsNullOrWhiteSpace(origin))
.Select(origin => origin.Trim())
.ToArray();
if (AllowCredentials && origins.Length == 0)
{
results.Add(new ValidationResult("CORS credentials require at least one allowed origin"));
}
foreach (var origin in origins)
{
if (origin == "*")
{
results.Add(new ValidationResult("CORS wildcard origins are not allowed; specify explicit origins"));
continue;
}
if (!Uri.TryCreate(origin, UriKind.Absolute, out var parsed) ||
(parsed.Scheme != Uri.UriSchemeHttp && parsed.Scheme != Uri.UriSchemeHttps))
{
results.Add(new ValidationResult($"CORS origin '{origin}' must be an absolute http:// or https:// URL"));
}
}
return results;
}
}
}
/// <summary>
/// Options for external integrations.
/// </summary>
public class IntegrationsOptions
{
/// <summary>
/// Gets VPN options.
/// </summary>
[Validate]
public VpnOptions Vpn { get; init; } = new();
/// <summary>
/// Gets webhook configuration.
/// </summary>
[Validate]
public Dictionary<string, WebhookOptions> Webhooks { get; init; } = [];
/// <summary>
/// Gets script configuration.
/// </summary>
[Validate]
public Dictionary<string, ScriptOptions> Scripts { get; init; } = [];
/// <summary>
/// Gets FTP options.
/// </summary>
[Validate]
public FtpOptions Ftp { get; init; } = new FtpOptions();
/// <summary>
/// Gets Pushbullet options.
/// </summary>
[Validate]
public PushbulletOptions Pushbullet { get; init; } = new PushbulletOptions();
/// <summary>
/// VPN options.
/// </summary>
public class VpnOptions : IValidatableObject
{
/// <summary>
/// Gets a value indicating whether the VPN integration is enabled.
/// </summary>
[Argument(default, "vpn")]
[EnvironmentVariable("VPN")]
[Description("enable VPN integration")]
[RequiresRestart]
public bool Enabled { get; init; } = false;
/// <summary>
/// Gets a value indicating whether the configured VPN supports dynamic port forwarding.
/// </summary>
[Argument(default, "vpn-port-forwarding")]
[EnvironmentVariable("VPN_PORT_FORWARDING")]
[Description("VPN supports dynamic port forwarding")]
public bool PortForwarding { get; init; } = false;
/// <summary>
/// Gets the rate at which to poll the configured VPN client for status updates, in milliseconds.
/// </summary>
[Argument(default, "vpn-polling-interval")]
[EnvironmentVariable("VPN_POLLING_INTERVAL")]
[Description("VPN client status polling interval")]
[Range(500, int.MaxValue)]
[RequiresRestart]
public int PollingInterval { get; init; } = 2500;
/// <summary>
/// Gets Gluetun options.
/// </summary>
[Validate]
public GluetunVpnOptions Gluetun { get; init; } = new GluetunVpnOptions();
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Enabled)
{
// as/if more VPN clients are added, update this logic to ensure that exactly one is configured
if (string.IsNullOrWhiteSpace(Gluetun?.Url))
{
yield return new ValidationResult("VPN is enabled but no client is configured");
yield break;
}
if (!Uri.TryCreate(Gluetun.Url, UriKind.Absolute, out _))
{
yield return new ValidationResult("The gluetun URL must be absolute, e.g. 'http://127.0.0.1:8000'");
}
}
}
/// <summary>
/// Gluetun options.
/// </summary>
public class GluetunVpnOptions
{
/// <summary>
/// Gets the Gluetun integration version.
/// </summary>
/// <remarks>
/// Only v1 of the Gluetun API exists right now; this is to ease a transition if there's ever a v2.
/// </remarks>
[Range(1, 1)]
public int Version { get; init; } = 1;
/// <summary>
/// Gets the fully qualified root URL for the Gluetun control server.
/// </summary>
[Argument(default, "vpn-gluetun-url")]
[EnvironmentVariable("VPN_GLUETUN_URL")]
[Description("URL for gluetun control server")]
public string Url { get; init; }
/// <summary>
/// Gets the timeout for HTTP requests to the Gluetun control server, in milliseconds.
/// </summary>
[Argument(default, "vpn-gluetun-timeout")]
[EnvironmentVariable("VPN_GLUETUN_TIMEOUT")]
[Description("timeout for HTTP requests to gluetun control server")]
[Range(500, 10_000)]
public int Timeout { get; init; } = 1000;
/// <summary>
/// Gets the username used for basic auth.
/// </summary>
[Argument(default, "vpn-gluetun-username")]
[EnvironmentVariable("VPN_GLUETUN_USERNAME")]
[Description("username for gluetun control server")]
public string Username { get; init; }
/// <summary>
/// Gets the password used for basic auth.
/// </summary>
[Argument(default, "vpn-gluetun-password")]
[EnvironmentVariable("VPN_GLUETUN_PASSWORD")]
[Description("password for gluetun control server")]
[Secret]
public string Password { get; init; }
/// <summary>
/// Gets the API key used for API key auth.
/// </summary>
[Argument(default, "vpn-gluetun-api-key")]
[EnvironmentVariable("VPN_GLUETUN_API_KEY")]
[Description("API key for gluetun control server")]
[Secret]
public string ApiKey { get; init; }
}
}
/// <summary>
/// Webhook configuration.
/// </summary>
public class WebhookOptions
{
/// <summary>
/// Gets the list of Event types that trigger the webhook.
/// </summary>
[Enum(typeof(EventType))]
public string[] On { get; init; } = Array.Empty<string>();
/// <summary>
/// Gets details about the webhook call.
/// </summary>
[Validate]
public WebhookHttpOptions Call { get; init; } = new WebhookHttpOptions();
/// <summary>
/// Gets the time to wait before timing out, in milliseconds.
/// </summary>
[Range(500, int.MaxValue)]
public int Timeout { get; init; } = 5000;
/// <summary>
/// Gets the retry configuration.
/// </summary>
[Validate]
public RetryOptions Retry { get; init; } = new RetryOptions();
}
/// <summary>
/// Webhook HTTP options.
/// </summary>
public class WebhookHttpOptions : IValidatableObject
{
/// <summary>
/// Gets the fully qualified URL for the webhook.
/// </summary>
[NotNullOrWhiteSpace]
[Secret]
public string Url { get; init; }
/// <summary>
/// Gets the HTTP headers to include with the webhook.
/// </summary>
[Validate]
public WebhookHttpHeader[] Headers { get; init; } = [];
/// <summary>
/// Gets a value indicating whether HTTPS certificate errors should be ignored.
/// </summary>
public bool IgnoreCertificateErrors { get; init; } = false;
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!Url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !Url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
yield return new ValidationResult($"The {nameof(Url)} field must contain a fully qualified URL, including protocol (e.g. http:// or https://)");
}
}
}
/// <summary>
/// Webhook HTTP header configuration.
/// </summary>
public class WebhookHttpHeader
{
/// <summary>
/// Gets the name of the header.
/// </summary>
[NotNullOrWhiteSpace]
public string Name { get; init; }
/// <summary>
/// Gets the header's value.
/// </summary>
[Secret]
public string Value { get; init; }
}
/// <summary>
/// Retry configuration.
/// </summary>
public class RetryOptions
{
/// <summary>
/// Gets the number of attempts to make before failing.
/// </summary>
[Range(1, int.MaxValue)]
public int Attempts { get; init; } = 1;
}
/// <summary>
/// Script configuration.
/// </summary>
public class ScriptOptions
{
/// <summary>
/// Gets the list of Event types that trigger the script.
/// </summary>
[Enum(typeof(EventType))]
public string[] On { get; init; } = Array.Empty<string>();
/// <summary>
/// Gets the shell script to invoke.
/// </summary>
public ScriptRunOptions Run { get; init; } = new ScriptRunOptions();
}
/// <summary>
/// Script run options.
/// </summary>
public class ScriptRunOptions : IValidatableObject
{
/// <summary>
/// Gets the shell command to run.
/// </summary>
[Secret]
public string Command { get; init; }
/// <summary>
/// Gets the executable to start.
/// </summary>
public string Executable { get; init; }
/// <summary>
/// Gets the arguments to pass to the executable.
/// </summary>
/// <remarks>
/// Mutually exclusive with <see cref="Arglist"/>.
/// </remarks>
[Secret]
public string Args { get; init; }
/// <summary>
/// Gets the list of arguments to pass to the executable.
/// </summary>
/// <remarks>
/// Mutually exclusive with <see cref="Args"/>.
/// </remarks>
public string[] Arglist { get; init; } = null;
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var cmdIsSet = !string.IsNullOrWhiteSpace(Command);
var exeIsSet = !string.IsNullOrWhiteSpace(Executable);
if ((cmdIsSet && exeIsSet) || (!cmdIsSet && !exeIsSet))
{
yield return new ValidationResult($"One and only one of the fields {nameof(Command)} or {nameof(Executable)} may be specified for a single script. If you intend to use the system shell, omit 'executable'. If you intend to use an executable other than the system shell, omit 'command' and specify either 'args' or 'args_list'.");
}
var argsIsSet = !string.IsNullOrWhiteSpace(Args);
var argsListIsSet = Arglist is not null;
if (argsIsSet && argsListIsSet)
{
yield return new ValidationResult($"Only one of the fields {nameof(Args)} or {nameof(Arglist)} may be specified for a single script. Specify 'args' if you intend to construct a single quoted string yourself, and specify 'args_list' if you'd like slskd to handle quoting for you.");
}
}
}
/// <summary>
/// FTP options.
/// </summary>
public class FtpOptions : IValidatableObject
{
/// <summary>
/// Gets a value indicating whether the FTP integration is enabled.
/// </summary>
[Argument(default, "ftp")]
[EnvironmentVariable("FTP")]
[Description("enable FTP integration")]
public bool Enabled { get; init; }
/// <summary>
/// Gets the FTP address.
/// </summary>
[Argument(default, "ftp-address")]
[EnvironmentVariable("FTP_ADDRESS")]
[Description("FTP address")]
public string Address { get; init; }
/// <summary>
/// Gets the FTP port.
/// </summary>
[Argument(default, "ftp-port")]
[EnvironmentVariable("FTP_PORT")]
[Description("FTP port")]
[Range(1, 65535)]
public int Port { get; init; } = 21;
/// <summary>
/// Gets the FTP encryption mode.
/// </summary>
[Argument(default, "ftp-encryption-mode")]
[EnvironmentVariable("FTP_ENCRYPTION_MODE")]
[Description("FTP encryption mode; none, implicit, explicit, auto")]
[Enum(typeof(FtpEncryptionMode))]
public string EncryptionMode { get; init; } = FtpEncryptionMode.Auto.ToString().ToLowerInvariant();
/// <summary>
/// Gets a value indicating whether FTP certificate errors should be ignored.
/// </summary>
[Argument(default, "ftp-ignore-certificate-errors")]
[EnvironmentVariable("FTP_IGNORE_CERTIFICATE_ERRORS")]
[Description("ignore FTP certificate errors")]
public bool IgnoreCertificateErrors { get; init; } = false;
/// <summary>
/// Gets the FTP username.
/// </summary>
[Argument(default, "ftp-username")]
[EnvironmentVariable("FTP_USERNAME")]
[Description("FTP username")]
public string Username { get; init; }
/// <summary>
/// Gets the FTP password.
/// </summary>
[Argument(default, "ftp-password")]
[EnvironmentVariable("FTP_PASSWORD")]
[Description("FTP password")]
[Secret]
public string Password { get; init; }
/// <summary>
/// Gets the remote path for uploads.
/// </summary>
[Argument(default, "ftp-remote-path")]
[EnvironmentVariable("FTP_REMOTE_PATH")]
[Description("remote path for FTP uploads")]
public string RemotePath { get; init; } = "/";
/// <summary>
/// Gets a value indicating whether existing files should be overwritten.
/// </summary>
[Argument(default, "ftp-overwrite-existing")]
[EnvironmentVariable("FTP_OVERWRITE_EXISTING")]
[Description("overwrite existing files when uploading to FTP")]
public bool OverwriteExisting { get; init; } = true;
/// <summary>
/// Gets the connection timeout value, in milliseconds.
/// </summary>
[Argument(default, "ftp-connection-timeout")]
[EnvironmentVariable("FTP_CONNECTION_TIMEOUT")]
[Description("FTP connection timeout, in milliseconds")]
[Range(0, int.MaxValue)]
public int ConnectionTimeout { get; init; } = 5000;
/// <summary>
/// Gets the number of times failing uploads will be retried.
/// </summary>
[Argument(default, "ftp-retry-attempts")]
[EnvironmentVariable("FTP_RETRY_ATTEMPTS")]
[Description("number of times failing FTP uploads will be retried")]
[Range(0, 5)]
public int RetryAttempts { get; init; } = 3;
/// <summary>
/// Extended validation.
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (Enabled && string.IsNullOrWhiteSpace(Address))
{
results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified."));
}
return results;
}
}
/// <summary>
/// Pushbullet options.
/// </summary>
public class PushbulletOptions : IValidatableObject
{
/// <summary>
/// Gets a value indicating whether the Pushbullet integration is enabled.
/// </summary>
[Argument(default, "pushbullet")]
[EnvironmentVariable("PUSHBULLET")]
[Description("enable Pushbullet integration")]
public bool Enabled { get; init; } = false;
/// <summary>
/// Gets the Pushbullet API access token.
/// </summary>
[Argument(default, "pushbullet-token")]
[EnvironmentVariable("PUSHBULLET_ACCESS_TOKEN")]
[Description("Pushbullet access token")]
[Secret]
public string AccessToken { get; init; }
/// <summary>
/// Gets the prefix for Pushbullet notification titles.
/// </summary>
[Argument(default, "pushbullet-prefix")]
[EnvironmentVariable("PUSHBULLET_NOTIFICATION_PREFIX")]
[Description("prefix for Pushbullet notification titles")]
public string NotificationPrefix { get; init; } = "From slskd:";
/// <summary>
/// Gets a value indicating whether a Pushbullet notification should be sent when a private message is received.
/// </summary>
[Argument(default, "pushbullet-notify-on-pm")]
[EnvironmentVariable("PUSHBULLET_NOTIFY_ON_PRIVATE_MESSAGE")]
[Description("send Pushbullet notifications when private messages are received")]
public bool NotifyOnPrivateMessage { get; init; } = true;
/// <summary>
/// Gets a value indicating whether a Pushbullet notification should be sent when the currently logged
/// in user's username is mentioned in a room.
/// </summary>
[Argument(default, "pushbullet-notify-on-room-mention")]
[EnvironmentVariable("PUSHBULLET_NOTIFY_ON_ROOM_MENTION")]
[Description("send Pushbullet notifications when your username is mentioned in a room")]
public bool NotifyOnRoomMention { get; init; } = true;
/// <summary>
/// Gets the number of times failing Pushbullet notifications will be retried.
/// </summary>
[Argument(default, "pushbullet-retry-attempts")]
[EnvironmentVariable("PUSHBULLET_RETRY_ATTEMPTS")]
[Description("number of times failing Pushbullet notifications will be retried")]
[Range(0, 5)]
public int RetryAttempts { get; init; } = 3;
/// <summary>
/// Gets the cooldown time for Pushbullet notifications, in milliseconds.
/// </summary>
[Argument(default, "pushbullet-cooldown")]
[EnvironmentVariable("PUSHBULLET_COOLDOWN_TIME")]
[Description("cooldown time for Pushbullet notifications, in milliseconds")]
public int CooldownTime { get; init; } = 900000; // 15 minutes
/// <summary>
/// Extended validation.
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (Enabled && string.IsNullOrWhiteSpace(AccessToken))
{
results.Add(new ValidationResult($"The Enabled field is true, but no AccessToken has been specified."));
}
return results;
}
}
}
}
}
|