sozu 2.0.2

sozu, a fast, reliable, hot reconfigurable HTTP reverse proxy
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
use std::{collections::BTreeMap, io::IsTerminal, net::SocketAddr, path::PathBuf};

use clap::{ArgAction, CommandFactory, FromArgMatches, Parser, Subcommand};
use sozu_command_lib::{
    proto::command::{LoadBalancingAlgorithms, TlsVersion},
    state::ClusterId as StateClusterId,
};

#[derive(Parser, PartialEq, Eq, Clone, Debug)]
#[clap(author, version, about)]
pub struct Args {
    #[clap(
        short = 'c',
        long = "config",
        global = true,
        help = "Sets a custom config file"
    )]
    pub config: Option<String>,
    #[clap(
        short = 't',
        long = "timeout",
        global = true,
        help = "Sets a custom timeout for commands (in milliseconds). 0 disables the timeout"
    )]
    pub timeout: Option<u64>,
    #[clap(
        short = 'j',
        long = "json",
        global = true,
        help = "display responses to queries in a JSON format"
    )]
    pub json: bool,
    #[clap(subcommand)]
    pub cmd: SubCmd,
}

impl paw::ParseArgs for Args {
    type Error = std::io::Error;

    fn parse_args() -> Result<Self, Self::Error> {
        const GREEN: &str = "\x1b[32m";
        const RED: &str = "\x1b[31m";
        const RESET: &str = "\x1b[0m";

        // ANSI escapes are emitted only when stdout is a real TTY. Redirected
        // output (`sozu --version > file`, package-metadata capture, systemd
        // journal) must stay raw ASCII so scripts and downstream parsers do
        // not ingest escape codes. The logger-colour preference is not
        // consulted because the logger is initialised after argument parsing,
        // so its thread-local state is always `false` at this point.
        let plain_features = env!("SOZU_BUILD_FEATURES");
        let use_color = std::io::stdout().is_terminal();
        let features: String = if use_color {
            plain_features
                .split(' ')
                .map(|flag| {
                    if let Some(name) = flag.strip_prefix('+') {
                        format!("{GREEN}+{name}{RESET}")
                    } else if let Some(name) = flag.strip_prefix('-') {
                        format!("{RED}-{name}{RESET}")
                    } else {
                        flag.to_owned()
                    }
                })
                .collect::<Vec<_>>()
                .join(" ")
        } else {
            plain_features.to_owned()
        };

        let long_version = format!(
            "{} ({})\n{}",
            env!("CARGO_PKG_VERSION"),
            env!("SOZU_BUILD_GIT"),
            features,
        );

        // clap requires &'static str for long_version. This intentional leak occurs once
        // during argument parsing (~300 bytes) and lasts for the process lifetime.
        let cmd = Self::command().long_version(long_version.leak() as &'static str);
        let matches = cmd.get_matches();
        Self::from_arg_matches(&matches)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))
    }
}

// The `Listener` variant balloons through its HttpListenerCmd/HttpsListenerCmd
// `Update` subvariants. Clap-derive's top-level enum can't be Boxed without
// breaking the derive; accept the disparity.
#[allow(clippy::large_enum_variant)]
#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum SubCmd {
    #[clap(name = "start", about = "launch the main process")]
    Start,
    #[clap(
        name = "worker",
        about = "start a worker (internal command, should not be used directly)"
    )]
    Worker {
        #[clap(long = "id", help = "worker identifier")]
        id: i32,
        #[clap(
            long = "fd",
            help = "IPC file descriptor of the worker to main channel"
        )]
        fd: i32,
        #[clap(
            long = "scm",
            help = "IPC SCM_RIGHTS file descriptor of the worker to main scm socket"
        )]
        scm: i32,
        #[clap(
            long = "configuration-state-fd",
            help = "configuration data file descriptor"
        )]
        configuration_state_fd: i32,
        #[clap(
            long = "command-buffer-size",
            help = "Worker's channel buffer size",
            default_value = "1000000"
        )]
        command_buffer_size: u64,
        #[clap(
            long = "max-command-buffer-size",
            help = "Worker's channel max buffer size"
        )]
        max_command_buffer_size: Option<u64>,
    },
    #[clap(
        name = "main",
        about = "start a new main process (internal command, should not be used directly)"
    )]
    Main {
        #[clap(long = "fd", help = "IPC file descriptor")]
        fd: i32,
        #[clap(long = "upgrade-fd", help = "upgrade data file descriptor")]
        upgrade_fd: i32,
        #[clap(
            long = "command-buffer-size",
            help = "Main process channel buffer size",
            default_value = "1000000"
        )]
        command_buffer_size: u64,
        #[clap(
            long = "max-command-buffer-size",
            help = "Main process channel max buffer size"
        )]
        max_command_buffer_size: Option<u64>,
    },

    // sozu command line
    #[clap(name = "shutdown", about = "shuts down the proxy")]
    Shutdown {
        #[clap(long = "hard", help = "do not wait for connections to finish")]
        hard: bool,
    },
    #[clap(
        name = "upgrade",
        about = "upgrade the main process OR a specific worker. Specify a longer timeout."
    )]
    Upgrade {
        #[clap(long = "worker", help = "upgrade a specific worker")]
        worker: Option<u32>,
    },

    #[clap(name = "status", about = "gets information on the running workers")]
    Status,
    #[clap(
        name = "metrics",
        about = "gets statistics on the main process and its workers"
    )]
    Metrics {
        #[clap(subcommand)]
        cmd: MetricsCmd,
    },
    #[clap(name = "logging", about = "change logging level")]
    Logging {
        #[clap(name = "filter")]
        filter: String,
    },
    #[clap(name = "state", about = "state management")]
    State {
        #[clap(subcommand)]
        cmd: StateCmd,
    },
    #[clap(
        name = "reload",
        about = "Reloads routing configuration (clusters, frontends and backends)"
    )]
    Reload {
        #[clap(
            short = 'f',
            long = "file",
            help = "use a different configuration file from the current one"
        )]
        file: Option<String>,
    },
    #[clap(name = "cluster", about = "cluster management")]
    Cluster {
        #[clap(subcommand)]
        cmd: ClusterCmd,
    },
    #[clap(name = "backend", about = "backend management")]
    Backend {
        #[clap(subcommand)]
        cmd: BackendCmd,
    },
    #[clap(name = "frontend", about = "frontend management")]
    Frontend {
        #[clap(subcommand)]
        cmd: FrontendCmd,
    },
    #[clap(name = "listener", about = "listener management")]
    Listener {
        #[clap(subcommand)]
        cmd: ListenerCmd,
    },
    #[clap(name = "certificate", about = "list, add and remove certificates")]
    Certificate {
        #[clap(subcommand)]
        cmd: CertificateCmd,
    },
    #[clap(name = "config", about = "configuration file management")]
    Config {
        #[clap(subcommand)]
        cmd: ConfigCmd,
    },
    #[clap(
        name = "events",
        about = "receive sozu events about the status of backends"
    )]
    Events,
    #[clap(
        name = "connection-limit",
        about = "manage the per-(cluster, source-IP) connection limit at runtime"
    )]
    ConnectionLimit {
        #[clap(subcommand)]
        cmd: ConnectionLimitCmd,
    },
    /// Live operator TUI: btop/htop-style overview of clusters, backends,
    /// listeners, and H2 health. Built behind the `tui` Cargo feature so
    /// production binaries stay lean. v1 is read-only; the cardinality lease
    /// is auto-applied (DETAIL_BACKEND, TTL ~60s) and self-clears on exit.
    #[cfg(feature = "tui")]
    #[clap(
        name = "top",
        about = "live operator TUI (btop/htop-style) for clusters, backends, listeners, H2"
    )]
    Top {
        /// Data poll interval in milliseconds; the render loop is capped
        /// independently at 30 fps regardless of this value.
        #[clap(long = "refresh-ms", default_value_t = 1000)]
        refresh_ms: u64,
        /// Disable mouse capture. Useful inside multiplexers that mis-route
        /// SGR mouse events.
        #[clap(long = "no-mouse")]
        no_mouse: bool,
        /// Skin name. Looked up under `$XDG_CONFIG_HOME/sozu/skins/<name>.toml`;
        /// `SOZU_TOP_SKIN` env var takes precedence when both are set.
        #[clap(long = "skin")]
        skin: Option<String>,
        /// Override the cardinality lease level. Default: `Backend`
        /// (auto-elevate, lease self-expires server-side).
        #[clap(long = "detail", value_enum)]
        detail: Option<TopDetail>,
        /// Lease TTL in seconds; the renewer halves this for renewals.
        /// Server clamps at 300s.
        #[clap(long = "lease-ttl-seconds", default_value_t = 60)]
        lease_ttl_seconds: u32,
        /// Render N frames to stdout and exit (test affordance, no terminal
        /// control). Mutually exclusive with interactive mode.
        #[clap(long = "snapshot")]
        snapshot: Option<u32>,
        /// Drive one data tick + one render tick and exit (test affordance).
        #[clap(long = "tick-once")]
        tick_once: bool,
        /// Force a glyph mode; auto-detect by default
        /// (Braille → Block → TTY-ASCII).
        #[clap(long = "glyphs", value_enum)]
        glyphs: Option<TopGlyphs>,
    },
}

