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
//! ASCII Armor.
//!
//! This module deals with ASCII Armored data (see [RFC 4880, section 6]).
//!
//! [RFC 4880, section 6]: https://tools.ietf.org/html/rfc4880#section-6
//!
//! # Scope
//!
//! This implements a subset of the ASCII Armor specification.  Not
//! supported multipart messages.
//!
//! # Memory allocations
//!
//! Both the reader and the writer allocate memory in the order of the
//! size of chunks read or written.
//!
//! # Example
//!
//! ```rust, no_run
//! extern crate sequoia_openpgp as openpgp;
//! use std::fs::File;
//! use openpgp::armor::{Reader, Kind};
//!
//! let mut file = File::open("somefile.asc").unwrap();
//! let mut r = Reader::new(&mut file, Some(Kind::File));
//! ```

extern crate base64;
use buffered_reader::{
    BufferedReader, BufferedReaderGeneric, BufferedReaderMemory,
    BufferedReaderFile,
};
use std::io::{Cursor, Read, Write};
use std::io::{Result, Error, ErrorKind};
use std::path::Path;
use std::cmp::min;
use std::str;
use quickcheck::{Arbitrary, Gen};

use packet::Header;

/// The encoded output stream must be represented in lines of no more
/// than 76 characters each (see (see [RFC 4880, section
/// 6.3](https://tools.ietf.org/html/rfc4880#section-6.3).  GnuPG uses
/// 64.
const LINE_LENGTH: usize = 64;

const LINE_ENDING: &str = "\n";

/// Specifies the type of data (see [RFC 4880, section 6.2]).
///
/// [RFC 4880, section 6.2]: https://tools.ietf.org/html/rfc4880#section-6.2
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Kind {
    /// A generic OpenPGP message.  (Since its structure hasn't been
    /// validated, in this crate's terminology, this is just a
    /// `PacketPile`.)
    Message,
    /// A transferable public key.
    PublicKey,
    /// A transferable secret key.
    SecretKey,
    /// A detached signature.
    Signature,
    /// A generic file.  This is a GnuPG extension.
    File,
}

impl Arbitrary for Kind {
    fn arbitrary<G: Gen>(g: &mut G) -> Self {
        use self::Kind::*;
        match u8::arbitrary(g) % 5 {
            0 => Message,
            1 => PublicKey,
            2 => SecretKey,
            3 => Signature,
            4 => File,
            _ => unreachable!(),
        }
    }
}

impl Kind {
    /// Autodetects the kind of data.
    fn detect(blurb: &[u8]) -> Option<Self> {
        if blurb.len() < "-----BEGIN PGP MESSAGE-----".len()
            || ! blurb.starts_with(b"-----BEGIN PGP ")
        {
            return None;
        }

        let kind = &blurb[15..];
        if kind.starts_with(b"MESSAGE-----") {
            Some(Kind::Message)
        } else if kind.starts_with(b"PUBLIC KEY BLOCK-----") {
            Some(Kind::PublicKey)
        } else if kind.starts_with(b"PRIVATE KEY BLOCK-----") {
            Some(Kind::SecretKey)
        } else if kind.starts_with(b"SIGNATURE-----") {
            Some(Kind::Signature)
        } else if kind.starts_with(b"ARMORED FILE-----") {
            Some(Kind::File)
        } else {
            None
        }
    }

    fn blurb(&self) -> &str {
        match self {
            &Kind::Message => "MESSAGE",
            &Kind::PublicKey => "PUBLIC KEY BLOCK",
            &Kind::SecretKey => "PRIVATE KEY BLOCK",
            &Kind::Signature => "SIGNATURE",
            &Kind::File => "ARMORED FILE",
        }
    }

    fn begin(&self) -> String {
        format!("-----BEGIN PGP {}-----", self.blurb())
    }

    fn end(&self) -> String {
        format!("-----END PGP {}-----", self.blurb())
    }

    /// Returns the maximal size of the footer with CRC.
    fn footer_max_len(&self) -> usize {
        (5    // CRC
         + 4  // CR NL CR NL
         + 18 // "-----END PGP -----"
         + self.blurb().len()
         + 2  // CR NL
        )
    }
}

/// A filter that applies ASCII Armor to the data written to it.
pub struct Writer<W: Write> {
    sink: W,
    kind: Kind,
    stash: Vec<u8>,
    column: usize,
    crc: CRC,
    epilogue: Vec<u8>,
    dirty: bool,
    finalized: bool,
}

