sop 0.8.2

Rust Interface for the Stateless OpenPGP Interface
Documentation
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
//! Command-line frontend for SOP.
//!
//! This is an implementation of the SOP Command-Line protocol in
//! terms of the trait [`crate::SOP`], hence it can be shared between
//! SOP implementations.
//!
//! Via the "cliv" feature, it can also produce a smaller standalone
//! binary that only implements the sopv subset.
//!
//! To use, add this snippet to `Cargo.toml`:
//!
//! ```toml
//! [[bin]]
//! name = "my-sop"
//! required-features = ["cli"]
//!
//! [[bin]]
//! name = "my-sopv"
//! required-features = ["cliv"]
//!
//! [features]
//! cli = ["sop/cli"]
//! cliv = ["sop/cliv"]
//! ```
//!
//! And create `src/bin/my-sop.rs` and `src/bin/my-sopv.rs`,
//! containing, respectively, something along the lines of:
//!
//! ```rust,ignore
//! fn main() {
//!     // Be clever and inspect argv[0].
//!     let argv0 = std::env::args_os().next();
//!     let variant = if argv0
//!         .map(|s| s.to_string_lossy().contains("my-sopv"))
//!         .unwrap_or(false)
//!     {
//!         // Restrict to the verification subset.
//!         sop::cli::Variant::Verification
//!     } else {
//!         sop::cli::Variant::Full
//!     };
//!
//!     sop::cli::main(&mut MySOPImplementation::default(),
//!                    sop::cli::Variant::Verification);
//! }
//! ```
//!
//! And for the verification subset:
//!
//! ```rust,ignore
//! fn main() {
//!     sop::cli::main(&mut MySOPImplementation::default(),
//!                    sop::cli::Variant::Verification);
//! }
//! ```
//!
//! Note: If you don't need to tweak your implementation for the
//! verification subset of SOP, you can also build both binaries from
//! the same source.
//!
//! ## Generating shell completions and manual pages
//!
//! To create shell completions, add this snippet to `Cargo.toml`:
//!
//! ```toml
//! [build-dependencies]
//! sop = "..."
//! ```
//!
//! And create `build.rs` along the lines of:
//!
//! ```rust,no_run
//! use std::{
//!     env,
//!     error::Error,
//!     fs,
//!     path::PathBuf,
//! };
//!
//! use sop::cli::Variant;
//!
//! #[path = "src/version.rs"]
//! mod version;
//!
//! fn main() {
//!     #[cfg(feature = "cli")]
//!     cli("sqop", Variant::Full).unwrap();
//!
//!     #[cfg(feature = "cliv")]
//!     cli("sqopv", Variant::Verification).unwrap();
//! }
//!
//! /// Writes shell completions and man pages.
//! fn cli(name: &'static str, variant: Variant) -> Result<(), Box<dyn Error>> {
//!     let version = version::Version::with_name(name);
//!
//!     sop::cli::write_shell_completions2(
//!         variant, name, asset_out_dir("shell-completions")?)?;
//!     sop::cli::write_man_pages(
//!         variant, &version, "Sequoia PGP",
//!         asset_out_dir("man-pages")?)?;
//!
//!     Ok(())
//! }
//!
//! /// Variable name to control the asset out directory with.
//! const ASSET_OUT_DIR: &str = "ASSET_OUT_DIR";
//!
//! /// Returns the directory to write the given assets to.
//! #[allow(dead_code)]
//! fn asset_out_dir(asset: &str) -> Result<PathBuf, Box<dyn Error>> {
//!     println!("cargo:rerun-if-env-changed={}", ASSET_OUT_DIR);
//!     let outdir: PathBuf =
//!         env::var_os(ASSET_OUT_DIR).unwrap_or_else(
//!             || env::var_os("OUT_DIR").expect("OUT_DIR not set")).into();
//!     if outdir.exists() && ! outdir.is_dir() {
//!         return Err(
//!             format!("{}={:?} is not a directory", ASSET_OUT_DIR, outdir).into());
//!     }
//!
//!     let path = outdir.join(asset);
//!     fs::create_dir_all(&path)?;
//!     Ok(path)
//! }
//! ```
//!
//! # Features and limitations
//!
//! - The special designator `@FD:` is only available on UNIX-like systems.
//!
//! - On Windows, certs and keys provided via the `@ENV:` special
//!   designator must be ASCII armored and well-formed UTF-8.

use std::{
    io::{self, Write},
    path::Path,
};

use anyhow::{Context, Result};

use chrono::{DateTime, NaiveTime, offset::Utc};
use clap::{CommandFactory, FromArgMatches, Parser};

use crate::{
    Save,
    Load,
    SOP,
};

#[cfg(feature = "cli")]
use crate::{
    ArmorLabel,
    EncryptAs,
    InlineSignAs,
    Password,
    SignAs,
};

/// The last meaningful update of the command line interface.
///
/// This will be used as-is in the generated manual pages.
pub const LAST_UPDATE_TIMESTAMP: &'static str =
// !!! Update this with every release changing the interface. !!!
//
// date +"%B %Y"
    "February 2025";

#[derive(Debug, Parser)]
#[clap(about = "An implementation of the Stateless OpenPGP Command Line Interface")]
#[clap(disable_version_flag(true))]
struct Cli<O: clap::Subcommand> {
    /// Emit verbose output for debugging.
    #[clap(long = "debug", global = true)]
    debug: bool,

    #[clap(subcommand)]
    operation: O,
}

/// Variant of the SOP specification.
#[derive(Clone, Copy)]
pub enum Variant {
    /// The full functionality.
    Full,

    /// The verification subset.
    Verification,
}

impl<O: clap::Subcommand> Cli<O> {
    fn with_version<'v, V>(v: &V, variant: Variant)
                       -> Result<clap::Command>
    where
        V: crate::ops::Version<'v> + ?Sized
    {
        // Do a little dance to supply name and version to clap.
        let (name, version, about) = {
            let v = v.frontend()?;
            (
                v.name.clone(),
                v.version.clone(),
                format!("An implementation of the {}\
                         Stateless OpenPGP Command \
                         Line Interface using {} {}",
                        match variant {
                            Variant::Full => "",
                            Variant::Verification =>
                                "verification-only subset of the ",
                        },
                        v.name, v.version),
            )
        };

        Ok(Cli::<O>::command()
           .name(Box::leak(name.into_boxed_str()) as &str)
           .about(Box::leak(about.into_boxed_str()) as &str)
           .version(Box::leak(version.into_boxed_str()) as &str))
    }
}