/// `--detail` clap value enum for `sozu top`. Mirrors `MetricDetailLevel`
/// without leaking the proto-generated type into the CLI surface.
#[cfg(feature = "tui")]
#[derive(clap::ValueEnum, PartialEq, Eq, Clone, Copy, Debug)]
pub enum TopDetail {
    /// Proxy-only counters (smallest keyspace).
    Process,
    /// Adds per-listener (frontend) breakdown.
    Frontend,
    /// Adds per-cluster aggregation (current Sōzu default).
    Cluster,
    /// Adds per-backend aggregation (cluster + backend, highest cardinality).
    Backend,
}

/// `--glyphs` clap value enum for `sozu top`. Three modes mirroring btop:
/// Braille (highest density), Block (compatible Unicode), TTY-ASCII fallback.
#[cfg(feature = "tui")]
#[derive(clap::ValueEnum, PartialEq, Eq, Clone, Copy, Debug)]
pub enum TopGlyphs {
    /// Highest-density Unicode Braille mosaics. Default when the terminal
    /// reports Unicode-capable locale + adequate font.
    Braille,
    /// Plain Unicode block elements; broadest Unicode terminal compatibility.
    Block,
    /// 7-bit ASCII fallback for `linux`/`dumb` TERMs and serial consoles.
    Tty,
}

#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum ConnectionLimitCmd {
    #[clap(
        name = "set",
        about = "set the global per-(cluster, source-IP) connection limit. `0` disables the feature."
    )]
    Set {
        #[clap(
            help = "maximum simultaneous connections per (cluster, source-IP) pair (0 = unlimited)"
        )]
        limit: u64,
    },
    #[clap(
        name = "remove",
        about = "disable the global per-(cluster, source-IP) limit (equivalent to `set 0`)"
    )]
    Remove,
    #[clap(
        name = "show",
        about = "show the current global per-(cluster, source-IP) connection limit"
    )]
    Show,
}

#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum MetricsCmd {
    #[clap(name = "enable", about = "Enables local metrics collection")]
    Enable,
    #[clap(name = "disable", about = "Disables local metrics collection")]
    Disable,
    #[clap(name = "clear", about = "Deletes local metrics data")]
    Clear,
    #[clap(
        name = "get",
        about = "get all metrics, filtered, or a list of available metrics"
    )]
    Get {
        #[clap(short, long, help = "list the available metrics on the proxy level")]
        list: bool,
        #[clap(short, long, help = "refresh metrics results (in seconds)")]
        refresh: Option<u32>,
        #[clap(
            short = 'n',
            long = "names",
            help = "Filter by metric names. Coma-separated list.",
            use_value_delimiter = true
        )]
        names: Vec<String>,
        #[clap(
            short = 'k',
            long = "clusters",
            help = "list of cluster ids (= application id)",
            use_value_delimiter = true
        )]
        clusters: Vec<String>,
        #[clap(
            short = 'b',
            long="backends",
            help="coma-separated list of backends, 'one_backend_id,other_backend_id'",
            use_value_delimiter = true
            // parse(try_from_str = split_slash)
        )]
        backends: Vec<String>,
        #[clap(
            long = "no-clusters",
            help = "get only the metrics of main process and workers (no cluster metrics)"
        )]
        no_clusters: bool,
        #[clap(
            short = 'w',
            long = "workers",
            help = "display metrics of each worker, without merging by metric name or cluster id (takes more space)"
        )]
        workers: bool,
    },
}

#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum StateCmd {
    #[clap(name = "save", about = "Save state to that file")]
    Save {
        #[clap(short = 'f', long = "file")]
        file: String,
    },
    #[clap(name = "load", about = "Load state from that file")]
    Load {
        #[clap(short = 'f', long = "file")]
        file: String,
    },
    #[clap(
        name = "stats",
        about = "show the counts of requests that were received since startup"
    )]
    Stats,
}