impl<W: Write> Writer<W> {
    /// Constructs a new filter for the given type of data.
    ///
    /// # Example
    ///
    /// ```
    /// # use std::io::Write;
    /// # extern crate sequoia_openpgp as openpgp;
    /// # use openpgp::armor::{Writer, Kind};
    /// # use std::io::{self, Result};
    /// # fn main() { f().unwrap(); }
    /// # fn f() -> Result<()> {
    /// let mut buffer = io::Cursor::new(vec![]);
    /// {
    ///     let mut writer = Writer::new(&mut buffer, Kind::File,
    ///         &[ ("Key", "Value") ][..])?;
    ///     writer.write_all(b"Hello world!")?;
    ///     // writer is drop()ed here.
    /// }
    /// assert_eq!(
    ///     String::from_utf8_lossy(buffer.get_ref()),
    ///     "-----BEGIN PGP ARMORED FILE-----
    /// Key: Value
    ///
    /// SGVsbG8gd29ybGQh
    /// =s4Gu
    /// -----END PGP ARMORED FILE-----
    /// ");
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(inner: W, kind: Kind, headers: &[(&str, &str)]) -> Result<Self> {
        let mut w = Writer {
            sink: inner,
            kind: kind,
            stash: Vec::<u8>::with_capacity(2),
            column: 0,
            crc: CRC::new(),
            epilogue: Vec::with_capacity(128),
            dirty: false,
            finalized: false,
        };

        {
            let mut cur = Cursor::new(&mut w.epilogue);
            write!(&mut cur, "{}{}", kind.begin(), LINE_ENDING)?;

            for h in headers {
                write!(&mut cur, "{}: {}{}", h.0, h.1, LINE_ENDING)?;
            }

            // A blank line separates the headers from the body.
            write!(&mut cur, "{}", LINE_ENDING)?;
        }

        Ok(w)
    }

    fn write_epilogue(&mut self) -> Result<()> {
        if ! self.dirty {
            self.dirty = true;
            self.sink.write_all(&self.epilogue)?;
            // Release memory.
            self.epilogue.clear();
            self.epilogue.shrink_to_fit();
        }
        Ok(())
    }

    /// Writes the footer.
    ///
    /// No more data can be written after this call.  If this is not
    /// called explicitly, the header is written once the writer is
    /// dropped.
    pub fn finalize(&mut self) -> Result<()> {
        if self.finalized {
            return Err(Error::new(ErrorKind::BrokenPipe, "Writer is finalized."));
        }

        if ! self.dirty {
            // No data was written to us, don't emit anything.
            return Ok(());
        }
        self.write_epilogue()?;

        // Write any stashed bytes and pad.
        if self.stash.len() > 0 {
            self.sink.write_all(base64::encode_config(&self.stash,
                                                      base64::STANDARD).as_bytes())?;
            self.column += 4;
        }
        self.linebreak()?;
        if self.column > 0 {
            write!(self.sink, "{}", LINE_ENDING)?;
        }

        let crc = self.crc.finalize();
        let bytes: [u8; 3] = [
            (crc >> 16) as u8,
            (crc >>  8) as u8,
            (crc >>  0) as u8,
        ];

        // CRC and footer.
        write!(self.sink, "={}{}{}{}",
               base64::encode_config(&bytes, base64::STANDARD_NO_PAD),
               LINE_ENDING, self.kind.end(), LINE_ENDING)?;

        self.finalized = true;
        Ok(())
    }

    /// Inserts a line break if necessary.
    fn linebreak(&mut self) -> Result<()> {
        assert!(self.column <= LINE_LENGTH);
        if self.column == LINE_LENGTH {
            write!(self.sink, "{}", LINE_ENDING)?;
            self.column = 0;
        }
        Ok(())
    }
}

impl<W: Write> Write for Writer<W> {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        if self.finalized {
            return Err(Error::new(ErrorKind::BrokenPipe, "Writer is finalized."));
        }

        self.write_epilogue()?;

        // Update CRC on the unencoded data.
        self.crc.update(buf);

        let mut input = buf;
        let mut written = 0;

        // First of all, if there are stashed bytes, fill the stash
        // and encode it.  If writing out the stash fails below, we
        // might end up with a stash of size 3.
        assert!(self.stash.len() <= 3);
        if self.stash.len() > 0 {
            while self.stash.len() < 3 {
                if input.len() == 0 {
                    /* We exhausted the input.  Return now, any
                     * stashed bytes are encoded when finalizing the
                     * writer.  */
                    return Ok(written);
                }
                self.stash.push(input[0]);
                input = &input[1..];
                written += 1;
            }
            assert_eq!(self.stash.len(), 3);

            // If this fails for some reason, and the caller retries
            // the write, we might end up with a stash of size 3.
            self.sink.write_all(base64::encode_config(&self.stash,
                                                      base64::STANDARD_NO_PAD).as_bytes())?;
            self.column += 4;
            self.linebreak()?;
            self.stash.clear();
        }

        // Ensure that a multiple of 3 bytes are encoded, stash the
        // rest from the end of input.
        while input.len() % 3 > 0 {
            self.stash.push(input[input.len()-1]);
            input = &input[..input.len()-1];
            written += 1;
        }
        // We popped values from the end of the input, fix the order.
        self.stash.reverse();
        assert!(self.stash.len() < 3);

        // We know that we have a multiple of 3 bytes, encode them and write them out.
        assert!(input.len() % 3 == 0);
        let encoded = base64::encode_config(input, base64::STANDARD_NO_PAD);
        written += input.len();
        let mut enc = encoded.as_bytes();
        while enc.len() > 0 {
            let n = min(LINE_LENGTH - self.column, enc.len());
            self.sink.write_all(&enc[..n])?;
            enc = &enc[n..];
            self.column += n;
            self.linebreak()?;
        }