/// All the operations of the verification subset of SOP.
#[derive(Debug, Parser)]
enum VerificationSubset {
    /// Prints version information.
    ///
    /// Invoked without arguments, returns name and version of the SOP
    /// implementation.
    #[clap(display_order = 100)]
    #[cfg(any(feature = "cliv", feature = "cli"))]
    Version {
        /// Returns name and version of the primary underlying OpenPGP
        /// toolkit.
        #[clap(long, conflicts_with("extended"), conflicts_with("sop_spec"), conflicts_with("sopv"))]
        backend: bool,

        /// Returns multiple lines of name and version information.
        ///
        /// The first line is the name and version of the SOP
        /// implementation, but the rest have no defined structure.
        #[clap(long, conflicts_with("backend"), conflicts_with("sop_spec"), conflicts_with("sopv"))]
        extended: bool,

        /// Returns the latest version of the SOP spec that is
        /// implemented.
        #[clap(long, conflicts_with("backend"), conflicts_with("extended"), conflicts_with("sopv"))]
        sop_spec: bool,

        /// Returns "1.0\n" if the sopv subset is implemented.
        #[clap(long, conflicts_with("backend"), conflicts_with("extended"), conflicts_with("sop_spec"))]
        sopv: bool,
    },

    /// Verifies Detached Signatures.
    #[clap(display_order = 500)]
    #[cfg(any(feature = "cli", feature = "cliv"))]
    Verify {
        /// Consider signatures before this date invalid.
        #[clap(long)]
        not_before: Option<NotBefore>,
        /// Consider signatures after this date invalid.
        #[clap(long)]
        not_after: Option<NotAfter>,
        /// Signatures to verify.
        signatures: String,
        /// Certs for verification.
        certs: Vec<String>,
    },

    /// Verifies Inline-Signed Messages.
    #[clap(display_order = 751)]
    #[cfg(any(feature = "cli", feature = "cliv"))]
    InlineVerify {
        /// Consider signatures before this date invalid.
        #[clap(long)]
        not_before: Option<NotBefore>,
        /// Consider signatures after this date invalid.
        #[clap(long)]
        not_after: Option<NotAfter>,
        /// Write verification result here.
        #[clap(long)]
        verifications_out: Option<String>,
        /// Certs for verification.
        certs: Vec<String>,
    },
}

/// All the operations of the full SOP.
#[derive(Debug, Parser)]
enum Operation {
    ///
    #[command(flatten)]
    VerificationSubset(VerificationSubset),

    /// Emits a list of profiles supported by the identified
    /// subcommand.
    #[clap(display_order = 150)]
    #[cfg(feature = "cli")]
    ListProfiles {
        subcommand: String,
    },
    /// Generates a Secret Key.
    #[clap(display_order = 200)]
    #[cfg(feature = "cli")]
    GenerateKey {
        /// Don't ASCII-armor output.
        #[clap(long)]
        no_armor: bool,
        /// Select the profile to use for key generation.
        #[clap(long)]
        profile: Option<String>,
        /// Create a signing-only key.
        #[clap(long)]
        signing_only: bool,
        /// Protect the newly generated key with the given password.
        #[clap(long)]
        with_key_password: Option<String>,
        /// UserIDs for the generated key.
        userids: Vec<String>,
    },

    /// Updates a key's password.
    ///
    /// The output will be the same set of OpenPGP Transferable Secret
    /// Keys as the input, but with all secret key material locked
    /// according to the password indicated by the
    /// `--new-key-password` option (or, with no password at all, if
    /// `--new-key-password` is absent).  Note that
    /// `--old-key-password` can be supplied multiple times, and each
    /// supplied password will be tried as a means to unlock any
    /// locked key material encountered.  It will normalize a
    /// Transferable Secret Key to use a single password even if it
    /// originally had distinct passwords locking each of the subkeys.
    ///
    /// If any secret key packet is locked but cannot be unlocked with
    /// any of the supplied `--old-key-password` arguments, this
    /// subcommand should fail with `KEY_IS_PROTECTED`.
    #[clap(display_order = 210)]
    #[cfg(feature = "cli")]
    ChangeKeyPassword {
        /// Don't ASCII-armor output.
        #[clap(long)]
        no_armor: bool,
        /// The new password to lock the key with, or just unlock the
        /// key if the option is absent.
        #[clap(long)]
        new_key_password: Option<String>,
        /// Unlock the keys with these passwords.
        #[clap(long, number_of_values = 1)]
        old_key_password: Vec<String>,
    },

    /// Creates a Revocation Certificate.
    ///
    /// Generate a revocation certificate for each Transferable Secret
    /// Key found.
    #[clap(display_order = 220)]
    #[cfg(feature = "cli")]
    RevokeKey {
        /// Don't ASCII-armor output.
        #[clap(long)]
        no_armor: bool,
        /// Unlock the keys with these passwords.
        #[clap(long, number_of_values = 1)]
        with_key_password: Vec<String>,
    },

    /// Extracts a Certificate from a Secret Key.
    #[clap(display_order = 230)]
    #[cfg(feature = "cli")]
    ExtractCert {
        /// Don't ASCII-armor output.
        #[clap(long)]
        no_armor: bool,
    },

    /// Keep a Secret Key Up-To-Date.
    #[clap(display_order = 240)]
    #[cfg(feature = "cli")]
    UpdateKey {
        /// Don't ASCII-armor output.
        #[clap(long)]
        no_armor: bool,

        /// Don't make the updated key encryption-capable if it isn't
        /// already.
        #[clap(long)]
        signing_only: bool,

        /// Don't advertise support for capabilities that aren't
        /// already advertised by the key.
        #[clap(long)]
        no_added_capabilities: bool,

        /// Unlock the keys with these passwords.
        #[clap(long, number_of_values = 1)]
        with_key_password: Vec<String>,

        /// Merge updates into the key.
        #[clap(long, number_of_values = 1)]
        merge_certs: Vec<String>,
    },

    /// Merge OpenPGP Certificates.
    #[clap(display_order = 250)]
    #[cfg(feature = "cli")]
    MergeCerts {
        /// Don't ASCII-armor output.
        #[clap(long)]
        no_armor: bool,

        /// Merge updates into the certs.
        certs: Vec<String>,
    },

    /// Certify OpenPGP Certificate User IDs.
    #[clap(display_order = 300)]
    #[cfg(feature = "cli")]
    CertifyUserid {
        /// Don't ASCII-armor output.
        #[clap(long)]
        no_armor: bool,

        /// Certify the specified user IDs.
        #[clap(long, required = true, number_of_values = 1)]
        userid: Vec<String>,

        /// Unlock the keys with these passwords.
        #[clap(long, number_of_values = 1)]
        with_key_password: Vec<String>,

        /// Don't require self-signatures on the user IDs to be
        /// certified.
        #[clap(long)]
        no_require_self_sig: bool,

        /// Create certifications using these keys.
        keys: Vec<String>,
    },