#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum ClusterCmd {
    #[clap(
        name = "list",
        about = "Query clusters, all of them, or filtered by id or domain"
    )]
    List {
        #[clap(short = 'i', long = "id", help = "cluster identifier")]
        id: Option<String>,
        #[clap(short = 'd', long = "domain", help = "cluster domain name")]
        domain: Option<String>,
    },
    #[clap(name = "remove", about = "Remove a cluster")]
    Remove {
        #[clap(short = 'i', long = "id", help = "cluster id")]
        id: String,
    },
    #[clap(name = "add", about = "Add a cluster")]
    Add {
        #[clap(short = 'i', long = "id", help = "cluster id")]
        id: String,
        #[clap(short = 's', long = "sticky-session")]
        sticky_session: bool,
        #[clap(short = 'r', long = "https-redirect")]
        https_redirect: bool,
        #[clap(
            long = "send-proxy",
            help = "Enforces use of the PROXY protocol version 2 over any connection established to this server."
        )]
        send_proxy: bool,
        #[clap(
            long = "expect-proxy",
            help = "Configures the client-facing connection to receive a PROXY protocol header version 2"
        )]
        expect_proxy: bool,
        #[clap(
            long = "load-balancing-policy",
            help = "Configures the load balancing policy. Possible values are 'roundrobin', 'random' or 'leastconnections'"
        )]
        load_balancing_policy: LoadBalancingAlgorithms,
        #[clap(
            long = "http2",
            help = "Use HTTP/2 for backend connections to this cluster"
        )]
        http2: bool,
        #[clap(
            long = "https-redirect-port",
            help = "Port to use when building the Location header for an https_redirect (defaults to the listener's effective HTTPS port)"
        )]
        https_redirect_port: Option<u32>,
        #[clap(
            long = "www-authenticate",
            help = "Realm string emitted in the WWW-Authenticate header on a 401 response (e.g. 'Basic realm=\"sozu\"')"
        )]
        www_authenticate: Option<String>,
        #[clap(
            long = "authorized-hash",
            help = "Authorized credential, formatted as 'username:hex(sha256(password))'. Repeatable. Generate with: printf 'user:pass' | sed -n 's/^[^:]*://p' | { read p; printf 'user:%s' \"$(printf %s \"$p\" | sha256sum | cut -d' ' -f1)\"; }"
        )]
        authorized_hash: Vec<String>,
        #[clap(
            long = "answer",
            help = "Per-status HTTP answer template for this cluster. Format: <code>=<body> for an inline literal (the value is taken verbatim, no disk I/O), or <code>=file://<path> to load the body off disk. Repeatable. Examples: --answer 503='HTTP/1.1 503 Service Unavailable\\r\\n\\r\\nbusy' , --answer 503=file:///etc/sozu/503.http ."
        )]
        answer: Vec<String>,
    },
    #[clap(
        name = "h2",
        about = "Enable or disable HTTP/2 for backend connections"
    )]
    H2 {
        #[clap(subcommand)]
        cmd: ClusterH2Cmd,
    },
    #[clap(name = "health-check", about = "Configure backend health checks")]
    HealthCheck {
        #[clap(subcommand)]
        cmd: HealthCheckCmd,
    },
}

#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum ClusterH2Cmd {
    #[clap(name = "enable", about = "Enable HTTP/2 for backend connections")]
    Enable {
        #[clap(short = 'i', long = "id", help = "cluster id")]
        id: String,
    },
    #[clap(name = "disable", about = "Disable HTTP/2 for backend connections")]
    Disable {
        #[clap(short = 'i', long = "id", help = "cluster id")]
        id: String,
    },
}

#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum HealthCheckCmd {
    #[clap(name = "set", about = "Set or update the health check for a cluster")]
    Set {
        #[clap(short = 'i', long = "id", help = "cluster id")]
        id: String,
        #[clap(
            short = 'u',
            long = "uri",
            help = "health check URI path (e.g. /health)"
        )]
        uri: String,
        #[clap(
            long = "interval",
            help = "check interval in seconds",
            default_value = "10"
        )]
        interval: u32,
        #[clap(
            long = "timeout",
            help = "check timeout in seconds",
            default_value = "5"
        )]
        timeout: u32,
        #[clap(
            long = "healthy-threshold",
            help = "consecutive successes to mark healthy",
            default_value = "3"
        )]
        healthy_threshold: u32,
        #[clap(
            long = "unhealthy-threshold",
            help = "consecutive failures to mark unhealthy",
            default_value = "3"
        )]
        unhealthy_threshold: u32,
        #[clap(
            long = "expected-status",
            help = "expected HTTP status code (0 = any 2xx)",
            default_value = "0"
        )]
        expected_status: u32,
    },
    #[clap(name = "remove", about = "Remove the health check from a cluster")]
    Remove {
        #[clap(short = 'i', long = "id", help = "cluster id")]
        id: String,
    },
    #[clap(name = "list", about = "List health check configurations")]
    List {
        #[clap(
            short = 'i',
            long = "id",
            help = "filter by cluster id (lists all if omitted)"
        )]
        id: Option<String>,
    },
}

#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum BackendCmd {
    #[clap(name = "remove", about = "Remove a backend")]
    Remove {
        #[clap(short = 'i', long = "id")]
        id: String,
        #[clap(long = "backend-id")]
        backend_id: String,
        #[clap(
            short = 'a',
            long = "address",
            help = "server address, format: IP:port"
        )]
        address: SocketAddr,
    },
    #[clap(name = "add", about = "Add a backend")]
    Add {
        #[clap(short = 'i', long = "id")]
        id: String,
        #[clap(long = "backend-id")]
        backend_id: String,
        #[clap(
            short = 'a',
            long = "address",
            help = "server address, format: IP:port"
        )]
        address: SocketAddr,
        #[clap(
            short = 's',
            long = "sticky-id",
            help = "value for the sticky session cookie"
        )]
        sticky_id: Option<String>,
        #[clap(short = 'b', long = "backup", help = "set backend as a backup backend")]
        backup: Option<bool>,
    },
}

#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum FrontendCmd {
    #[clap(name = "http", about = "HTTP frontend management")]
    Http {
        #[clap(subcommand)]
        cmd: HttpFrontendCmd,
    },
    #[clap(name = "https", about = "HTTPS frontend management")]
    Https {
        #[clap(subcommand)]
        cmd: HttpFrontendCmd,
    },
    #[clap(name = "tcp", about = "TCP frontend management")]
    Tcp {
        #[clap(subcommand)]
        cmd: TcpFrontendCmd,
    },
    #[clap(name = "list", about = "List frontends using filters")]
    List {
        #[clap(long = "http", help = "filter for http frontends")]
        http: bool,
        #[clap(long = "https", help = "filter for https frontends")]
        https: bool,
        #[clap(long = "tcp", help = "filter for tcp frontends")]
        tcp: bool,
        #[clap(
            short = 'd',
            long = "domain",
            help = "filter by domain name (for http & https frontends)"
        )]
        domain: Option<String>,
    },
}

#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum ClusterId {
    /// traffic will go to the backend servers with this cluster id
    Id {
        /// traffic will go to the backend servers with this cluster id
        id: String,
    },
    /// traffic to this frontend will be rejected with HTTP 401
    Deny,
}

#[allow(clippy::from_over_into)]
impl std::convert::Into<Option<StateClusterId>> for ClusterId {
    fn into(self) -> Option<StateClusterId> {
        match self {
            ClusterId::Deny => None,
            ClusterId::Id { id } => Some(id),
        }
    }
}