        assert_eq!(written, buf.len());
        Ok(written)
    }

    fn flush(&mut self) -> Result<()> {
        self.sink.flush()
    }
}

impl<W: Write> Drop for Writer<W> {
    fn drop(&mut self) {
        let _ = self.finalize();
    }
}

/// A filter that strips ASCII Armor from a stream of data.
pub struct Reader<'a> {
    source: Box<'a + BufferedReader<()>>,
    kind: Option<Kind>,
    strict: bool,
    buffer: Vec<u8>,
    crc: CRC,
    expect_crc: Option<u32>,
    initialized: bool,
    headers: Vec<(String, String)>,
    finalized: bool,
}

impl<'a> Reader<'a> {
    /// Constructs a new filter for the given type of data.
    ///
    /// [ASCII Armor], designed to protect OpenPGP data in transit,
    /// has been a source of problems if the armor structure is
    /// damaged.  For example, copying data manually from one program
    /// to another might introduce or drop newlines.
    ///
    /// By default, the reader operates in robust mode.  It will
    /// extract the first armored OpenPGP data block it can find, even
    /// if the armor frame is damaged, or missing.
    ///
    /// To select strict mode, specify a kind argument.  In strict
    /// mode, the reader will match on the armor frame.  The reader
    /// ignores any data in front of the Armor Header Line, as long as
    /// the line the header is in is only prefixed by whitespace.
    ///
    ///   [ASCII Armor]: https://tools.ietf.org/html/rfc4880#section-6.2
    ///
    /// # Example
    ///
    /// ```
    /// # use std::io::Read;
    /// # extern crate sequoia_openpgp as openpgp;
    /// # use openpgp::{Result, Message};
    /// # use openpgp::armor::Reader;
    /// # use openpgp::parse::Parse;
    /// # use std::io;
    /// # fn main() { f().unwrap(); }
    /// # fn f() -> Result<()> {
    /// let data = "yxJiAAAAAABIZWxsbyB3b3JsZCE="; // base64 over literal data packet
    ///
    /// let mut cursor = io::Cursor::new(&data);
    /// let mut reader = Reader::new(&mut cursor, None);
    ///
    /// let mut buf = Vec::new();
    /// reader.read_to_end(&mut buf)?;
    ///
    /// let message = Message::from_bytes(&buf)?;
    /// assert_eq!(message.body().unwrap().body().unwrap(),
    ///            b"Hello world!");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Or, in strict mode:
    ///
    /// ```
    /// # use std::io::Read;
    /// # extern crate sequoia_openpgp as openpgp;
    /// # use openpgp::armor::{Reader, Kind};
    /// # use std::io::{self, Result};
    /// # fn main() { f().unwrap(); }
    /// # fn f() -> Result<()> {
    /// let data =
    ///     "-----BEGIN PGP ARMORED FILE-----
    ///
    ///      SGVsbG8gd29ybGQh
    ///      =s4Gu
    ///      -----END PGP ARMORED FILE-----";
    ///
    /// let mut cursor = io::Cursor::new(&data);
    /// let mut reader = Reader::new(&mut cursor, Some(Kind::File));
    ///
    /// let mut content = String::new();
    /// reader.read_to_string(&mut content)?;
    /// assert_eq!(content, "Hello world!");
    /// assert_eq!(reader.kind(), Some(Kind::File));
    /// # Ok(())
    /// # }
    /// ```
    pub fn new<R>(inner: R, kind: Option<Kind>) -> Self
        where R: 'a + Read
    {
        Self::from_buffered_reader(
            Box::new(BufferedReaderGeneric::new(inner, None)),
            kind)
    }

    /// Creates a `Reader` from an `io::Read`er.
    pub fn from_reader<R>(reader: R, kind: Option<Kind>) -> Self
        where R: 'a + Read
    {
        Self::from_buffered_reader(
            Box::new(BufferedReaderGeneric::new(reader, None)),
            kind)
    }

    /// Creates a `Reader` from a file.
    pub fn from_file<P>(path: P, kind: Option<Kind>) -> Result<Self>
        where P: AsRef<Path>
    {
        Ok(Self::from_buffered_reader(
            Box::new(BufferedReaderFile::open(path)?),
            kind))
    }

    /// Creates a `Reader` from a buffer.
    pub fn from_bytes(bytes: &'a [u8], kind: Option<Kind>) -> Self {
        Self::from_buffered_reader(
            Box::new(BufferedReaderMemory::new(bytes)),
            kind)
    }

    pub(crate) fn from_buffered_reader<C: 'a>(
        inner: Box<'a + BufferedReader<C>>, kind: Option<Kind>) -> Self
    {
        Reader {
            source: Box::new(BufferedReaderGeneric::new(inner, None)),
            kind: kind,
            strict: kind.is_some(),
            buffer: Vec::<u8>::with_capacity(1024),
            crc: CRC::new(),
            expect_crc: None,
            headers: Vec::new(),
            initialized: false,
            finalized: false,
        }
    }