    /// Validate a User ID in an OpenPGP Certificate.
    #[clap(display_order = 320)]
    #[cfg(feature = "cli")]
    ValidateUserid {
        /// Treat USERID as an e-mail address, and matched only
        /// against the e-mail address part of each correctly bound
        /// User ID.
        #[clap(long)]
        addr_spec_only: bool,

        /// Evaluate the validity of the User ID at the specified
        /// time, not at the current time.
        #[clap(long)]
        validate_at: Option<Timestamp>,

        /// The User ID to validate.
        userid: String,

        /// Authority OpenPGP certificates, i.e. trust roots.
        #[clap(required = true)]
        certs: Vec<String>,
    },

    /// Creates Detached Signatures.
    #[clap(display_order = 400)]
    #[cfg(feature = "cli")]
    Sign {
        /// Don't ASCII-armor output.
        #[clap(long)]
        no_armor: bool,
        /// Sign binary data or UTF-8 text.
        #[clap(default_value = "binary", long = "as")]
        as_: SignAs,
        /// Emit the digest algorithm used to the specified file.
        #[clap(long)]
        micalg_out: Option<String>,
        /// Try to decrypt the signing KEYS with these passwords.
        #[clap(long, number_of_values = 1)]
        with_key_password: Vec<String>,
        /// Keys for signing.
        keys: Vec<String>,
    },
    /// Encrypts a Message.
    #[clap(display_order = 600)]
    #[cfg(feature = "cli")]
    Encrypt {
        /// Don't ASCII-armor output.
        #[clap(long)]
        no_armor: bool,
        /// Select the profile to use for encryption.
        #[clap(long)]
        profile: Option<String>,
        /// Encrypt binary data or UTF-8 text.
        #[clap(default_value = "binary", long = "as")]
        as_: EncryptAs,
        /// Encrypt with passwords.
        #[clap(long, number_of_values = 1)]
        with_password: Vec<String>,
        /// Keys for signing.
        #[clap(long, number_of_values = 1)]
        sign_with: Vec<String>,
        /// Try to decrypt the signing KEYS with these passwords.
        #[clap(long, number_of_values = 1)]
        with_key_password: Vec<String>,
        /// Write the session key here.
        #[clap(long)]
        session_key_out: Option<String>,
        /// Encrypt for these certs.
        certs: Vec<String>,
    },
    /// Decrypts a Message.
    #[clap(display_order = 700)]
    #[cfg(feature = "cli")]
    Decrypt {
        /// Write the session key here.
        #[clap(long)]
        session_key_out: Option<String>,
        /// Try to decrypt with this session key.
        #[clap(long, number_of_values = 1)]
        with_session_key: Vec<String>,
        /// Try to decrypt with this password.
        #[clap(long, number_of_values = 1)]
        with_password: Vec<String>,
        /// Write verification result here.
        #[clap(long, alias("verify-out"))]
        verifications_out: Option<String>,
        /// Certs for verification.
        #[clap(long, number_of_values = 1)]
        verify_with: Vec<String>,
        /// Consider signatures before this date invalid.
        #[clap(long)]
        verify_not_before: Option<NotBefore>,
        /// Consider signatures after this date invalid.
        #[clap(long)]
        verify_not_after: Option<NotAfter>,
        /// Try to decrypt the encryption KEYS with these passwords.
        #[clap(long, number_of_values = 1)]
        with_key_password: Vec<String>,
        /// Try to decrypt with these keys.
        keys: Vec<String>,
    },
    /// Converts binary OpenPGP data to ASCII.
    #[clap(display_order = 800)]
    #[cfg(feature = "cli")]
    Armor {
        /// Indicates the kind of data.
        #[clap(long, default_value = "auto", hide(true))]
        label: ArmorLabel,
    },
    /// Converts ASCII OpenPGP data to binary.
    #[clap(display_order = 900)]
    #[cfg(feature = "cli")]
    Dearmor {
    },
    /// Splits Signatures from an Inline-Signed Message.
    #[clap(display_order = 750)]
    #[cfg(feature = "cli")]
    InlineDetach {
        /// Don't ASCII-armor the signatures.
        #[clap(long)]
        no_armor: bool,
        /// Write Signatures here.
        #[clap(long)]
        signatures_out: String,
    },
    /// Creates Inline-Signed Messages.
    #[clap(display_order = 752)]
    #[cfg(feature = "cli")]
    InlineSign {
        /// Don't ASCII-armor output.
        #[clap(long)]
        no_armor: bool,
        /// Sign binary data, UTF-8 text, or using the Cleartext
        /// Signature Framework.
        #[clap(default_value = "binary", long = "as")]
        as_: InlineSignAs,
        /// Try to decrypt the signing KEYS with these passwords.
        #[clap(long, number_of_values = 1)]
        with_key_password: Vec<String>,
        /// Keys for signing.
        keys: Vec<String>,
    },
    /// Unsupported subcommand.
    #[clap(external_subcommand)]
    Unsupported(Vec<String>),
}

/// Generates shell completions.
#[deprecated(note="Use write_shell_completions2.")]
pub fn write_shell_completions<B, P>(binary_name: B,
                                     out_path: P)
                                     -> io::Result<()>
where B: AsRef<str>,
      P: AsRef<Path>,
{
    let variant = if binary_name.as_ref().ends_with("v") {
        Variant::Verification
    } else {
        Variant::Full
    };

    write_shell_completions2(variant, binary_name, out_path)
}

/// Generates shell completions for the given variant.
pub fn write_shell_completions2<B, P>(variant: Variant,
                                      binary_name: B,
                                      out_path: P)
                                      -> io::Result<()>
where
    B: AsRef<str>,
    P: AsRef<Path>,
{
    use clap_complete::{generate_to, Shell};

    let binary_name = binary_name.as_ref();
    let out_path = out_path.as_ref();
    std::fs::create_dir_all(&out_path)?;

    const SHELLS: &[Shell] = &[
        Shell::Bash, Shell::Fish, Shell::Zsh, Shell::PowerShell,
        Shell::Elvish,
    ];
    match variant {
        Variant::Verification => {
            let mut clap = Cli::<VerificationSubset>::command();
            for shell in SHELLS {
                generate_to(*shell, &mut clap, binary_name, out_path)?;
            }
        },

        Variant::Full => {
            let mut clap = Cli::<Operation>::command();
            for shell in SHELLS {
                generate_to(*shell, &mut clap, binary_name, out_path)?;
            }
        },
    }

    println!("cargo:warning={}: shell completions written to {}",
             binary_name,
             out_path.display());
    Ok(())
}

/// Generates man pages.
pub fn write_man_pages<A, P, V>(variant: Variant,
                                version: &V,
                                author: A,
                                out_path: P)
                                -> Result<()>