#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum HttpFrontendCmd {
    #[clap(name = "add")]
    Add {
        #[clap(
            short = 'a',
            long = "address",
            help = "frontend address, format: IP:port"
        )]
        address: SocketAddr,
        #[clap(subcommand, name = "cluster_id")]
        cluster_id: ClusterId,
        #[clap(long = "hostname", aliases = &["host"])]
        hostname: String,
        #[clap(short = 'p', long = "path-prefix", help = "URL prefix of the frontend")]
        path_prefix: Option<String>,
        #[clap(
            long = "path-regex",
            help = "the frontend URL path should match this regex"
        )]
        path_regex: Option<String>,
        #[clap(
            long = "path-equals",
            help = "the frontend URL path should equal this regex"
        )]
        path_equals: Option<String>,
        #[clap(short = 'm', long = "method", help = "HTTP method")]
        method: Option<String>,
        #[clap(long = "tags", help = "Specify tag (key-value pair) to apply on front-end (example: 'key=value, other-key=other-value')", value_parser = parse_tags)]
        tags: Option<BTreeMap<String, String>>,
        #[clap(
            long = "redirect",
            help = "Redirect policy. Possible values: 'forward' (default), 'permanent', 'unauthorized'"
        )]
        redirect: Option<String>,
        #[clap(
            long = "redirect-scheme",
            help = "Scheme for permanent-redirect Location URLs. Possible values: 'use-same' (default), 'use-http', 'use-https'"
        )]
        redirect_scheme: Option<String>,
        #[clap(
            long = "redirect-template",
            help = "Optional template applied when emitting a permanent redirect. Supports %REDIRECT_LOCATION."
        )]
        redirect_template: Option<String>,
        #[clap(
            long = "rewrite-host",
            help = "Rewrite request host with this template. Supports $HOST[n] / $PATH[n] capture placeholders."
        )]
        rewrite_host: Option<String>,
        #[clap(
            long = "rewrite-path",
            help = "Rewrite request path with this template. Same grammar as --rewrite-host."
        )]
        rewrite_path: Option<String>,
        #[clap(
            long = "rewrite-port",
            help = "Override the port in the rewritten URL (1..=65535)."
        )]
        rewrite_port: Option<u32>,
        #[clap(
            long = "required-auth",
            help = "Require a valid Authorization: Basic header on this frontend."
        )]
        required_auth: bool,
        #[clap(
            long = "header",
            help = "Header mutation, format: <position>=<name>=<value>. Position is 'request', 'response', or 'both'. Empty <value> deletes the header (HAProxy del-header parity). Repeatable. To replace a header, pass it twice: first with an empty value (deletes the existing one), then with the new value (sets it). The runtime applies all deletes before any sets."
        )]
        header: Vec<String>,
        #[clap(
            long = "hsts-max-age",
            help = "HSTS (RFC 6797) `max-age` directive in seconds. Setting any of the --hsts-* flags enables HSTS on this frontend. Defaults to 31536000 (1 year, HSTS preload list minimum) when --hsts-max-age is omitted but another --hsts-* flag is set. `0` is the RFC 6797 §11.4 kill switch."
        )]
        hsts_max_age: Option<u32>,
        #[clap(
            long = "hsts-include-subdomains",
            help = "Append `; includeSubDomains` to the rendered HSTS header. Implies HSTS enabled."
        )]
        hsts_include_subdomains: bool,
        #[clap(
            long = "hsts-preload",
            help = "Append `; preload` to the rendered HSTS header (Chrome HSTS preload list — see https://hstspreload.org/). Implies HSTS enabled. Opt-in only; once submitted, removal from the preload list is slow and partial (RFC 6797 §14.2)."
        )]
        hsts_preload: bool,
        #[clap(
            long = "hsts-disabled",
            conflicts_with_all = ["hsts_max_age", "hsts_include_subdomains", "hsts_preload", "hsts_force_replace_backend"],
            help = "Explicitly disable HSTS on this frontend, suppressing any inherited listener-default HSTS. Mutually exclusive with --hsts-max-age / --hsts-include-subdomains / --hsts-preload / --hsts-force-replace-backend."
        )]
        hsts_disabled: bool,
        #[clap(
            long = "hsts-force-replace-backend",
            help = "Override any backend-supplied `Strict-Transport-Security` header with sozu's typed policy instead of preserving it (RFC 6797 §6.1 backend-wins is the default). Use when upstream backends emit a stale or weak HSTS policy that the operator wants to harden centrally. Implies HSTS enabled."
        )]
        hsts_force_replace_backend: bool,
    },
    #[clap(name = "remove")]
    Remove {
        #[clap(
            short = 'a',
            long = "address",
            help = "frontend address, format: IP:port"
        )]
        address: SocketAddr,
        #[clap(subcommand, name = "cluster_id")]
        cluster_id: ClusterId,
        #[clap(long = "hostname", aliases = &["host"])]
        hostname: String,
        #[clap(short = 'p', long = "path-prefix", help = "URL prefix of the frontend")]
        path_prefix: Option<String>,
        #[clap(
            long = "path-regex",
            help = "the frontend URL path should match this regex"
        )]
        path_regex: Option<String>,
        #[clap(
            long = "path-equals",
            help = "the frontend URL path should equal this regex"
        )]
        path_equals: Option<String>,
        #[clap(short = 'm', long = "method", help = "HTTP method")]
        method: Option<String>,
    },
}

#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum TcpFrontendCmd {
    #[clap(name = "add")]
    Add {
        #[clap(
            short = 'i',
            long = "id",
            help = "the id of the cluster to which the frontend belongs"
        )]
        id: String,
        #[clap(
            short = 'a',
            long = "address",
            help = "frontend address, format: IP:port"
        )]
        address: SocketAddr,
        #[clap(
            long = "tags",
            help = "Specify tag (key-value pair) to apply on front-end (example: 'key=value, other-key=other-value')",
            value_parser = parse_tags
        )]
        tags: Option<BTreeMap<String, String>>,
    },
    #[clap(name = "remove")]
    Remove {
        #[clap(
            short = 'i',
            long = "id",
            help = "the id of the cluster to which the frontend belongs"
        )]
        id: String,
        #[clap(
            short = 'a',
            long = "address",
            help = "frontend address, format: IP:port"
        )]
        address: SocketAddr,
    },
}

#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum ListenerCmd {
    #[clap(name = "http", about = "HTTP listener management")]
    Http {
        #[clap(subcommand)]
        cmd: HttpListenerCmd,
    },
    #[clap(name = "https", about = "HTTPS listener management")]
    Https {
        #[clap(subcommand)]
        cmd: HttpsListenerCmd,
    },
    #[clap(name = "tcp", about = "TCP listener management")]
    Tcp {
        #[clap(subcommand)]
        cmd: TcpListenerCmd,
    },
    #[clap(name = "list", about = "List all listeners")]
    List,
}