    /// Returns the kind of data this reader is for.
    ///
    /// Useful if the kind of data is not known in advance.  If the
    /// header has not been encountered yet (try reading some data
    /// first!), this function returns None.
    pub fn kind(&self) -> Option<Kind> {
        self.kind
    }

    /// Returns the armored headers.
    ///
    /// The tuples contain a key and a value.
    ///
    /// Note: if a key occurs multiple times, then there are multiple
    /// entries in the vector with the same key; values with the same
    /// key are *not* combined.
    pub fn headers(&mut self) -> Result<&[(String, String)]> {
        self.initialize()?;
        Ok(&self.headers[..])
    }

    /// Consumes the header if not already done.
    fn initialize(&mut self) -> Result<()> {
        if self.initialized { return Ok(()) }

        // Look for the Armor Header Line, skipping any garbage in the
        // process.
        let mut n = 0;
        let mut found_blob = false;
        'search: loop {
            self.source.consume(n);

            let line = self.source.read_to('\n' as u8)?;
            n = line.len();
            if n == 0 {
                return Err(
                    Error::new(ErrorKind::InvalidInput,
                               "Reached EOF looking for Armor Header Line"));
            }

            // If the user did not specify what kind of data we want,
            // we aggressively try to decode any data, even if we do
            // not see a valid header.
            if ! self.strict {
                // Try the whole string, as well as substrings
                // starting at each whitespace sequence.
                let mut offset = 0;
                loop {
                    if is_armored_pgp_blob(&line[offset..]) {
                        // Consume anything up to this point.
                        n = offset;
                        found_blob = true;
                        break 'search;
                    }

                    if let Some(o) = &line[offset..].iter()
                        .position(|c| c.is_ascii_whitespace())
                    {
                        offset += *o;

                        // Skip whitespaces.
                        while offset < line.len()
                            && line[offset].is_ascii_whitespace()
                        {
                            offset += 1;
                        }
                    } else {
                        // No armored blob found in this line.
                        break;
                    }
                }
            }

            if line.len() < 27 {
                // Line is too short to contain the shortest header.
                continue;
            }

            for i in 0..(line.len() - 27 + 1) {
                if let Some(kind) = Kind::detect(&line[i..]) {
                    if self.kind == None {
                        // Found any!
                        self.kind = Some(kind);
                        break 'search;
                    }

                    if self.kind == Some(kind) {
                        // Found it!
                        break 'search;
                    }
                }

                if ! line[i].is_ascii_whitespace() {
                    // Non-whitespace prefix.
                    continue 'search;
                }
            }
        }
        self.source.consume(n);

        if found_blob {
            // Skip the rest of the initialization.
            self.initialized = true;
            return Ok(());
        }

        // Read the headers.
        let mut n = 0;
        loop {
            self.source.consume(n);

            let line = self.source.read_to('\n' as u8)?;
            n = line.len();

            let line = str::from_utf8(line);
            // Ignore---don't error out---lines that are not valid UTF8.
            if line.is_err() {
                continue;
            }

            let line = line.unwrap();

            // The line almost certainly ends with \n: the only reason
            // it couldn't is if we encountered EOF.  We need to strip
            // it.  But, if it ends with \r\n, then we also want to
            // strip the \r too.
            let line = if line.ends_with(&"\r\n"[..]) {
                // \r\n.
                &line[..line.len() - 2]
            } else if line.len() > 0 {
                // \n.
                &line[..line.len() - 1]
            } else {
                // EOF.
                line
            };

            /* Process headers.  */
            let key_value = line.splitn(2, ": ").collect::<Vec<&str>>();
            if key_value.len() == 1 {
                if line.trim_left().len() == 0 {
                    // Empty line.
                    break;
                }
            } else {
                let key = key_value[0];
                let value = key_value[1];

                self.headers.push((key.into(), value.into()));
            }
        }
        self.source.consume(n);

        self.initialized = true;
        Ok(())
    }

    /// Parses the footer.
    fn finalize(footer: &[u8], kind: Option<Kind>) -> Result<Option<u32>> {
        let mut off = 0;

        /* Look for CRC.  The CRC is optional.  */
        let crc = if footer.len() >= 6 && footer[0] == '=' as u8
            && footer[1..5].iter().all(is_base64_char)
        {
            /* Found.  */
            let crc = match base64::decode_config(&footer[1..5], base64::MIME) {
                Ok(d) => d,
                Err(e) => return Err(Error::new(ErrorKind::InvalidInput, e)),
            };

            assert_eq!(crc.len(), 3);
            let crc =
                (crc[0] as u32) << 16
                | (crc[1] as u32) << 8
                | crc[2] as u32;

            /* Update offset, skip whitespace.  */
            off += 5;
            while off < footer.len() && footer[off].is_ascii_whitespace() {
                off += 1;
            }

            Some(crc)
        } else {
            None
        };

        if let Some(kind) = kind {
            if ! footer[off..].starts_with(&kind.end().into_bytes()) {
                return Err(Error::new(ErrorKind::InvalidInput, "Invalid ASCII Armor footer."));
            }
        }

        Ok(crc)
    }
}