where
    V: for <'a> crate::ops::Version<'a>,
    A: ToString,
    P: AsRef<Path>,
{
    let out_path = out_path.as_ref();
    std::fs::create_dir_all(&out_path)?;

    match variant {
        Variant::Verification => {
            let cmd = Cli::<VerificationSubset>::with_version(version, variant)?
                .author(Box::leak(author.to_string().into_boxed_str()) as &str);
            generate_to(cmd, LAST_UPDATE_TIMESTAMP, out_path)?;
        },

        Variant::Full => {
            let cmd = Cli::<Operation>::with_version(version, variant)?
                .author(Box::leak(author.to_string().into_boxed_str()) as &str);
            generate_to(cmd, LAST_UPDATE_TIMESTAMP, out_path)?;
        },
    }

    println!("cargo:warning={}: man pages written to {}",
             version.frontend()?.name,
             out_path.display());
    Ok(())
}

/// Like clap's version, but modifies the man page's source and date.
fn generate_to(
    cmd: clap::Command,
    date: &str,
    out_dir: impl AsRef<std::path::Path>,
) -> Result<(), std::io::Error> {
    fn generate(
        cmd: clap::Command,
        source: &str,
        date: &str,
        out_dir: &std::path::Path,
    ) -> Result<(), std::io::Error> {
        for cmd in cmd.get_subcommands().filter(|s| !s.is_hide_set()).cloned() {
            generate(cmd, source, date, out_dir)?;
        }
        clap_mangen::Man::new(cmd)
            .source(source) // Always use the top-level source.
            .date(date) // Set the last modification timestamp.
            .generate_to(out_dir)?;
        Ok(())
    }

    // Use the top-level source for all man pages.
    let source = format!(
        "{} {}",
        cmd.get_name(),
        cmd.get_version().unwrap_or_default()
    );

    let mut cmd = cmd.disable_help_subcommand(true);
    cmd.build();
    generate(cmd, &source, date, out_dir.as_ref())
}

/// Implements the SOP command-line interface.
pub fn main<'s, S, C, K, Sigs>(sop: &'s mut S, variant: Variant)
                               -> !
where
    S: SOP<'s, Certs = C, Keys = K, Sigs = Sigs>,
    C: Load<'s, S> + Save,
    K: Load<'s, S> + Save,
    Sigs: Load<'s, S> + Save,
{
    use std::process::exit;

    match real_main::<S, C, K, Sigs>(sop, variant) {
        Ok(()) => exit(0),
        Err(e) => {
            print_error_chain(&e);
            let e = match e.downcast::<crate::Error>() {
                Ok(e) => exit(Error::from(e).into()),
                Err(e) => e,
            };
            let e = match e.downcast::<Error>() {
                Ok(e) => exit(e.into()),
                Err(e) => e,
            };

            // XXX: Would be nice to at least inform developers that
            // we return a generic error here.
            let _ = e;
            exit(1);
        },
    }
}

fn real_main<'s, S, C, K, Sigs>(sop: &'s mut S, variant: Variant)
                                -> Result<()>