// `Update` carries ~20 Option<T> fields and is the dominant variant; accept
// the size disparity rather than Box the variant (clap-derive doesn't help
// when you Box a subcommand struct).
#[allow(clippy::large_enum_variant)]
#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum HttpListenerCmd {
    #[clap(name = "add")]
    Add {
        #[clap(short = 'a')]
        address: SocketAddr,
        #[clap(
            long = "public-address",
            help = "a different IP than the one the socket sees, for logs and forwarded headers"
        )]
        public_address: Option<SocketAddr>,
        #[clap(
            long = "answer-404",
            help = "path to file of the 404 answer sent to the client when a frontend is not found"
        )]
        answer_404: Option<String>,
        #[clap(
            long = "answer-503",
            help = "path to file of the 503 answer sent to the client when a cluster has no backends available"
        )]
        answer_503: Option<String>,
        #[clap(
            long = "expect-proxy",
            help = "Configures the client socket to receive a PROXY protocol header"
        )]
        expect_proxy: bool,
        #[clap(long = "sticky-name", help = "sticky session cookie name")]
        sticky_name: Option<String>,
        #[clap(
            long = "front-timeout",
            help = "maximum time of inactivity for a frontend socket"
        )]
        front_timeout: Option<u32>,
        #[clap(
            long = "back-timeout",
            help = "maximum time of inactivity for a backend socket"
        )]
        back_timeout: Option<u32>,
        #[clap(
            long = "request-timeout",
            help = "maximum time to receive a request since the connection started"
        )]
        request_timeout: Option<u32>,
        #[clap(
            long = "connect-timeout",
            help = "maximum time to connect to a backend server"
        )]
        connect_timeout: Option<u32>,
    },
    #[clap(name = "remove")]
    Remove {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
    },
    #[clap(name = "activate")]
    Activate {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
    },
    #[clap(name = "deactivate")]
    Deactivate {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
    },
    #[clap(name = "update", about = "Patch a running HTTP listener in place")]
    Update {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
        #[clap(
            long = "public-address",
            help = "a different IP than the one the socket sees, for logs and forwarded headers"
        )]
        public_address: Option<SocketAddr>,
        #[clap(long = "sticky-name", help = "sticky session cookie name")]
        sticky_name: Option<String>,
        #[clap(
            long = "front-timeout",
            help = "maximum time of inactivity for a frontend socket, in seconds"
        )]
        front_timeout: Option<u32>,
        #[clap(
            long = "back-timeout",
            help = "maximum time of inactivity for a backend socket, in seconds"
        )]
        back_timeout: Option<u32>,
        #[clap(
            long = "connect-timeout",
            help = "maximum time to connect to a backend server, in seconds"
        )]
        connect_timeout: Option<u32>,
        #[clap(
            long = "request-timeout",
            help = "maximum time to receive a complete request, in seconds"
        )]
        request_timeout: Option<u32>,

        // Paired boolean flags — fold to Option<bool> in the request builder
        #[clap(long = "expect-proxy", action = ArgAction::SetTrue, overrides_with = "no_expect_proxy",
               help = "Enable PROXY protocol header on the client socket")]
        expect_proxy: bool,
        #[clap(long = "no-expect-proxy", action = ArgAction::SetTrue, overrides_with = "expect_proxy",
               help = "Disable PROXY protocol header on the client socket")]
        no_expect_proxy: bool,

        // H2 flood knobs
        #[clap(
            long,
            help = "Maximum RST_STREAM frames per second window (CVE-2023-44487, CVE-2019-9514); must be >= 1"
        )]
        h2_max_rst_stream_per_window: Option<u32>,
        #[clap(
            long,
            help = "Maximum PING frames per second window (CVE-2019-9512); must be >= 1"
        )]
        h2_max_ping_per_window: Option<u32>,
        #[clap(
            long,
            help = "Maximum SETTINGS frames per second window (CVE-2019-9515); must be >= 1"
        )]
        h2_max_settings_per_window: Option<u32>,
        #[clap(
            long,
            help = "Maximum empty DATA frames per second window (CVE-2019-9518); must be >= 1"
        )]
        h2_max_empty_data_per_window: Option<u32>,
        #[clap(
            long,
            help = "Maximum CONTINUATION frames per header block (CVE-2024-27316); must be >= 1"
        )]
        h2_max_continuation_frames: Option<u32>,
        #[clap(
            long,
            help = "Maximum accumulated protocol anomalies before ENHANCE_YOUR_CALM; must be >= 1"
        )]
        h2_max_glitch_count: Option<u32>,
        #[clap(
            long,
            help = "Connection-level receive window size in bytes (RFC 9113 §6.9.2)"
        )]
        h2_initial_connection_window: Option<u32>,
        #[clap(
            long,
            help = "Maximum concurrent H2 streams (SETTINGS_MAX_CONCURRENT_STREAMS); must be >= 1"
        )]
        h2_max_concurrent_streams: Option<u32>,
        #[clap(
            long,
            help = "Shrink threshold ratio for recycled stream slots; must be >= 1"
        )]
        h2_stream_shrink_ratio: Option<u32>,
        #[clap(
            long,
            help = "Absolute lifetime cap on RST_STREAM frames received (CVE-2023-44487)"
        )]
        h2_max_rst_stream_lifetime: Option<u64>,
        #[clap(
            long,
            help = "Lifetime cap on abusive RST_STREAM frames — Rapid Reset signature"
        )]
        h2_max_rst_stream_abusive_lifetime: Option<u64>,
        #[clap(
            long,
            help = "Absolute lifetime cap on RST_STREAM frames emitted by the server (CVE-2025-8671)"
        )]
        h2_max_rst_stream_emitted_lifetime: Option<u64>,
        #[clap(
            long,
            help = "Maximum HPACK-decoded header list size per request (RFC 9113 §6.5.2)"
        )]
        h2_max_header_list_size: Option<u32>,
        #[clap(long, help = "Maximum HPACK dynamic table size accepted from the peer")]
        h2_max_header_table_size: Option<u32>,
        #[clap(
            long,
            help = "Maximum materialized header fields per request, incl. cookie crumbs (HTTP/2 header-bomb mitigation)"
        )]
        h2_max_header_fields: Option<u32>,
        #[clap(long, help = "Per-stream idle timeout in seconds")]
        h2_stream_idle_timeout_seconds: Option<u32>,
        #[clap(
            long,
            help = "Seconds to wait after GOAWAY(NO_ERROR) before force-closing; 0 = wait forever"
        )]
        h2_graceful_shutdown_deadline_seconds: Option<u32>,
        #[clap(
            long,
            help = "Maximum connection-level (stream 0) WINDOW_UPDATE frames per window (must be >= 1)"
        )]
        h2_max_window_update_stream0_per_window: Option<u32>,
        #[clap(
            long,
            help = "Name of the correlation header injected per request (e.g. \"Sozu-Id\")"
        )]
        sozu_id_header: Option<String>,

        // Listener-default HTTP answer bodies (file paths)
        #[clap(long, help = "path to file for the 301 answer body")]
        answer_301: Option<PathBuf>,
        #[clap(long, help = "path to file for the 401 answer body")]
        answer_401: Option<PathBuf>,
        #[clap(long, help = "path to file for the 404 answer body")]
        answer_404: Option<PathBuf>,
        #[clap(long, help = "path to file for the 408 answer body")]
        answer_408: Option<PathBuf>,
        #[clap(long, help = "path to file for the 413 answer body")]
        answer_413: Option<PathBuf>,
        #[clap(long, help = "path to file for the 421 answer body")]
        answer_421: Option<PathBuf>,
        #[clap(
            long,
            help = "path to file for the 429 answer body (per-(cluster, source-IP) connection limit)"
        )]
        answer_429: Option<PathBuf>,
        #[clap(long, help = "path to file for the 502 answer body")]
        answer_502: Option<PathBuf>,
        #[clap(long, help = "path to file for the 503 answer body")]
        answer_503: Option<PathBuf>,
        #[clap(long, help = "path to file for the 504 answer body")]
        answer_504: Option<PathBuf>,
        #[clap(long, help = "path to file for the 507 answer body")]
        answer_507: Option<PathBuf>,
    },
}