/// Checks whether the given bytes contain armored OpenPGP data.
fn is_armored_pgp_blob(bytes: &[u8]) -> bool {
    use packet::Tag::*;

    let bytes = if let Some(msg) = get_base64_prefix(bytes) {
        msg
    }  else {
        return false;
    };

    // We may need to drop some characters at the end.
    let mut end = bytes.len();
    loop {
        match base64::decode_config(&bytes[..end], base64::MIME) {
            Ok(d) => {
                let mut br = BufferedReaderMemory::new(&d);
                let header = Header::parse(&mut br);
                break match header {
                    Ok(h) => match h.ctb.tag {
                        // Might be a message?
                        PKESK | SKESK | OnePassSig | CompressedData | Literal =>
                            true,
                        // Might be a key?
                        SecretKey | PublicKey =>
                            true,
                        // Might be a detached signature?
                        Signature =>
                            true,
                        // ... otherwise, looks like garbage.
                        _ =>
                            false,
                    },
                    Err(_) => false,
                }
            },
            Err(_) =>
                if end == 0 {
                    break false;
                } else {
                    end -= 1;
                },
        }
    }
}

/// Gets a slice containing the largest valid base64 prefix.
fn get_base64_prefix(bytes: &[u8]) -> Option<&[u8]> {
    let mut seen_padding = false;
    for (i, c) in bytes.iter().enumerate() {
        if c.is_ascii_whitespace() {
            continue;
        }

        if seen_padding && *c != '=' as u8 {
            return Some(&bytes[..i]);
        }

        if *c == '=' as u8 {
            seen_padding = true;
        } else if ! is_base64_char(c) {
            if i == 0 {
                return None;
            } else {
                return Some(&bytes[..i]);
            }
        }
    }

    return Some(bytes);
}

/// Checks whether the given byte is in the base64 character set.
fn is_base64_char(b: &u8) -> bool {
    b.is_ascii_alphanumeric() || *b == '+' as u8 || *b == '/' as u8
}

/// Checks whether the given slice looks like an armor footer.  If so,
/// returns the size of the footer.
fn is_footer(buf: &[u8], reference: &[u8]) -> Option<usize> {
    if buf.len() < reference.len() {
        return None;
    }

    let mut off = 0;

    // Look for CRC.  The CRC is optional.
    if buf.len() >= 6 && buf[0] == '=' as u8
        && buf[1..5].iter().all(is_base64_char)
    {
        // Found.  Update offset, skip whitespace.
        off += 5;
        while off < buf.len() && buf[off].is_ascii_whitespace() {
            off += 1;
        }
    }

    if buf[off..].starts_with(reference) {
        Some(off + reference.len())
    } else {
        None
    }
}

/// Looks for the footer, returning the footer's offset, and the end
/// of the footer.
fn find_footer(buf: &[u8], kind: Kind) -> Option<(usize, usize)> {
    let reference = kind.end().into_bytes();

    if buf.len() < reference.len() {
        return None;
    }

    for i in 0..buf.len() - reference.len() {
        if let Some(length) = is_footer(&buf[i..], &reference) {
            // Found footer at offset i.
            return Some((i, i + length));
        }
    }
    None
}