where
    S: SOP<'s, Certs = C, Keys = K, Sigs = Sigs>,
    C: Load<'s, S> + Save,
    K: Load<'s, S> + Save,
    Sigs: Load<'s, S> + Save,
{
    // If we are the full version, but are invoked as the verification
    // subset, we first parse the arguments using the verification
    // subset parser.
    #[cfg(feature = "cli")]
    if let Variant::Verification = variant {
        let app = Cli::<VerificationSubset>::with_version(
            sop.version()?.as_ref(), Variant::Verification)?;

        let matches = match app.try_get_matches() {
            Ok(v) => v,
            Err(e) => {
                use clap::error::ErrorKind;
                return match e.kind() {
                    ErrorKind::DisplayHelp => {
                        e.exit()
                    },
                    ErrorKind::UnknownArgument =>
                        Err(anyhow::Error::from(Error::UnsupportedOption)
                            .context(format!("{}", e))),
                    _ => Err(e.into()),
                };
            },
        };

        Cli::<VerificationSubset>::from_arg_matches(&matches)?;

        // If we get here, the syntax checked out.  We now just fall
        // through to the full parser, which accepts a superset of
        // what we just parsed.
    }

    let app = Cli::<Operation>::with_version(sop.version()?.as_ref(), variant)?;

    let matches = match app.clone().try_get_matches() {
        Ok(v) => v,
        Err(e) => {
            use clap::error::ErrorKind;
            return match e.kind() {
                ErrorKind::DisplayHelp => {
                    e.exit()
                },
                ErrorKind::UnknownArgument =>
                    Err(anyhow::Error::from(Error::UnsupportedOption)
                        .context(format!("{}", e))),
                _ => Err(e.into()),
            };
        },
    };

    let cli = Cli::from_arg_matches(&matches)?;
    sop.debug(cli.debug);

    match cli.operation {
        Operation::VerificationSubset(VerificationSubset::Version {
            backend, extended, sop_spec, sopv,
        }) => {
            let version = sop.version()?;
            match (backend, extended, sop_spec, sopv) {
                (false, false, false, false) => {
                    let v = version.frontend()?;
                    println!("{} {}", v.name, v.version);
                },
                (true, false, false, false) => {
                    let v = version.backend()?;
                    println!("{} {}", v.name, v.version);
                },
                (false, true, false, false) => {
                    let v = version.frontend()?;
                    println!("{} {}", v.name, v.version);
                    println!("sop-rs {}", env!("CARGO_PKG_VERSION"));
                    println!("{}", version.extended()?);
                },
                (false, false, true, false) => {
                    println!("{}", sop.spec_version());
                },
                (false, false, false, true) => {
                    println!("{}", sop.sopv_version()?);
                },
                _ => unreachable!("flags are mutually exclusive"),
            }
        },

        #[cfg(feature = "cli")]
        Operation::ListProfiles { subcommand, } => {
            let profiles = match subcommand.as_str() {
                "generate-key" => sop.generate_key()?.list_profiles(),
                "encrypt" => sop.encrypt()?.list_profiles(),
                _ => return Err(Error::UnsupportedProfile.into()),
            };
            for (p, d) in profiles {
                println!("{}: {}", p, d);
            }
        },

        #[cfg(feature = "cli")]
        Operation::GenerateKey {
            no_armor,
            profile,
            signing_only,
            with_key_password,
            userids,
        } => {
            let mut op = sop.generate_key()?;
            if let Some(p) = profile {
                op = op.profile(&p)?;
            }
            if signing_only {
                op = op.signing_only();
            }
            if let Some(p) = with_key_password {
                op = op.with_key_password(get_password(p)?)?;
            }
            for u in userids {
                op = op.userid(&u);
            }
            op.generate()?
                .to_stdout(! no_armor)?;
        },

        #[cfg(feature = "cli")]
        Operation::ChangeKeyPassword {
            no_armor,
            new_key_password,
            old_key_password,
        } => {
            let mut op = sop.change_key_password()?;
            if let Some(p) = new_key_password {
                op = op.new_key_password(get_password(p)?)?;
            }
            for p in old_key_password {
                op = op.old_key_password(get_password(p)?)?;
            }
            op.keys(&K::from_stdin(sop)?)?
                .to_stdout(! no_armor)?;
        }

        #[cfg(feature = "cli")]
        Operation::RevokeKey { no_armor, with_key_password, } => {
            let mut op = sop.revoke_key()?;
            for p in with_key_password {
                op = op.with_key_password(get_password(p)?)?;
            }
            op.keys(&K::from_stdin(sop)?)?
                .to_stdout(! no_armor)?;
        }

        #[cfg(feature = "cli")]
        Operation::ExtractCert { no_armor, } => {
            sop.extract_cert()?
                .keys(&K::from_stdin(sop)?)?
                .to_stdout(! no_armor)?;
        },

        #[cfg(feature = "cli")]
        Operation::UpdateKey {
            no_armor, signing_only, no_added_capabilities,
            with_key_password, merge_certs,
        } => {
            let mut op = sop.update_key()?;
            if signing_only {
                op = op.signing_only();
            }
            if no_added_capabilities {
                op = op.no_added_capabilities();
            }
            for p in with_key_password {
                op = op.with_key_password(get_password(p)?)?;
            }
            for (name, mut stream) in load_files(merge_certs)? {
                op = op.merge_updates(&C::from_reader(sop, &mut stream, Some(name))?)?;
            }
            let keys = op.update(&K::from_stdin(sop)?)?;
            keys.to_stdout(! no_armor)?;
        },

        #[cfg(feature = "cli")]
        Operation::MergeCerts { no_armor, certs, } => {
            let mut op = sop.merge_certs()?;
            for (name, mut stream) in load_files(certs)? {
                op = op.merge_updates(&C::from_reader(sop, &mut stream, Some(name))?)?;
            }
            let certs = op.merge(&C::from_stdin(sop)?)?;
            certs.to_stdout(! no_armor)?;
        },

        #[cfg(feature = "cli")]
        Operation::CertifyUserid {
            no_armor, userid, with_key_password, no_require_self_sig, keys,
        } => {
            let mut op = sop.certify_userid()?;
            if no_require_self_sig {
                op = op.no_require_self_sig();
            }
            for u in userid {
                op = op.userid(u);
            }
            for p in with_key_password {
                op = op.with_key_password(get_password(p)?)?;
            }
            for (name, mut stream) in load_files(keys)? {
                op = op.keys(&K::from_reader(sop, &mut stream, Some(name))?)?;
            }
            let certs = op.certify(&C::from_stdin(sop)?)?;
            certs.to_stdout(! no_armor)?;
        },

        #[cfg(feature = "cli")]
        Operation::ValidateUserid {
            addr_spec_only, validate_at, userid, certs,
        } => {
            let mut op = sop.validate_userid()?;
            if let Some(t) = validate_at {
                op = op.validate_at(t.into())?;
            }
            for (name, mut stream) in load_files(certs)? {
                op = op.trust_roots(&C::from_reader(sop, &mut stream, Some(name))?)?;
            }

            op = op.target_certs(&C::from_stdin(sop)?)?;

            if addr_spec_only {
                op.email(&userid)?;
            } else {
                op.userid(&userid)?;
            }
        },

        #[cfg(feature = "cli")]
        Operation::Sign {
            no_armor,
            as_,
            micalg_out,
            with_key_password,
            keys,
        } => {
            let mut op = sop.sign()?.mode(as_);
            for p in with_key_password {
                op = op.with_key_password(get_password_unchecked(p)?)?;
            }
            for (name, mut stream) in load_files(keys)? {
                op = op.keys(&K::from_reader(sop, &mut stream, Some(name))?)?;
            }
            let (micalg, sigs) = op.data(&mut io::stdin())?;
            if let Some(path) = micalg_out {
                let mut sink = create_file(path)?;
                write!(sink, "{}", micalg)?;
            }
            sigs.to_stdout(! no_armor)?;
        },

        #[cfg(any(feature = "cli", feature = "cliv"))]
        Operation::VerificationSubset(VerificationSubset::Verify {
            not_before, not_after, signatures, certs,
        }) => {
            let mut op = sop.verify()?;
            if let Some(t) = not_before {
                op = op.not_before(t.into());
            }
            if let Some(t) = not_after {
                op = op.not_after(t.into());
            }
            for (name, mut stream) in load_files(certs)? {
                op = op.certs(&C::from_reader(sop, &mut stream, Some(name))?)?;
            }
            let (name, mut stream) = load_file(signatures)?;
            let verifications =
                op.signatures(&Sigs::from_reader(sop, &mut stream, Some(name))?)?
                .data(&mut io::stdin())?;

            for v in verifications {
                println!("{}", v);
            }
        },

        #[cfg(feature = "cli")]
        Operation::Encrypt {
            no_armor,
            profile,
            as_,
            with_password,
            with_key_password,
            sign_with,
            session_key_out,
            certs,
        } =>
        {
            let session_key_out: Option<Box<dyn io::Write>> =
                if let Some(f) = session_key_out {
                    Some(Box::new(create_file(f)?))
                } else {
                    None
                };

            let mut op = sop.encrypt()?.mode(as_);
            if no_armor {
                op = op.no_armor();
            }
            if let Some(p) = profile {
                op = op.profile(&p)?;
            }
            for p in with_key_password {
                op = op.with_key_password(get_password_unchecked(p)?)?;
            }
            for (name, mut stream) in load_files(sign_with)? {
                op = op.sign_with_keys(&K::from_reader(sop, &mut stream, Some(name))?)?;
            }
            for pw in with_password.into_iter().map(get_password) {
                op = op.with_password(pw?)?;
            }
            for (name, mut stream) in load_files(certs)? {
                op = op.with_certs(&C::from_reader(sop, &mut stream, Some(name))?)?;
            }
            let session_key =
                op.plaintext(&mut io::stdin())?.to_writer(&mut io::stdout())?;

            if let Some(mut sko) = session_key_out {
                if let Some(sk) = session_key {
                    writeln!(sko, "{}", sk)?;
                } else {
                    return Err(Error::UnsupportedSubcommand.into());
                }
            }
        },

        #[cfg(feature = "cli")]
        Operation::Decrypt {
            session_key_out,
            with_session_key,
            with_password,
            verifications_out,
            verify_with,
            verify_not_before,
            verify_not_after,
            with_key_password,
            keys,
        } => {
            let session_key_out: Option<Box<dyn io::Write>> =
                if let Some(f) = session_key_out {
                    Some(Box::new(create_file(f)?))
                } else {
                    None
                };

            if verifications_out.is_none() != verify_with.is_empty() {
                return Err(anyhow::Error::from(Error::IncompleteVerification))
                    .context("--verifications-out and --verify-with \
                              must both be given");
            }

            let mut verify_out: Box<dyn io::Write> =
                if let Some(f) = verifications_out {
                    Box::new(create_file(f)?)
                } else {
                    Box::new(io::sink())
                };

            let mut op = sop.decrypt()?;

            for (_name, mut stream) in load_files(with_session_key)? {
                let mut sk = String::new();
                stream.read_to_string(&mut sk)?;
                op = op.with_session_key(sk.parse()?)?;
            }

            for pw in with_password.into_iter().map(get_password_unchecked) {
                op = op.with_password(pw?)?;
            }

            for p in with_key_password {
                op = op.with_key_password(get_password_unchecked(p)?)?;
            }

            for (name, mut stream) in load_files(keys)? {
                op = op.with_keys(&K::from_reader(sop, &mut stream, Some(name))?)?;
            }

            for (name, mut stream) in load_files(verify_with)? {
                op = op.verify_with_certs(&C::from_reader(sop, &mut stream, Some(name))?)?;
            }

            if let Some(t) = verify_not_before {
                op = op.verify_not_before(t.into());
            }

            if let Some(t) = verify_not_after {
                op = op.verify_not_after(t.into());
            }

            let (session_key, verifications) =
                op.ciphertext(&mut io::stdin())?.to_writer(&mut io::stdout())?;

            for v in verifications {
                writeln!(verify_out, "{}", v)?;
            }
            if let Some(mut sko) = session_key_out {
                if let Some(sk) = session_key {
                    writeln!(sko, "{}", sk)?;
                } else {
                    return Err(Error::UnsupportedSubcommand.into());
                }
            }
        },

        #[cfg(feature = "cli")]
        Operation::Armor { label, } => {
            #[allow(deprecated)]
            let op = sop.armor()?.label(label);
            op.data(&mut io::stdin())?
                .to_writer(&mut io::stdout())?;
        },

        #[cfg(feature = "cli")]
        Operation::Dearmor {} => {
            let op = sop.dearmor()?;
            op.data(&mut io::stdin())?
                .to_writer(&mut io::stdout())?;
        },

        #[cfg(feature = "cli")]
        Operation::InlineDetach { no_armor, signatures_out, } => {
            let op = sop.inline_detach()?;
            let mut signatures_out = create_file(signatures_out)?;
            let signatures =
                op.message(&mut io::stdin())?.to_writer(&mut io::stdout())?;
            signatures.to_writer(! no_armor, &mut signatures_out)?;
        },

        #[cfg(any(feature = "cli", feature = "cliv"))]
        Operation::VerificationSubset(VerificationSubset::InlineVerify {
            not_before,
            not_after,
            verifications_out,
            certs,
        }) => {
            let mut op = sop.inline_verify()?;

            if let Some(t) = not_before {
                op = op.not_before(t.into());
            }
            if let Some(t) = not_after {
                op = op.not_after(t.into());
            }
            let mut verifications_out: Box<dyn io::Write> =
                if let Some(f) = verifications_out {
                    Box::new(create_file(f)?)
                } else {
                    Box::new(io::sink())
                };
            for (name, mut stream) in load_files(certs)? {
                op = op.certs(&C::from_reader(sop, &mut stream, Some(name))?)?;
            }
            let verifications =
                op.message(&mut io::stdin())?.to_writer(&mut io::stdout())?;

            for v in verifications {
                writeln!(&mut verifications_out, "{}", v)?;
            }
        },

        #[cfg(feature = "cli")]
        Operation::InlineSign { no_armor, as_, with_key_password, keys, } => {
            let mut op = sop.inline_sign()?.mode(as_);
            if no_armor {
                op = op.no_armor();
            }
            for p in with_key_password {
                op = op.with_key_password(get_password_unchecked(p)?)?;
            }
            for (name, mut stream) in load_files(keys)? {
                op = op.keys(&K::from_reader(sop, &mut stream, Some(name))?)?;
            }
            op.data(&mut io::stdin())?.to_writer(&mut io::stdout())?;
        },

        Operation::Unsupported(args) => {
            return Err(anyhow::Error::from(Error::UnsupportedSubcommand))
                .context(format!("Subcommand {} is not supported", args[0]));
        },
    }
    Ok(())
}