#[allow(clippy::large_enum_variant)]
#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum HttpsListenerCmd {
    #[clap(name = "add")]
    Add {
        #[clap(short = 'a')]
        address: SocketAddr,
        #[clap(
            long = "public-address",
            help = "a different IP than the one the socket sees, for logs and forwarded headers"
        )]
        public_address: Option<SocketAddr>,
        #[clap(
            long = "answer-404",
            help = "path to file of the 404 answer sent to the client when a frontend is not found"
        )]
        answer_404: Option<String>,
        #[clap(
            long = "answer-503",
            help = "path to file of the 503 answer sent to the client when a cluster has no backends available"
        )]
        answer_503: Option<String>,
        #[clap(long = "tls-versions", help = "list of TLS versions to use")]
        tls_versions: Vec<TlsVersion>,
        #[clap(
            long = "tls-cipher-list",
            help = "List of TLS cipher list to use (TLSv1.2 and TLSv1.3)"
        )]
        cipher_list: Option<Vec<String>>,
        #[clap(
            long = "expect-proxy",
            help = "Configures the client socket to receive a PROXY protocol header"
        )]
        expect_proxy: bool,
        #[clap(long = "sticky-name", help = "sticky session cookie name")]
        sticky_name: Option<String>,
        #[clap(
            long = "front-timeout",
            help = "maximum time of inactivity for a frontend socket"
        )]
        front_timeout: Option<u32>,
        #[clap(
            long = "back-timeout",
            help = "maximum time of inactivity for a frontend socket"
        )]
        back_timeout: Option<u32>,
        #[clap(
            long = "request-timeout",
            help = "maximum time to receive a request since the connection started"
        )]
        request_timeout: Option<u32>,
        #[clap(
            long = "connect-timeout",
            help = "maximum time to connect to a backend server"
        )]
        connect_timeout: Option<u32>,
    },
    #[clap(name = "remove")]
    Remove {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
    },
    #[clap(name = "activate")]
    Activate {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
    },
    #[clap(name = "deactivate")]
    Deactivate {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
    },
    #[clap(name = "update", about = "Patch a running HTTPS listener in place")]
    Update {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
        #[clap(
            long = "public-address",
            help = "a different IP than the one the socket sees, for logs and forwarded headers"
        )]
        public_address: Option<SocketAddr>,
        #[clap(long = "sticky-name", help = "sticky session cookie name")]
        sticky_name: Option<String>,
        #[clap(
            long = "front-timeout",
            help = "maximum time of inactivity for a frontend socket, in seconds"
        )]
        front_timeout: Option<u32>,
        #[clap(
            long = "back-timeout",
            help = "maximum time of inactivity for a backend socket, in seconds"
        )]
        back_timeout: Option<u32>,
        #[clap(
            long = "connect-timeout",
            help = "maximum time to connect to a backend server, in seconds"
        )]
        connect_timeout: Option<u32>,
        #[clap(
            long = "request-timeout",
            help = "maximum time to receive a complete request, in seconds"
        )]
        request_timeout: Option<u32>,

        // Paired boolean flags — fold to Option<bool> in the request builder
        #[clap(long = "expect-proxy", action = ArgAction::SetTrue, overrides_with = "no_expect_proxy",
               help = "Enable PROXY protocol header on the client socket")]
        expect_proxy: bool,
        #[clap(long = "no-expect-proxy", action = ArgAction::SetTrue, overrides_with = "expect_proxy",
               help = "Disable PROXY protocol header on the client socket")]
        no_expect_proxy: bool,
        #[clap(long = "strict-sni-binding", action = ArgAction::SetTrue, overrides_with = "no_strict_sni_binding",
               help = "Require :authority/Host to match the TLS SNI (CWE-346/CWE-444)")]
        strict_sni_binding: bool,
        #[clap(long = "no-strict-sni-binding", action = ArgAction::SetTrue, overrides_with = "strict_sni_binding",
               help = "Allow :authority/Host to differ from the TLS SNI")]
        no_strict_sni_binding: bool,
        #[clap(long = "disable-http11", action = ArgAction::SetTrue, overrides_with = "enable_http11",
               help = "Only accept H2 connections; HTTP/1.1 is dropped at handshake")]
        disable_http11: bool,
        #[clap(long = "enable-http11", action = ArgAction::SetTrue, overrides_with = "disable_http11",
               help = "Re-enable HTTP/1.1 connections alongside H2")]
        enable_http11: bool,

        // ALPN: either --alpn-protocols h2,http/1.1 (set) or --reset-alpn (empty vec = default)
        #[clap(
            long,
            value_delimiter = ',',
            conflicts_with = "reset_alpn",
            help = "Set ALPN protocols to advertise (comma-separated: h2,http/1.1)"
        )]
        alpn_protocols: Option<Vec<String>>,
        #[clap(long = "reset-alpn", action = ArgAction::SetTrue,
               help = "Reset ALPN to the built-in default ([\"h2\", \"http/1.1\"])")]
        reset_alpn: bool,

        // H2 flood knobs
        #[clap(
            long,
            help = "Maximum RST_STREAM frames per second window (CVE-2023-44487, CVE-2019-9514); must be >= 1"
        )]
        h2_max_rst_stream_per_window: Option<u32>,
        #[clap(
            long,
            help = "Maximum PING frames per second window (CVE-2019-9512); must be >= 1"
        )]
        h2_max_ping_per_window: Option<u32>,
        #[clap(
            long,
            help = "Maximum SETTINGS frames per second window (CVE-2019-9515); must be >= 1"
        )]
        h2_max_settings_per_window: Option<u32>,
        #[clap(
            long,
            help = "Maximum empty DATA frames per second window (CVE-2019-9518); must be >= 1"
        )]
        h2_max_empty_data_per_window: Option<u32>,
        #[clap(
            long,
            help = "Maximum CONTINUATION frames per header block (CVE-2024-27316); must be >= 1"
        )]
        h2_max_continuation_frames: Option<u32>,
        #[clap(
            long,
            help = "Maximum accumulated protocol anomalies before ENHANCE_YOUR_CALM; must be >= 1"
        )]
        h2_max_glitch_count: Option<u32>,
        #[clap(
            long,
            help = "Connection-level receive window size in bytes (RFC 9113 §6.9.2)"
        )]
        h2_initial_connection_window: Option<u32>,
        #[clap(
            long,
            help = "Maximum concurrent H2 streams (SETTINGS_MAX_CONCURRENT_STREAMS); must be >= 1"
        )]
        h2_max_concurrent_streams: Option<u32>,
        #[clap(
            long,
            help = "Shrink threshold ratio for recycled stream slots; must be >= 1"
        )]
        h2_stream_shrink_ratio: Option<u32>,
        #[clap(
            long,
            help = "Absolute lifetime cap on RST_STREAM frames received (CVE-2023-44487)"
        )]
        h2_max_rst_stream_lifetime: Option<u64>,
        #[clap(
            long,
            help = "Lifetime cap on abusive RST_STREAM frames — Rapid Reset signature"
        )]
        h2_max_rst_stream_abusive_lifetime: Option<u64>,
        #[clap(
            long,
            help = "Absolute lifetime cap on RST_STREAM frames emitted by the server (CVE-2025-8671)"
        )]
        h2_max_rst_stream_emitted_lifetime: Option<u64>,
        #[clap(
            long,
            help = "Maximum HPACK-decoded header list size per request (RFC 9113 §6.5.2)"
        )]
        h2_max_header_list_size: Option<u32>,
        #[clap(long, help = "Maximum HPACK dynamic table size accepted from the peer")]
        h2_max_header_table_size: Option<u32>,
        #[clap(
            long,
            help = "Maximum materialized header fields per request, incl. cookie crumbs (HTTP/2 header-bomb mitigation)"
        )]
        h2_max_header_fields: Option<u32>,
        #[clap(long, help = "Per-stream idle timeout in seconds")]
        h2_stream_idle_timeout_seconds: Option<u32>,
        #[clap(
            long,
            help = "Seconds to wait after GOAWAY(NO_ERROR) before force-closing; 0 = wait forever"
        )]
        h2_graceful_shutdown_deadline_seconds: Option<u32>,
        #[clap(
            long,
            help = "Maximum connection-level (stream 0) WINDOW_UPDATE frames per window (must be >= 1)"
        )]
        h2_max_window_update_stream0_per_window: Option<u32>,
        #[clap(
            long,
            help = "Name of the correlation header injected per request (e.g. \"Sozu-Id\")"
        )]
        sozu_id_header: Option<String>,

        // Listener-default HTTP answer bodies (file paths)
        #[clap(long, help = "path to file for the 301 answer body")]
        answer_301: Option<PathBuf>,
        #[clap(long, help = "path to file for the 401 answer body")]
        answer_401: Option<PathBuf>,
        #[clap(long, help = "path to file for the 404 answer body")]
        answer_404: Option<PathBuf>,
        #[clap(long, help = "path to file for the 408 answer body")]
        answer_408: Option<PathBuf>,
        #[clap(long, help = "path to file for the 413 answer body")]
        answer_413: Option<PathBuf>,
        #[clap(long, help = "path to file for the 421 answer body")]
        answer_421: Option<PathBuf>,
        #[clap(
            long,
            help = "path to file for the 429 answer body (per-(cluster, source-IP) connection limit)"
        )]
        answer_429: Option<PathBuf>,
        #[clap(long, help = "path to file for the 502 answer body")]
        answer_502: Option<PathBuf>,
        #[clap(long, help = "path to file for the 503 answer body")]
        answer_503: Option<PathBuf>,
        #[clap(long, help = "path to file for the 504 answer body")]
        answer_504: Option<PathBuf>,
        #[clap(long, help = "path to file for the 507 answer body")]
        answer_507: Option<PathBuf>,

        // ── HSTS (RFC 6797) listener-default knobs ──
        // Same surface as `frontend https add`. The full `HstsConfig`
        // patch follows the documented full-object replacement
        // semantics on `UpdateHttpsListenerConfig.hsts`: when any of
        // these flags is supplied the listener's HSTS policy is
        // replaced wholesale, and `Router::refresh_inheriting_hsts`
        // reflows the new policy onto every frontend that inherits
        // from this listener (no per-frontend override).
        #[clap(
            long = "hsts-max-age",
            help = "HSTS (RFC 6797) `max-age` directive in seconds. Setting any of the --hsts-* flags replaces the listener's HSTS policy and refreshes inheriting frontends. Defaults to 31536000 (1 year, HSTS preload list minimum) when --hsts-max-age is omitted but another --hsts-* flag is set. `0` is the RFC 6797 §11.4 kill switch."
        )]
        hsts_max_age: Option<u32>,
        #[clap(
            long = "hsts-include-subdomains",
            help = "Append `; includeSubDomains` to the rendered HSTS header. Implies HSTS enabled."
        )]
        hsts_include_subdomains: bool,
        #[clap(
            long = "hsts-preload",
            help = "Append `; preload` to the rendered HSTS header (Chrome HSTS preload list — see https://hstspreload.org/). Implies HSTS enabled. Opt-in only; once submitted, removal from the preload list is slow and partial (RFC 6797 §14.2)."
        )]
        hsts_preload: bool,
        #[clap(
            long = "hsts-disabled",
            conflicts_with_all = ["hsts_max_age", "hsts_include_subdomains", "hsts_preload", "hsts_force_replace_backend"],
            help = "Explicitly disable the listener-default HSTS, suppressing it for inheriting frontends. Mutually exclusive with --hsts-max-age / --hsts-include-subdomains / --hsts-preload / --hsts-force-replace-backend."
        )]
        hsts_disabled: bool,
        #[clap(
            long = "hsts-force-replace-backend",
            help = "Override any backend-supplied `Strict-Transport-Security` header with sōzu's typed policy instead of preserving it (RFC 6797 §6.1 backend-wins is the default). Implies HSTS enabled."
        )]
        hsts_force_replace_backend: bool,
    },
}