impl<'a> Read for Reader<'a> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        self.initialize()?;

        /* How much did we get?  */
        let mut read = 0;

        // First, use what we have in the buffer.
        let amount = min(buf.len(), self.buffer.len());
        &mut buf[..amount].copy_from_slice(&self.buffer[..amount]);
        self.buffer.drain(..amount);
        read += amount;

        // If we could satisfy the read from the buffer, we're done.
        if read == buf.len() {
            return Ok(read);
        }
        assert_eq!(self.buffer.len(), 0);

        // Our buffer is drained.  If we are finalized, nothing more
        // can be read.
        if self.finalized {
            return Ok(read);
        }

        let (consumed, decoded) = {
            // Try to get enough bytes to fill buf, account for bytes
            // filled using our buffer, round up, and add enough for
            // the footer.
            //
            // Later, we may have to get some more until we have a
            // multiple of four non-whitespace ASCII characters.
            let mut want = (buf.len() - read + 2) / 3 * 4
                + self.kind.map(|k| k.footer_max_len()).unwrap_or(46);

            // Keep track of how much we got last time to detect
            // hitting EOF.
            let mut got = 0;

            'readloop: loop {
                let raw = self.source.data(want)?;
                if raw.len() == got {
                    // EOF.  Decide how to proceed.

                    if self.strict {
                        // If we are here, we should have seen an
                        // footer by now.
                        return Err(Error::new(ErrorKind::UnexpectedEof,
                                              "Armor footer is missing"));
                    } else {
                        // Otherwise, we may have found only the blob,
                        // or the footer is damaged, or missing.  Try
                        // to decode what we have got, then we are
                        // done.

                        // We need to try to discard garbage at the end.
                        let mut end = min(raw.len(), want);
                        loop {
                            match base64::decode_config(&raw[..end],
                                                        base64::MIME) {
                                Ok(d) => break 'readloop (end, d),
                                Err(_) =>
                                    if end == 0 {
                                        // No more valid data.
                                        break 'readloop (raw.len(), vec![]);
                                    } else {
                                        end -= 1;
                                    },
                            }
                        }
                    }
                } else {
                    got = raw.len();
                }

                // Check if we see the footer.  If so, we're almost done.
                if let Some(kind) = self.kind {
                    if let Some((n, end)) = find_footer(&raw, kind) {
                        self.expect_crc = Reader::finalize(&raw[n..], self.kind)?;
                        self.finalized = true;
                        match base64::decode_config(&raw[..n], base64::MIME) {
                            Ok(d) => break (end, d),
                            Err(e) =>
                                return Err(Error::new(ErrorKind::InvalidInput, e)),
                        }
                    }
                }

                // See how many valid characters we got.
                let n = &raw.iter().filter(
                    |c| ! (**c).is_ascii_whitespace()).count();
                if n % 4 == 0 {
                    // Enough!  Try to decode them.

                    // We need to try to discard garbage at the end.
                    let mut end = raw.len();
                    loop {
                        match base64::decode_config(&raw[..end],
                                                    base64::MIME) {
                            Ok(d) => break 'readloop (end, d),
                            Err(_) =>
                                if end == 0 {
                                    // No more valid data.
                                    break 'readloop (raw.len(), vec![]);
                                } else {
                                    end -= 1;
                                },
                        }
                    }
                }

                // Otherwise, get some more bytes.
                want = got + 4 - n % 4;
            }
        };
        self.source.consume(consumed);
        self.crc.update(&decoded);

        /* Check how much we got vs how much was requested.  */
        if decoded.len() <= (buf.len() - read) {
            &mut buf[read..read + decoded.len()].copy_from_slice(&decoded);
            read += decoded.len();
        } else {
            // We got more than we wanted, spill the surplus into our
            // buffer.
            let spill = decoded.len() - (buf.len() - read);

            &mut buf[read..read + decoded.len() - spill].copy_from_slice(
                &decoded[..decoded.len() - spill]);
            read += decoded.len() - spill;

            self.buffer.extend_from_slice(&decoded[decoded.len() - spill..]);
        }

        /* If we are finalized, we may have found a crc sum.  */
        if let Some(crc) = self.expect_crc {
            if self.crc.finalize() != crc {
                return Err(Error::new(ErrorKind::InvalidInput, "Bad CRC sum."));
            }
        }
        Ok(read)
    }
}

// XXX: impl BufferedReader for Reader

#[macro_export]
/// Constructs a reader from an armored string literal.
///
/// # Example
///
/// ```
/// use std::io::Read;
/// #[macro_use] extern crate sequoia_openpgp as openpgp;
/// # use std::io::Result;
/// # fn main() { f().unwrap(); }
/// # fn f() -> Result<()> {
///
/// let mut reader = armored!(
///     "-----BEGIN PGP ARMORED FILE-----
///
///      SGVsbG8gd29ybGQh
///      =s4Gu
///      -----END PGP ARMORED FILE-----"
/// );
///
/// let mut content = String::new();
/// reader.read_to_string(&mut content)?;
/// assert_eq!(content, "Hello world!");
/// # Ok(())
/// # }
/// ```
macro_rules! armored {
    ($data:expr) => {{
        use ::std::io::Cursor;
        $crate::armor::Reader::new(Cursor::new(&$data), None)
    }};
}

const CRC24_INIT: u32 = 0xB704CE;
const CRC24_POLY: u32 = 0x1864CFB;

struct CRC {
    n: u32,
}

/// Computess the CRC-24, (see [RFC 4880, section 6.1]).
///
/// [RFC 4880, section 6.1]: https://tools.ietf.org/html/rfc4880#section-6.1
impl CRC {
    fn new() -> Self {
        CRC { n: CRC24_INIT }
    }

    fn update(&mut self, buf: &[u8]) -> &Self {
        for octet in buf {
            self.n ^= (*octet as u32) << 16;
            for _ in 0..8 {
                self.n <<= 1;
                if self.n & 0x1000000 > 0 {
                    self.n ^= CRC24_POLY;
                }
            }
        }
        self
    }

    fn finalize(&self) -> u32 {
        self.n & 0xFFFFFF
    }
}

#[cfg(test)]
mod test {
    use std::io::Write;
    use super::CRC;
    use super::Kind;
    use super::Writer;

    #[test]
    fn crc() {
        let b = b"foobarbaz";
        let crcs = [
            0xb704ce,
            0x6d2804,
            0xa2d10d,
            0x4fc255,
            0x7aafca,
            0xc79c46,
            0x7334de,
            0x77dc72,
            0x000f65,
            0xf40d86,
        ];

        for len in 0..b.len() + 1 {
            assert_eq!(CRC::new().update(&b[..len]).finalize(), crcs[len]);
        }
    }