fn is_special_designator<S: AsRef<str>>(file: S) -> bool {
    file.as_ref().starts_with("@")
}


/// Checks whether the given descriptor is valid.
#[cfg(unix)]
fn check_fd(fd: std::os::fd::RawFd) -> Result<()> {
    unsafe {
        // Try to dup(2) it.
        let dup = libc::dup(fd);

        if dup > 0 {
            libc::close(dup);
            Ok(())
        } else {
            Err(std::io::Error::last_os_error().into())
        }
    }
}

/// Loads the given (special) file.
fn load_file<S: AsRef<str>>(file: S)
                            -> Result<(String, Box<dyn io::Read + Send + Sync>)> {
    let f = file.as_ref();
    let file_name = f.into();

    if is_special_designator(f) {
        if Path::new(f).exists() {
            return Err(anyhow::Error::from(Error::AmbiguousInput))
                .context(format!("File {:?} exists", f));
        }

        #[cfg(unix)]
        {
            if f.starts_with("@FD:")
                && f[4..].chars().all(|c| c.is_ascii_digit())
            {
                use std::os::unix::io::{RawFd, FromRawFd};

                let fd: RawFd = f[4..].parse()
                    .map_err(|_| Error::UnsupportedSpecialPrefix)?;
                check_fd(fd)?;
                let f = unsafe {
                    std::fs::File::from_raw_fd(fd)
                };
                return Ok((file_name, Box::new(f)));
            }

            if f.starts_with("@ENV:") {
                use std::os::unix::ffi::OsStringExt;

                let key = &f[5..];
                let value = std::env::var_os(key)
                    .ok_or(Error::UnsupportedSpecialPrefix)?;
                // Prevent leak to child processes.
                std::env::remove_var(key);
                return Ok((file_name,
                           Box::new(io::Cursor::new(value.into_vec()))));
            }
        }

        #[cfg(windows)]
        {
            if f.starts_with("@ENV:") {
                let key = &f[5..];
                let value = std::env::var(key)
                    .map_err(|_| Error::UnsupportedSpecialPrefix)?;
                // Prevent leak to child processes.
                std::env::remove_var(key);
                return Ok((file_name,
                           Box::new(io::Cursor::new(value.into_bytes()))));
            }
        }

        return Err(anyhow::Error::from(Error::UnsupportedSpecialPrefix));
    }

    std::fs::File::open(f)
        .map(|f| -> (String, Box<dyn io::Read + Send + Sync>) {
            (file_name, Box::new(f))
        })
        .map_err(|_| Error::MissingInput)
        .context(format!("Failed to open file {:?}", f))
}