#[allow(clippy::large_enum_variant)]
#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum TcpListenerCmd {
    #[clap(name = "add")]
    Add {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
        #[clap(
            long = "public-address",
            help = "a different IP than the one the socket sees, for logs and forwarded headers"
        )]
        public_address: Option<SocketAddr>,
        #[clap(
            long = "expect-proxy",
            help = "Configures the client socket to receive a PROXY protocol header"
        )]
        expect_proxy: bool,
    },
    #[clap(name = "remove")]
    Remove {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
    },
    #[clap(name = "activate")]
    Activate {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
    },
    #[clap(name = "deactivate")]
    Deactivate {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
    },
    #[clap(name = "update", about = "Patch a running TCP listener in place")]
    Update {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
        #[clap(
            long = "public-address",
            help = "a different IP than the one the socket sees, for logs and forwarded headers"
        )]
        public_address: Option<SocketAddr>,
        #[clap(
            long = "front-timeout",
            help = "maximum time of inactivity for a frontend socket, in seconds"
        )]
        front_timeout: Option<u32>,
        #[clap(
            long = "back-timeout",
            help = "maximum time of inactivity for a backend socket, in seconds"
        )]
        back_timeout: Option<u32>,
        #[clap(
            long = "connect-timeout",
            help = "maximum time to connect to a backend server, in seconds"
        )]
        connect_timeout: Option<u32>,

        // Paired boolean flags — fold to Option<bool> in the request builder
        #[clap(long = "expect-proxy", action = ArgAction::SetTrue, overrides_with = "no_expect_proxy",
               help = "Enable PROXY protocol header on the client socket")]
        expect_proxy: bool,
        #[clap(long = "no-expect-proxy", action = ArgAction::SetTrue, overrides_with = "expect_proxy",
               help = "Disable PROXY protocol header on the client socket")]
        no_expect_proxy: bool,
    },
}

#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum CertificateCmd {
    #[clap(
        name = "list",
        about = "Query all certificates, or filtered by fingerprint or domain name.
This command queries the state of Sōzu by default, but can show results for all workers.
Use the --json option to get a much more verbose result, with certificate contents."
    )]
    List {
        #[clap(
            short = 'f',
            long = "fingerprint",
            help = "get the certificate for a given fingerprint"
        )]
        fingerprint: Option<String>,
        #[clap(
            short = 'd',
            long = "domain",
            help = "list certificates for a domain name"
        )]
        domain: Option<String>,
        #[clap(
            short = 'w',
            long = "workers",
            help = "Show results for each worker (slower)"
        )]
        query_workers: bool,
    },
    #[clap(name = "add", about = "Add a certificate")]
    Add {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
        #[clap(long = "certificate", help = "path to the certificate")]
        certificate: String,
        #[clap(long = "certificate-chain", help = "path to the certificate chain")]
        chain: String,
        #[clap(long = "key", help = "path to the key")]
        key: String,
        #[clap(long = "tls-versions", help = "accepted TLS versions for this certificate",
                value_parser = parse_tls_versions)]
        tls_versions: Vec<TlsVersion>,
    },
    #[clap(name = "remove", about = "Remove a certificate")]
    Remove {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
        #[clap(aliases = &["cert"], long = "certificate", help = "path to the certificate")]
        certificate: Option<String>,
        #[clap(short = 'f', long = "fingerprint", help = "certificate fingerprint")]
        fingerprint: Option<String>,
    },
    #[clap(name = "replace", about = "Replace an existing certificate")]
    Replace {
        #[clap(
            short = 'a',
            long = "address",
            help = "listener address, format: IP:port"
        )]
        address: SocketAddr,
        #[clap(long = "new-certificate", help = "path to the new certificate")]
        certificate: String,
        #[clap(
            long = "new-certificate-chain",
            help = "path to the new certificate chain"
        )]
        chain: String,
        #[clap(long = "new-key", help = "path to the new key")]
        key: String,
        #[clap(
            aliases = &["old-cert"],
            long = "old-certificate",
            help = "path to the old certificate"
        )]
        old_certificate: Option<String>,
        #[clap(
            short = 'f',
            long = "fingerprint",
            help = "old certificate fingerprint"
        )]
        old_fingerprint: Option<String>,
        #[clap(long = "tls-versions", help = "accepted TLS versions for this certificate",
                value_parser = parse_tls_versions)]
        tls_versions: Vec<TlsVersion>,
    },
}