    use std::fs::File;
    use std::io::prelude::*;

    const TEST_VECTORS: [u8; 9] = [0, 1, 2, 3, 47, 48, 49, 50, 51];

    #[test]
    fn enarmor() {
        for len in TEST_VECTORS.iter() {
            let mut file = File::open(format!("tests/data/armor/test-{}.bin", len)).unwrap();
            let mut bin = Vec::<u8>::new();
            file.read_to_end(&mut bin).unwrap();

            let mut file = File::open(format!("tests/data/armor/test-{}.asc", len)).unwrap();
            let mut asc = Vec::<u8>::new();
            file.read_to_end(&mut asc).unwrap();

            let mut buf = Vec::new();
            {
                let mut w = Writer::new(&mut buf, Kind::File, &[]).unwrap();
                w.write(&[]).unwrap();  // Avoid zero-length optimization.
                w.write_all(&bin).unwrap();
            }
            assert_eq!(String::from_utf8_lossy(&buf),
                       String::from_utf8_lossy(&asc));
        }
    }

    #[test]
    fn enarmor_bytewise() {
        for len in TEST_VECTORS.iter() {
            let mut file = File::open(format!("tests/data/armor/test-{}.bin", len)).unwrap();
            let mut bin = Vec::<u8>::new();
            file.read_to_end(&mut bin).unwrap();

            let mut file = File::open(format!("tests/data/armor/test-{}.asc", len)).unwrap();
            let mut asc = Vec::<u8>::new();
            file.read_to_end(&mut asc).unwrap();

            let mut buf = Vec::new();
            {
                let mut w = Writer::new(&mut buf, Kind::File, &[]).unwrap();
                w.write(&[]).unwrap();  // Avoid zero-length optimization.
                for (i, _) in bin.iter().enumerate() {
                    w.write(&bin[i..i+1]).unwrap();
                }
            }
            assert_eq!(String::from_utf8_lossy(&buf),
                       String::from_utf8_lossy(&asc));
        }
    }

    #[test]
    fn drop_writer() {
        // No ASCII frame shall be emitted if the writer is dropped
        // unused.
        let mut buf = Vec::new();
        {
            drop(Writer::new(&mut buf, Kind::File, &[]).unwrap());
        }
        assert!(buf.is_empty());

        // However, if the user insists, we will encode a zero-byte
        // string.
        let mut buf = Vec::new();
        {
            let mut w = Writer::new(&mut buf, Kind::File, &[]).unwrap();
            w.write(&[]).unwrap();
        }
        assert_eq!(
            &buf[..],
            &b"-----BEGIN PGP ARMORED FILE-----\n\
               \n\
               =twTO\n\
               -----END PGP ARMORED FILE-----\n"[..]);
    }

    use super::Reader;

    #[test]
    fn dearmor_robust() {
        for len in TEST_VECTORS.iter() {
            let mut file = File::open(format!("tests/data/armor/literal-{}.bin",
                                              len)).unwrap();
            let mut reference = Vec::<u8>::new();
            file.read_to_end(&mut reference).unwrap();

            for test in &["", "-no-header-with-chksum", "-no-header",
                          "-no-newlines"] {
                let filename = format!("tests/data/armor/literal-{}{}.asc",
                                       len, test);
                let mut file = File::open(filename).unwrap();
                let mut r = Reader::new(&mut file, None);
                let mut dearmored = Vec::<u8>::new();
                r.read_to_end(&mut dearmored).unwrap();

                assert_eq!(&reference, &dearmored);
            }
        }
    }

    #[test]
    fn dearmor_binary() {
        for len in TEST_VECTORS.iter() {
            let mut file = File::open(format!("tests/data/armor/test-{}.bin", len)).unwrap();
            let mut r = Reader::new(&mut file, Some(Kind::Message));
            let mut buf = [0; 5];
            let e = r.read(&mut buf);
            assert!(e.is_err());
        }
    }

    #[test]
    fn dearmor_wrong_kind() {
        let mut file = File::open("tests/data/armor/test-0.asc").unwrap();
        let mut r = Reader::new(&mut file, Some(Kind::Message));
        let mut buf = [0; 5];
        let e = r.read(&mut buf);
        assert!(e.is_err());
    }

    #[test]
    fn dearmor_wrong_crc() {
        let mut file = File::open("tests/data/armor/test-0.bad-crc.asc").unwrap();
        let mut r = Reader::new(&mut file, Some(Kind::File));
        let mut buf = [0; 5];
        let e = r.read(&mut buf);
        assert!(e.is_err());
    }

    #[test]
    fn dearmor_wrong_footer() {
        let mut file = File::open("tests/data/armor/test-2.bad-footer.asc").unwrap();
        let mut r = Reader::new(&mut file, Some(Kind::File));
        let mut buf = [0; 5];
        let e = r.read(&mut buf);
        assert!(e.is_err());
    }