/// Gets the password from the given location.
///
/// Use this for passwords given to create artifacts.
///
/// Passwords are indirect data types, meaning that they are
/// loaded from files or special designators.
#[cfg(feature = "cli")]
fn get_password<S: AsRef<str>>(location: S) -> Result<Password> {
    let mut stream = load_file(location)?.1;
    let mut pw = Vec::new();
    stream.read_to_end(&mut pw)?;
    Ok(Password::new(pw)?)
}

/// Gets the password from the given location.
///
/// Use this for passwords given to consume artifacts.
///
/// Passwords are indirect data types, meaning that they are
/// loaded from files or special designators.
#[cfg(feature = "cli")]
fn get_password_unchecked<S: AsRef<str>>(location: S) -> Result<Password> {
    let mut stream = load_file(location)?.1;
    let mut pw = Vec::new();
    stream.read_to_end(&mut pw)?;
    Ok(Password::new_unchecked(pw))
}

/// Creates the given (special) file.
fn create_file<S: AsRef<str>>(file: S) -> Result<std::fs::File> {
    let f = file.as_ref();

    if is_special_designator(f) {
        if Path::new(f).exists() {
            return Err(anyhow::Error::from(Error::AmbiguousInput))
                .context(format!("File {:?} exists", f));
        }

        #[cfg(unix)]
        {
            if f.starts_with("@FD:")
                && f[4..].chars().all(|c| c.is_ascii_digit())
            {
                use std::os::unix::io::{RawFd, FromRawFd};

                let fd: RawFd = f[4..].parse()
                    .map_err(|_| Error::UnsupportedSpecialPrefix)?;
                check_fd(fd)?;
                let f = unsafe {
                    std::fs::File::from_raw_fd(fd)
                };
                return Ok(f);
            }
        }

        return Err(anyhow::Error::from(Error::UnsupportedSpecialPrefix));
    }

    if Path::new(f).exists() {
        return Err(anyhow::Error::from(Error::OutputExists))
            .context(format!("File {:?} exists", f));
    }

    std::fs::File::create(f).map_err(|_| Error::MissingInput) // XXX
            .context(format!("Failed to create file {:?}", f))
}

/// Loads the the (special) files.
fn load_files(files: Vec<String>)
              -> Result<Vec<(String, Box<dyn io::Read + Send + Sync>)>> {
    files.iter().map(load_file).collect()
}

/// Parses the given string depicting a ISO 8601 timestamp, rounding down.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct NotBefore(DateTime<Utc>);

impl std::str::FromStr for NotBefore {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<NotBefore> {
        match s {
            // XXX: parse "-" to None once we figure out how to do that
            // with clap.
            "now" => Ok(Utc::now()),
            _ => parse_iso8601(s, NaiveTime::from_hms_opt(0, 0, 0).unwrap()),
        }.map(|t| NotBefore(t))
    }
}

impl From<NotBefore> for std::time::SystemTime {
    fn from(t: NotBefore) -> std::time::SystemTime {
        t.0.into()
    }
}

/// Parses the given string depicting a ISO 8601 timestamp, rounding up.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct NotAfter(DateTime<Utc>);

impl std::str::FromStr for NotAfter {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<NotAfter> {
        match s {
            // XXX: parse "-" to None once we figure out how to do that
            // with clap.
            "now" => Ok(Utc::now()),
            _ => parse_iso8601(s, NaiveTime::from_hms_opt(23, 59, 59).unwrap()),
        }.map(|t| NotAfter(t))
    }
}

impl From<NotAfter> for std::time::SystemTime {
    fn from(t: NotAfter) -> std::time::SystemTime {
        t.0.into()
    }
}

/// Parses the given string depicting a ISO 8601 timestamp.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Timestamp(DateTime<Utc>);

impl std::str::FromStr for Timestamp {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Timestamp> {
        match s {
            // XXX: parse "-" to None once we figure out how to do that
            // with clap.
            "now" => Ok(Utc::now()),
            _ => parse_iso8601(s, NaiveTime::from_hms_opt(0, 0, 0).unwrap()),
        }.map(|t| Timestamp(t))
    }
}

impl From<Timestamp> for std::time::SystemTime {
    fn from(t: Timestamp) -> std::time::SystemTime {
        t.0.into()
    }
}

/// Parses the given string depicting a ISO 8601 timestamp.
fn parse_iso8601(s: &str, pad_date_with: chrono::NaiveTime)
                 -> Result<DateTime<Utc>>
{
    // If you modify this function this function, synchronize the
    // changes with the copy in sqv.rs!
    for f in &[
        "%Y-%m-%dT%H:%M:%S%#z",
        "%Y-%m-%dT%H:%M:%S",
        "%Y-%m-%dT%H:%M%#z",
        "%Y-%m-%dT%H:%M",
        "%Y-%m-%dT%H%#z",
        "%Y-%m-%dT%H",
        "%Y%m%dT%H%M%S%#z",
        "%Y%m%dT%H%M%S",
        "%Y%m%dT%H%M%#z",
        "%Y%m%dT%H%M",
        "%Y%m%dT%H%#z",
        "%Y%m%dT%H",
    ] {
        if f.ends_with("%#z") {
            if let Ok(d) = DateTime::parse_from_str(s, *f) {
                return Ok(d.into());
            }
        } else {
            if let Ok(d) = chrono::NaiveDateTime::parse_from_str(s, *f) {
                return Ok(DateTime::from_utc(d, Utc));
            }
        }
    }
    for f in &[
        "%Y-%m-%d",
        "%Y-%m",
        "%Y-%j",
        "%Y%m%d",
        "%Y%m",
        "%Y%j",
        "%Y",
    ] {
        if let Ok(d) = chrono::NaiveDate::parse_from_str(s, *f) {
            return Ok(DateTime::from_utc(d.and_time(pad_date_with), Utc));
        }
    }
    Err(anyhow::anyhow!("Malformed ISO8601 timestamp: {}", s))
}

#[test]
fn test_parse_iso8601() {
    let z = chrono::NaiveTime::from_hms_opt(0, 0, 0).unwrap();
    parse_iso8601("2017-03-04T13:25:35Z", z).unwrap();
    parse_iso8601("2017-03-04T13:25:35+08:30", z).unwrap();
    parse_iso8601("2017-03-04T13:25:35", z).unwrap();
    parse_iso8601("2017-03-04T13:25Z", z).unwrap();
    parse_iso8601("2017-03-04T13:25", z).unwrap();
    // parse_iso8601("2017-03-04T13Z", z).unwrap(); // XXX: chrono doesn't like
    // parse_iso8601("2017-03-04T13", z).unwrap(); // ditto
    parse_iso8601("2017-03-04", z).unwrap();
    // parse_iso8601("2017-03", z).unwrap(); // ditto
    parse_iso8601("2017-031", z).unwrap();
    parse_iso8601("20170304T132535Z", z).unwrap();
    parse_iso8601("20170304T132535+0830", z).unwrap();
    parse_iso8601("20170304T132535", z).unwrap();
    parse_iso8601("20170304T1325Z", z).unwrap();
    parse_iso8601("20170304T1325", z).unwrap();
    // parse_iso8601("20170304T13Z", z).unwrap(); // ditto
    // parse_iso8601("20170304T13", z).unwrap(); // ditto
    parse_iso8601("20170304", z).unwrap();
    // parse_iso8601("201703", z).unwrap(); // ditto
    parse_iso8601("2017031", z).unwrap();
    // parse_iso8601("2017", z).unwrap(); // ditto
}