#[derive(Subcommand, PartialEq, Eq, Clone, Debug)]
pub enum ConfigCmd {
    #[clap(name = "check", about = "check configuration file syntax and exit")]
    Check,
}

fn parse_tls_versions(i: &str) -> Result<TlsVersion, String> {
    match i {
        "TLSv1" => {
            eprintln!("warning: TLS 1.0 is deprecated and insecure (RFC 8996)");
            Ok(TlsVersion::TlsV10)
        }
        "TLS_V11" => {
            eprintln!("warning: TLS 1.1 is deprecated and insecure (RFC 8996)");
            Ok(TlsVersion::TlsV11)
        }
        "TLS_V12" => Ok(TlsVersion::TlsV12),
        "TLS_V13" => Ok(TlsVersion::TlsV13),
        s => Err(format!("unrecognized TLS version: {s}")),
    }
}

fn parse_tags(string_to_parse: &str) -> Result<BTreeMap<String, String>, String> {
    let mut tags: BTreeMap<String, String> = BTreeMap::new();

    for s in string_to_parse.split(',') {
        if let Some((key, value)) = s.trim().split_once('=') {
            tags.insert(key.to_owned(), value.to_owned());
        } else {
            return Err(format!(
                "something went wrong while parsing the tags '{string_to_parse}'"
            ));
        }
    }

    Ok(tags)
}

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

        let tags_to_parse =
            "owner=John ,uuid=0dd8d7b1-a50a-461a-b1f9-5211a5f45a83=, hexkey=#846e84";

        assert_eq!(
            Ok(BTreeMap::from([
                ("owner".to_owned(), "John".to_owned()),
                (
                    "uuid".to_owned(),
                    "0dd8d7b1-a50a-461a-b1f9-5211a5f45a83=".to_owned(),
                ),
                ("hexkey".to_owned(), "#846e84".to_owned())
            ])),
            parse_tags(tags_to_parse)
        );
    }

    // ── HSTS flags on `sozu listener https update` ──
    // Validates the clap surface exposed for the hot listener-default
    // HSTS patch path (UpdateHttpsListenerConfig.hsts). The destructure
    // has to stay in lock-step with `request_builder.rs::https_listener_command`
    // — these tests catch a missed field rename or a forgotten dispatch
    // arg the next time clap-derive grows another `Update` knob.

    fn extract_https_update(args: super::Args) -> super::HttpsListenerCmd {
        match args.cmd {
            super::SubCmd::Listener {
                cmd: super::ListenerCmd::Https { cmd },
            } => cmd,
            other => panic!("expected listener https subcommand, got {other:?}"),
        }
    }

    #[test]
    fn listener_https_update_parses_hsts_enabling_flags() {
        use super::*;

        let args = Args::try_parse_from([
            "sozu",
            "listener",
            "https",
            "update",
            "-a",
            "127.0.0.1:443",
            "--hsts-max-age",
            "31536000",
            "--hsts-include-subdomains",
            "--hsts-force-replace-backend",
        ])
        .expect("clap should accept --hsts-* on listener https update");

        let HttpsListenerCmd::Update {
            hsts_max_age,
            hsts_include_subdomains,
            hsts_preload,
            hsts_disabled,
            hsts_force_replace_backend,
            ..
        } = extract_https_update(args)
        else {
            panic!("expected HttpsListenerCmd::Update");
        };
        assert_eq!(hsts_max_age, Some(31_536_000));
        assert!(hsts_include_subdomains);
        assert!(!hsts_preload);
        assert!(!hsts_disabled);
        assert!(hsts_force_replace_backend);
    }

    #[test]
    fn listener_https_update_parses_hsts_disabled_alone() {
        use super::*;

        let args = Args::try_parse_from([
            "sozu",
            "listener",
            "https",
            "update",
            "-a",
            "127.0.0.1:443",
            "--hsts-disabled",
        ])
        .expect("clap should accept --hsts-disabled on listener https update");

        let HttpsListenerCmd::Update {
            hsts_disabled,
            hsts_max_age,
            hsts_include_subdomains,
            hsts_preload,
            hsts_force_replace_backend,
            ..
        } = extract_https_update(args)
        else {
            panic!("expected HttpsListenerCmd::Update");
        };
        assert!(hsts_disabled);
        assert_eq!(hsts_max_age, None);
        assert!(!hsts_include_subdomains);
        assert!(!hsts_preload);
        assert!(!hsts_force_replace_backend);
    }

    #[test]
    fn listener_https_update_no_hsts_flags_inherits_listener_default() {
        use super::*;

        // Sanity: the new flags are all optional and the existing
        // surface still parses with no `--hsts-*` argument at all.
        let args = Args::try_parse_from([
            "sozu",
            "listener",
            "https",
            "update",
            "-a",
            "127.0.0.1:443",
            "--front-timeout",
            "120",
        ])
        .expect("clap should accept the existing listener-update surface unchanged");

        let HttpsListenerCmd::Update {
            hsts_max_age,
            hsts_include_subdomains,
            hsts_preload,
            hsts_disabled,
            hsts_force_replace_backend,
            front_timeout,
            ..
        } = extract_https_update(args)
        else {
            panic!("expected HttpsListenerCmd::Update");
        };
        assert_eq!(hsts_max_age, None);
        assert!(!hsts_include_subdomains);
        assert!(!hsts_preload);
        assert!(!hsts_disabled);
        assert!(!hsts_force_replace_backend);
        assert_eq!(front_timeout, Some(120));
    }

    #[test]
    fn listener_https_update_hsts_disabled_conflicts_with_max_age() {
        use super::*;

        let err = Args::try_parse_from([
            "sozu",
            "listener",
            "https",
            "update",
            "-a",
            "127.0.0.1:443",
            "--hsts-disabled",
            "--hsts-max-age",
            "31536000",
        ])
        .expect_err("clap should reject --hsts-disabled with --hsts-max-age");
        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
    }

    #[test]
    fn listener_https_update_hsts_disabled_conflicts_with_force_replace_backend() {
        use super::*;

        let err = Args::try_parse_from([
            "sozu",
            "listener",
            "https",
            "update",
            "-a",
            "127.0.0.1:443",
            "--hsts-disabled",
            "--hsts-force-replace-backend",
        ])
        .expect_err("clap should reject --hsts-disabled with --hsts-force-replace-backend");
        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
    }
}