    #[test]
    fn dearmor_no_crc() {
        let mut file = File::open("tests/data/armor/test-1.no-crc.asc").unwrap();
        let mut r = Reader::new(&mut file, Some(Kind::File));
        let mut buf = [0; 5];
        let e = r.read(&mut buf);
        assert!(e.unwrap() == 1 && buf[0] == 0xde);
    }

    #[test]
    fn dearmor_with_header() {
        let mut file = File::open("tests/data/armor/test-3.with-headers.asc").unwrap();
        let mut r = Reader::new(&mut file, Some(Kind::File));
        assert_eq!(r.headers().unwrap(),
                   &[("Comment".into(), "Some Header".into()),
                     ("Comment".into(), "Another one".into())]);
        let mut buf = [0; 5];
        let e = r.read(&mut buf);
        assert!(e.is_ok());
    }

    #[test]
    fn dearmor_any() {
        let mut file = File::open("tests/data/armor/test-3.with-headers.asc").unwrap();
        let mut r = Reader::new(&mut file, None);
        let mut buf = [0; 5];
        let e = r.read(&mut buf);
        assert!(r.kind() == Some(Kind::File));
        assert!(e.is_ok());
    }

    #[test]
    fn dearmor_with_garbage() {
        use std::io::Cursor;

        // Get some valid data.
        let mut armored = Vec::new();
        File::open("tests/data/armor/test-3.with-headers.asc")
            .unwrap()
            .read_to_end(&mut armored)
            .unwrap();

        // Slap some garbage in front and make sure it still reads ok.
        let mut garbage = Vec::new();
        write!(&mut garbage, "Some\ngarbage\nlines\n\t\r  ").unwrap();
        garbage.extend_from_slice(&armored);

        let mut r = Reader::new(Cursor::new(&garbage), None);
        let mut buf = [0; 5];
        let e = r.read(&mut buf);
        assert!(r.kind() == Some(Kind::File));
        assert!(e.is_ok());

        // Again, but this time add a non-whitespace character in the
        // line of the header.
        let mut garbage = Vec::new();
        write!(&mut garbage, "Some\ngarbage\nlines\n\t.\r  ").unwrap();
        garbage.extend_from_slice(&armored);

        let mut r = Reader::new(Cursor::new(&garbage), None);
        let mut buf = [0; 5];
        let e = r.read(&mut buf);
        assert!(e.is_err());
    }

    #[test]
    fn dearmor() {
        for len in TEST_VECTORS.iter() {
            let mut file = File::open(format!("tests/data/armor/test-{}.bin", len)).unwrap();
            let mut bin = Vec::<u8>::new();
            file.read_to_end(&mut bin).unwrap();

            let mut file = File::open(format!("tests/data/armor/test-{}.asc", len)).unwrap();
            let mut r = Reader::new(&mut file, Some(Kind::File));
            let mut dearmored = Vec::<u8>::new();
            r.read_to_end(&mut dearmored).unwrap();

            assert_eq!(&bin, &dearmored);
        }
    }

    #[test]
    fn dearmor_bytewise() {
        for len in TEST_VECTORS.iter() {
            let mut file = File::open(format!("tests/data/armor/test-{}.bin", len)).unwrap();
            let mut bin = Vec::<u8>::new();
            file.read_to_end(&mut bin).unwrap();

            let mut file = File::open(format!("tests/data/armor/test-{}.asc", len)).unwrap();
            let r = Reader::new(&mut file, Some(Kind::File));
            let mut dearmored = Vec::<u8>::new();
            for c in r.bytes() {
                dearmored.push(c.unwrap());
            }

            assert_eq!(&bin, &dearmored);
        }
    }

    #[test]
    fn dearmor_yuge() {
        let mut file =
            File::open("tests/data/keys/yuge-key-so-yuge-the-yugest.asc")
            .unwrap();
        let mut r = Reader::new(&mut file, None);
        let mut dearmored = Vec::<u8>::new();
        r.read_to_end(&mut dearmored).unwrap();

        let mut file =
            File::open("tests/data/keys/yuge-key-so-yuge-the-yugest.asc")
            .unwrap();
        let r = Reader::new(&mut file, None);
        let mut dearmored = Vec::<u8>::new();
        for c in r.bytes() {
            dearmored.push(c.unwrap());
        }
    }

    quickcheck! {
        fn roundtrip(kind: Kind, payload: Vec<u8>) -> bool {
            use std::io::Cursor;

            if payload.is_empty() {
                // Empty payloads do not emit an armor framing unless
                // one does an explicit empty write (and .write_all()
                // does not).
                return true;
            }

            let mut encoded = Vec::new();
            Writer::new(&mut encoded, kind, &[]).unwrap()
                .write_all(&payload)
                .unwrap();

            let mut recovered = Vec::new();
            Reader::new(Cursor::new(&encoded), Some(kind))
                .read_to_end(&mut recovered)
                .unwrap();

            let mut recovered_any = Vec::new();
            Reader::new(Cursor::new(&encoded), None)
                .read_to_end(&mut recovered_any)
                .unwrap();

            payload == recovered && payload == recovered_any
        }
    }
}