/// Errors defined by the Stateless OpenPGP Command-Line Protocol.
#[derive(thiserror::Error, Debug)]
enum Error {
    /// Unspecified failure.
    #[error("Unspecified failure")]
    UnspecifiedFailure,

    /// No acceptable signatures found ("sop verify").
    #[error("No acceptable signatures found")]
    NoSignature,

    /// Asymmetric algorithm unsupported ("sop encrypt").
    #[error("Asymmetric algorithm unsupported")]
    UnsupportedAsymmetricAlgo,

    /// Certificate not encryption-capable (e.g., expired, revoked,
    /// unacceptable usage flags) ("sop encrypt").
    #[error("Certificate not encryption-capable")]
    CertCannotEncrypt,

    /// Key not signature-capable (e.g., expired, revoked,
    /// unacceptable usage flags) (`sop sign` and `sop encrypt` with
    /// `--sign-with`).
    #[error("Key not signing-capable")]
    KeyCannotSign,

    /// Missing required argument.
    #[error("Missing required argument")]
    MissingArg,

    /// Incomplete verification instructions ("sop decrypt").
    #[error("Incomplete verification instructions")]
    IncompleteVerification,

    /// Unable to decrypt ("sop decrypt").
    #[error("Unable to decrypt")]
    CannotDecrypt,

    /// Non-"UTF-8" or otherwise unreliable password ("sop encrypt").
    #[error("Non-UTF-8 or otherwise unreliable password")]
    PasswordNotHumanReadable,

    /// Unsupported option.
    #[error("Unsupported option")]
    UnsupportedOption,

    /// Invalid data type (no secret key where "KEY" expected, etc).
    #[error("Invalid data type")]
    BadData,

    /// Non-text input where text expected.
    #[error("Non-text input where text expected")]
    ExpectedText,

    /// Output file already exists.
    #[error("Output file already exists")]
    OutputExists,

    /// Input file does not exist.
    #[error("Input file does not exist")]
    MissingInput,

    /// A "KEY" input is protected (locked) with a password, and "sop" cannot
    /// unlock it.
    #[error("A KEY input is protected with a password")]
    KeyIsProtected,

    /// Unsupported subcommand.
    #[error("Unsupported subcommand")]
    UnsupportedSubcommand,

    /// An indirect parameter is a special designator (it starts with "@") but
    /// "sop" does not know how to handle the prefix.
    #[error("An indirect parameter is a special designator with unknown prefix")]
    UnsupportedSpecialPrefix,

    /// A indirect input parameter is a special designator (it starts with
    /// "@"), and a filename matching the designator is actually present.
    #[error("A indirect input parameter is a special designator matches file")]
    AmbiguousInput,

    /// Options were supplied that are incompatible with each other.
    #[error("Options were supplied that are incompatible with each other")]
    IncompatibleOptions,

    /// The requested profile is unsupported (sop generate-key, sop
    /// encrypt), or the indicated subcommand does not accept profiles
    /// (sop list-profiles).
    #[error("Profile not supported")]
    UnsupportedProfile,

    /// The primary key of a KEYS object is too weak or revoked.
    #[error("The primary key of a KEYS object is too weak or revoked")]
    PrimaryKeyBad,

    /// The CERTS object has no matching User ID.
    #[error("The CERTS object has no matching User ID")]
    CertUseridNoMatch,

    /// An I/O operation failed.
    #[error(transparent)]
    IoError(#[from] io::Error),
}

impl From<crate::Error> for Error {
    fn from(e: crate::Error) -> Self {
        use crate::Error as E;
        use Error as CE;
        match e {
            E::UnspecifiedFailure => CE::UnspecifiedFailure,
            E::NoSignature => CE::NoSignature,
            E::UnsupportedAsymmetricAlgo => CE::UnsupportedAsymmetricAlgo,
            E::CertCannotEncrypt => CE::CertCannotEncrypt,
            E::KeyCannotSign => CE::KeyCannotSign,
            E::MissingArg => CE::MissingArg,
            E::IncompleteVerification => CE::IncompleteVerification,
            E::CannotDecrypt => CE::CannotDecrypt,
            E::PasswordNotHumanReadable => CE::PasswordNotHumanReadable,
            E::UnsupportedOption => CE::UnsupportedOption,
            E::BadData => CE::BadData,
            E::ExpectedText => CE::ExpectedText,
            E::OutputExists => CE::OutputExists,
            E::MissingInput => CE::MissingInput,
            E::KeyIsProtected => CE::KeyIsProtected,
            E::AmbiguousInput => CE::AmbiguousInput,
            E::IncompatibleOptions => CE::IncompatibleOptions,
            E::NotImplemented => CE::UnsupportedSubcommand,
            E::UnsupportedProfile => CE::UnsupportedProfile,
            E::PrimaryKeyBad => CE::PrimaryKeyBad,
            E::CertUseridNoMatch => CE::CertUseridNoMatch,
            E::IoError(e) => CE::IoError(e),
        }
    }
}

impl From<Error> for i32 {
    fn from(e: Error) -> Self {
        use Error::*;
        match e {
            UnspecifiedFailure => 1,
            NoSignature => 3,
            UnsupportedAsymmetricAlgo => 13,
            CertCannotEncrypt => 17,
            MissingArg => 19,
            IncompleteVerification => 23,
            CannotDecrypt => 29,
            PasswordNotHumanReadable => 31,
            UnsupportedOption => 37,
            BadData => 41,
            ExpectedText => 53,
            OutputExists => 59,
            MissingInput => 61,
            KeyIsProtected => 67,
            UnsupportedSubcommand => 69,
            UnsupportedSpecialPrefix => 71,
            AmbiguousInput => 73,
            KeyCannotSign => 79,
            IncompatibleOptions => 83,
            UnsupportedProfile => 89,
            PrimaryKeyBad => 103,
            CertUseridNoMatch => 107,
            IoError(_) => 1,
        }
    }
}

/// Prints the error and causes, if any.
fn print_error_chain(err: &anyhow::Error) {
    eprintln!("           {}", err);
    err.chain().skip(1).for_each(|cause| eprintln!("  because: {}", cause));
}