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
//! www-authenticate
//! missing HTTP WWW-Authenticate header parser/printer for hyper

extern crate hyperx;
extern crate unicase;
extern crate url;

use hyperx::Result;
use hyperx::header::{Formatter, Header, Raw};
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::mem;
use std::ops::{Deref, DerefMut};
use unicase::UniCase;

/// `WWW-Authenticate` header, defined in
/// [RFC7235](https://tools.ietf.org/html/rfc7235#section-4.1)
///
/// The `WWW-Authenticate` header field indicates the authentication
/// scheme(s) and parameters applicable to the target resource.
/// This MUST be contained in HTTP responses whose status is 401.
///
/// # ABNF
/// ```plain
/// WWW-Authenticate = 1#challenge
/// ```
///
/// # Example values
/// * `Basic realm="foo", charset="UTF-8"`
/// * `Digest
///    realm="http-auth@example.org",
///    qop="auth, auth-int",
///    algorithm=MD5,
///    nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v",
///    opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"`
///
/// # Examples
///
/// ```
/// # extern crate hyperx;
/// # extern crate www_authenticate;
/// # use hyperx::header::Headers;
/// # use www_authenticate::{WwwAuthenticate, DigestChallenge, Qop,
/// # Algorithm};
/// # fn main(){
/// let auth = WwwAuthenticate::new(
///     DigestChallenge {
///         realm: Some("http-auth@example.org".into()),
///         qop: Some(vec![Qop::Auth, Qop::AuthInt]),
///         algorithm: Some(Algorithm::Sha256),
///         nonce: Some("7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v".into()),
///         opaque: Some("FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"
///                          .into()),
///         domain: None,
///         stale: None,
///         userhash: None,
/// });
/// let mut headers = Headers::new();
/// headers.set(auth);
/// # }
/// ```
///
/// ```
/// # extern crate hyperx;
/// # extern crate www_authenticate;
/// # use hyperx::header::Headers;
/// # use www_authenticate::{WwwAuthenticate, BasicChallenge};
/// # fn main(){
/// let auth = WwwAuthenticate::new(BasicChallenge{realm: "foo".into()});
/// let mut headers = Headers::new();
/// headers.set(auth);
/// let auth = headers.get::<WwwAuthenticate>().unwrap();
/// let basics = auth.get::<BasicChallenge>().unwrap();
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct WwwAuthenticate(HashMap<UniCase<CowStr>, Vec<RawChallenge>>);

/// The challenge described in
/// [RFC7235](https://tools.ietf.org/html/rfc7235#section-4.1).
/// Used in `WWW-Authenticate` header.
pub trait Challenge: Clone {
    fn challenge_name() -> &'static str;
    fn from_raw(raw: RawChallenge) -> Option<Self>;
    fn into_raw(self) -> RawChallenge;
}

impl WwwAuthenticate {
    pub fn new<C: Challenge>(c: C) -> Self {
        let mut auth = WwwAuthenticate(HashMap::new());
        auth.set(c);
        auth
    }

    pub fn new_from_raw(scheme: String, raw: RawChallenge) -> Self {
        let mut auth = WwwAuthenticate(HashMap::new());
        auth.set_raw(scheme, raw);
        auth
    }

    /// find challenges and convert them into `C` if found.
    pub fn get<C: Challenge>(&self) -> Option<Vec<C>> {
        self.0
            .get(&UniCase(CowStr(Cow::Borrowed(C::challenge_name()))))
            .map(|m| m.iter().map(Clone::clone).flat_map(C::from_raw).collect())
    }

    /// find challenges and return it if found
    pub fn get_raw(&self, name: &str) -> Option<&[RawChallenge]> {
        self.0
            .get(&UniCase(CowStr(Cow::Borrowed(unsafe {
                mem::transmute::<&str, &'static str>(name)
            }))))
            .map(AsRef::as_ref)
    }

    /// set a challenge. This replaces existing challenges of the same name.
    pub fn set<C: Challenge>(&mut self, c: C) -> bool {
        self.0
            .insert(
                UniCase(CowStr(Cow::Borrowed(C::challenge_name()))),
                vec![c.into_raw()],
            )
            .is_some()
    }

    /// set a challenge. This replaces existing challenges of the same name.
    pub fn set_raw(&mut self, scheme: String, raw: RawChallenge) -> bool {
        self.0
            .insert(UniCase(CowStr(Cow::Owned(scheme))), vec![raw])
            .is_some()
    }

    /// append a challenge. This appends existing challenges of the same name.
    pub fn append<C: Challenge>(&mut self, c: C) {
        self.0
            .entry(UniCase(CowStr(Cow::Borrowed(C::challenge_name()))))
            .or_insert(Vec::new())
            .push(c.into_raw())
    }

    /// append a challenge. This appends existing challenges of the same name.
    pub fn append_raw(&mut self, scheme: String, raw: RawChallenge) {
        self.0
            .entry(UniCase(CowStr(Cow::Owned(scheme))))
            .or_insert(Vec::new())
            .push(raw)
    }

    /// test if the challenge exists
    pub fn has<C: Challenge>(&self) -> bool {
        self.get::<C>().is_some()
    }
}

impl fmt::Display for WwwAuthenticate {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for (scheme, values) in &self.0 {
            for value in values.iter() {
                // tail commas are allowed
                write!(f, "{} {}, ", scheme, value)?;
            }
        }
        Ok(())
    }
}

impl Header for WwwAuthenticate {
    fn header_name() -> &'static str {
        "WWW-Authenticate"
    }

    fn parse_header(raw: &Raw) -> Result<Self> {
        let mut map = HashMap::new();
        for data in raw {
            let stream = parser::Stream::new(data.as_ref());
            loop {
                let (scheme, challenge) = match stream.challenge() {
                    Ok(v) => v,
                    Err(e) => {
                        if stream.is_end() {
                            break;
                        } else {
                            return Err(e);
                        }
                    }
                };
                // TODO: treat the cases when a scheme is duplicated
                map.entry(UniCase(CowStr(Cow::Owned(scheme))))
                    .or_insert(Vec::new())
                    .push(challenge);
            }
        }
        Ok(WwwAuthenticate(map))
    }

    fn fmt_header(&self, f: &mut Formatter) -> fmt::Result {
        f.fmt_line(self)
    }
}

#[test]
fn test_www_authenticate_multiple_headers() {
    let input1 = br#"Digest realm="http-auth@example.org", qop="auth, auth-int", algorithm=SHA-256, nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS""#.to_vec();
    let input2 = br#"Digest realm="http-auth@example.org", qop="auth, auth-int", algorithm=MD5, nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS""#.to_vec();
    let input = vec![input1, input2];

    let auth = WwwAuthenticate::parse_header(&input.into()).unwrap();
    let digests = auth.get::<DigestChallenge>().unwrap();
    assert!(digests.contains(&DigestChallenge {
        realm: Some("http-auth@example.org".into()),
        qop: Some(vec![Qop::Auth, Qop::AuthInt]),
        algorithm: Some(Algorithm::Sha256),
        nonce: Some("7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v".into()),
        opaque: Some("FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS".into()),
        domain: None,
        stale: None,
        userhash: None,
    }));

    assert!(digests.contains(&DigestChallenge {
        realm: Some("http-auth@example.org".into()),
        qop: Some(vec![Qop::Auth, Qop::AuthInt]),
        algorithm: Some(Algorithm::Md5),
        nonce: Some("7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v".into()),
        opaque: Some("FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS".into()),
        domain: None,
        stale: None,
        userhash: None,
    }));
}

macro_rules! try_opt {
    ($e:expr) => {
        match $e {
            Some(e) => e,
            None => return None,
        }
    };
}

#[derive(Clone, Hash, Eq, PartialEq, PartialOrd, Ord)]
struct CowStr(Cow<'static, str>);

impl Deref for CowStr {
    type Target = Cow<'static, str>;

    fn deref(&self) -> &Cow<'static, str> {
        &self.0
    }
}

impl fmt::Debug for CowStr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, f)
    }
}

impl fmt::Display for CowStr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl DerefMut for CowStr {
    fn deref_mut(&mut self) -> &mut Cow<'static, str> {
        &mut self.0
    }
}

impl AsRef<str> for CowStr {
    fn as_ref(&self) -> &str {
        self
    }
}

pub use self::raw::*;
mod raw {
    use super::*;
    use std::borrow::Cow;
    use std::mem;
    use unicase::UniCase;

    #[derive(Debug, Clone, PartialEq, Eq)]
    enum Quote {
        Always,
        IfNeed,
    }

    /// A representation of the challenge fields
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub struct ChallengeFields(HashMap<UniCase<CowStr>, (String, Quote)>);

    impl ChallengeFields {
        pub fn new() -> Self {
            ChallengeFields(HashMap::new())
        }
        // fn values(&self) -> Values<K, V>
        // fn values_mut(&mut self) -> ValuesMut<K, V>
        // fn iter(&self) -> Iter<K, V>
        // fn iter_mut(&mut self) -> IterMut<K, V>
        // fn entry(&mut self, key: K) -> Entry<K, V>
        pub fn len(&self) -> usize {
            self.0.len()
        }
        pub fn is_empty(&self) -> bool {
            self.0.is_empty()
        }
        // fn drain(&mut self) -> Drain<K, V>
        pub fn clear(&mut self) {
            self.0.clear()
        }
        pub fn get(&self, k: &str) -> Option<&String> {
            self.0
                .get(&UniCase(CowStr(Cow::Borrowed(unsafe {
                    mem::transmute::<&str, &'static str>(k)
                }))))
                .map(|&(ref s, _)| s)
        }
        pub fn contains_key(&self, k: &str) -> bool {
            self.0.contains_key(&UniCase(CowStr(Cow::Borrowed(unsafe {
                mem::transmute::<&str, &'static str>(k)
            }))))
        }
        pub fn get_mut(&mut self, k: &str) -> Option<&mut String> {
            self.0
                .get_mut(&UniCase(CowStr(Cow::Borrowed(unsafe {
                    mem::transmute::<&str, &'static str>(k)
                }))))
                .map(|&mut (ref mut s, _)| s)
        }
        pub fn insert(&mut self, k: String, v: String) -> Option<String> {
            self.0
                .insert(UniCase(CowStr(Cow::Owned(k))), (v, Quote::IfNeed))
                .map(|(s, _)| s)
        }
        pub fn insert_quoting(&mut self, k: String, v: String) -> Option<String> {
            self.0
                .insert(UniCase(CowStr(Cow::Owned(k))), (v, Quote::Always))
                .map(|(s, _)| s)
        }
        pub fn insert_static(&mut self, k: &'static str, v: String) -> Option<String> {
            self.0
                .insert(UniCase(CowStr(Cow::Borrowed(k))), (v, Quote::IfNeed))
                .map(|(s, _)| s)
        }
        pub fn insert_static_quoting(&mut self, k: &'static str, v: String) -> Option<String> {
            self.0
                .insert(UniCase(CowStr(Cow::Borrowed(k))), (v, Quote::Always))
                .map(|(s, _)| s)
        }
        pub fn remove(&mut self, k: &str) -> Option<String> {
            self.0
                .remove(&UniCase(CowStr(Cow::Borrowed(unsafe {
                    mem::transmute::<&str, &'static str>(k)
                }))))
                .map(|(s, _)| s)
        }
    }
    // index

    /// A representation of raw challenges. A Challenge is either a token or
    /// fields.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub enum RawChallenge {
        Token68(String),
        Fields(ChallengeFields),
    }

    fn need_quote(s: &str, q: &Quote) -> bool {
        if q == &Quote::Always {
            true
        } else {
            s.bytes().any(|c| !parser::is_token_char(c))
        }
    }

    impl fmt::Display for RawChallenge {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            use self::RawChallenge::*;
            match *self {
                Token68(ref token) => write!(f, "{}", token)?,
                Fields(ref fields) => for (k, &(ref v, ref quote)) in fields.0.iter() {
                    if need_quote(v, quote) {
                        write!(f, "{}={:?}, ", k, v)?
                    } else {
                        write!(f, "{}={}, ", k, v)?
                    }
                },
            }
            Ok(())
        }
    }
}

pub use self::basic::*;
mod basic {
    use super::raw::RawChallenge;
    use super::*;

    /// The challenge for Basic authentication
    #[derive(Debug, Clone, Eq, PartialEq, Hash)]
    pub struct BasicChallenge {
        /// realm of the authentication
        pub realm: String,
        // pub charset: Option<Charset>
    }

    impl Challenge for BasicChallenge {
        fn challenge_name() -> &'static str {
            "Basic"
        }
        fn from_raw(raw: RawChallenge) -> Option<Self> {
            use self::RawChallenge::*;
            match raw {
                Token68(_) => return None,
                Fields(mut map) => {
                    let realm = try_opt!(map.remove("realm"));
                    // only "UTF-8" is allowed.
                    // See https://tools.ietf.org/html/rfc7617#section-2.1
                    match map.remove("charset") {
                        Some(c) => {
                            if UniCase(&c) == UniCase("UTF-8") {
                                ()
                            } else {
                                return None;
                            }
                        }
                        None => (),
                    }
                    if !map.is_empty() {
                        return None;
                    }
                    Some(BasicChallenge { realm: realm })
                }
            }
        }
        fn into_raw(self) -> RawChallenge {
            let mut map = ChallengeFields::new();
            map.insert_static("realm", self.realm);
            RawChallenge::Fields(map)
        }
    }

    #[test]
    fn test_parse_basic() {
        let input = "Basic realm=\"secret zone\"";
        let auth = WwwAuthenticate::parse_header(&input.into()).unwrap();
        let mut basics = auth.get::<BasicChallenge>().unwrap();
        assert_eq!(basics.len(), 1);
        let basic = basics.swap_remove(0);
        assert_eq!(basic.realm, "secret zone")
    }

    #[test]
    fn test_roundtrip_basic() {
        let basic = BasicChallenge {
            realm: "secret zone".into(),
        };
        let auth = WwwAuthenticate::new(basic.clone());
        let data = format!("{}", auth);
        let auth = WwwAuthenticate::parse_header(&data.into()).unwrap();
        let basic_tripped = auth.get::<BasicChallenge>().unwrap().swap_remove(0);
        assert_eq!(basic, basic_tripped);
    }
}

pub use self::digest::*;
mod digest {
    use super::*;
    use std::str::FromStr;
    use url::Url;

    /// The challenge for Digest authentication
    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
    pub struct DigestChallenge {
        /// realm of the authentication
        pub realm: Option<String>,
        /// domains of the authentication
        pub domain: Option<Vec<Url>>,
        /// the nonce used in authentiaction
        pub nonce: Option<String>,
        /// a string data specified by the server
        pub opaque: Option<String>,
        /// a flag indicating that the previous request from
        /// the client was rejected because the nonce value was stale.
        pub stale: Option<bool>,
        /// the algorithm used to produce the digest and unkeyed digest.
        /// if not present, it is assumed to be Md5
        pub algorithm: Option<Algorithm>,
        /// "quality of protection" values supported by the server
        pub qop: Option<Vec<Qop>>,
        // pub charset: Option<Charset>,
        /// this is an OPTIONAL parameter that is used by the server to
        /// indicate that it supports username hashing.
        /// default is false if not present
        pub userhash: Option<bool>,
    }

    /// Algorithms used to produce the digest and unkeyed digest.
    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
    pub enum Algorithm {
        /// MD5
        Md5,
        /// MD5-sess
        Md5Sess,
        /// SHA-512-256
        Sha512Trunc256,
        /// SHA-512-256-sess
        Sha512Trunc256Sess,
        /// SHA-256
        Sha256,
        /// SHA-256-sess
        Sha256Sess,
        /// other algorithm
        Other(String),
    }

    /// Quority of protection
    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
    pub enum Qop {
        /// authentication
        Auth,
        /// authentication with integrity protection
        AuthInt,
    }

    impl Challenge for DigestChallenge {
        fn challenge_name() -> &'static str {
            "Digest"
        }
        fn from_raw(raw: RawChallenge) -> Option<Self> {
            use self::RawChallenge::*;
            match raw {
                Token68(_) => return None,
                Fields(mut map) => {
                    let realm = map.remove("realm");
                    let domains = map.remove("domain");
                    let nonce = map.remove("nonce");
                    let opaque = map.remove("opaque");
                    let stale = map.remove("stale");
                    let algorithm = map.remove("algorithm");
                    let qop = map.remove("qop");
                    let charset = map.remove("charset");
                    let userhash = map.remove("userhash");

                    if !map.is_empty() {
                        return None;
                    }

                    let domains = domains.and_then(|ds| {
                        ds.split_whitespace()
                            .map(Url::from_str)
                            .map(::std::result::Result::ok)
                            .collect::<Option<Vec<Url>>>()
                    });
                    let stale = stale.map(|s| s == "true");
                    let algorithm = algorithm.map(|a| {
                        use self::Algorithm::*;
                        match a.as_str() {
                            "MD5" => return Md5,
                            "MD5-sess" => return Md5Sess,
                            "SHA-512-256" => return Sha512Trunc256,
                            "SHA-512-256-sess" => return Sha512Trunc256Sess,
                            "SHA-256" => return Sha256,
                            "SHA-256-sess" => return Sha256Sess,
                            _ => (),
                        };
                        return Other(a);
                    });
                    let qop = match qop {
                        None => None,
                        Some(qop) => {
                            let mut v = vec![];
                            let s = parser::Stream::new(qop.as_bytes());
                            loop {
                                match try_opt!(s.token().ok()) {
                                    "auth" => v.push(Qop::Auth),
                                    "auth-int" => v.push(Qop::AuthInt),
                                    _ => (),
                                }
                                try_opt!(s.skip_field_sep().ok());
                                if s.is_end() {
                                    break;
                                }
                            }
                            Some(v)
                        }
                    };
                    match charset {
                        Some(c) => {
                            if UniCase(&c) == UniCase("UTF-8") {
                                ()
                            } else {
                                return None;
                            }
                        }
                        None => (),
                    }

                    let userhash = userhash.and_then(|u| match u.as_str() {
                        "true" => Some(true),
                        "false" => Some(false),
                        _ => None,
                    });
                    Some(DigestChallenge {
                        realm: realm,
                        domain: domains,
                        nonce: nonce,
                        opaque: opaque,
                        stale: stale,
                        algorithm: algorithm,
                        qop: qop,
                        // pub charset: Option<Charset>,
                        userhash: userhash,
                    })
                }
            }
        }
        fn into_raw(self) -> RawChallenge {
            let mut map = ChallengeFields::new();
            // Notes on quoting/non-quoting from the spec
            // ttps://tools.ietf.org/html/rfc7616#section-3.3
            //
            // > For historical reasons, a sender MUST only generate the quoted string
            // > syntax values for the following parameters: realm, domain, nonce,
            // > opaque, and qop.
            // >
            // > For historical reasons, a sender MUST NOT generate the quoted string
            // > syntax values for the following parameters: stale and algorithm.

            for realm in self.realm {
                map.insert_static_quoting("realm", realm);
            }

            for domain in self.domain {
                let mut d = String::new();
                d.extend(domain.into_iter().map(Url::into_string).map(|s| s + " "));
                let len = d.len();
                d.truncate(len - 1);
                map.insert_static_quoting("domain", d);
            }
            for nonce in self.nonce {
                map.insert_static_quoting("nonce", nonce);
            }
            for opaque in self.opaque {
                map.insert_static_quoting("opaque", opaque);
            }
            for stale in self.stale {
                map.insert_static("stale", format!("{}", stale));
            }
            for algorithm in self.algorithm {
                map.insert_static("algorithm", format!("{}", algorithm));
            }
            for qop in self.qop {
                let mut q = String::new();
                q.extend(qop.into_iter().map(|q| format!("{}", q)).map(|s| s + ", "));
                let len = q.len();
                q.truncate(len - 2);
                map.insert_static_quoting("qop", q);
            }
            for userhash in self.userhash {
                map.insert_static("userhash", format!("{}", userhash));
            }
            RawChallenge::Fields(map)
        }
    }

    impl fmt::Display for Algorithm {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            use self::Algorithm::*;
            match *self {
                Md5 => write!(f, "MD5"),
                Md5Sess => write!(f, "MD5-sess"),
                Sha512Trunc256 => write!(f, "SHA-512-256"),
                Sha512Trunc256Sess => write!(f, "SHA-512-256-sess"),
                Sha256 => write!(f, "SHA-256"),
                Sha256Sess => write!(f, "SHA-256-sess"),
                Other(ref s) => write!(f, "{}", s),
            }
        }
    }

    impl fmt::Display for Qop {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            use self::Qop::*;
            match *self {
                Auth => write!(f, "auth"),
                AuthInt => write!(f, "auth-int"),
            }
        }
    }

    #[test]
    fn test_parse_digest() {
        let input = r#"Digest realm="http-auth@example.org", qop="auth, auth-int", algorithm=SHA-256, nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS""#;
        let auth = WwwAuthenticate::parse_header(&input.into()).unwrap();
        let mut digests = auth.get::<DigestChallenge>().unwrap();
        assert_eq!(digests.len(), 1);
        let digest = digests.swap_remove(0);
        assert_eq!(digest.realm, Some("http-auth@example.org".into()));
        assert_eq!(digest.domain, None);
        assert_eq!(
            digest.nonce,
            Some("7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v".into())
        );
        assert_eq!(
            digest.opaque,
            Some("FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS".into())
        );
        assert_eq!(digest.stale, None);
        assert_eq!(digest.algorithm, Some(Algorithm::Sha256));
        assert_eq!(digest.qop, Some(vec![Qop::Auth, Qop::AuthInt]));
        assert_eq!(digest.userhash, None);
    }

    #[test]
    fn test_roundtrip_digest() {
        let digest = DigestChallenge {
            realm: Some("http-auth@example.org".into()),
            domain: None,
            nonce: Some("7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v".into()),
            opaque: Some("FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS".into()),
            stale: None,
            algorithm: Some(Algorithm::Sha256),
            qop: Some(vec![Qop::Auth, Qop::AuthInt]),
            userhash: None,
        };
        let auth = WwwAuthenticate::new(digest.clone());
        let data = format!("{}", auth);
        let auth = WwwAuthenticate::parse_header(&data.into()).unwrap();
        let digest_tripped = auth.get::<DigestChallenge>().unwrap().swap_remove(0);
        assert_eq!(digest, digest_tripped);
    }
}

mod parser {
    use super::raw::{ChallengeFields, RawChallenge};
    use hyperx::{Error, Result};
    use std::cell::Cell;
    use std::str::from_utf8_unchecked;

    pub struct Stream<'a>(Cell<usize>, &'a [u8]);

    pub fn is_ws(c: u8) -> bool {
        // See https://tools.ietf.org/html/rfc7230#section-3.2.3
        b"\t ".contains(&c)
    }

    pub fn is_token_char(c: u8) -> bool {
        // See https://tools.ietf.org/html/rfc7230#section-3.2.6
        br#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!#$%&'*+-.^_`|~"#.contains(&c)
    }

    pub fn is_obs_text(c: u8) -> bool {
        // See https://tools.ietf.org/html/rfc7230#section-3.2.6
        // u8 is always under 0xFF
        0x80 <= c
    }

    pub fn is_vchar(c: u8) -> bool {
        // consult the ASCII definition
        0x21 <= c && c <= 0x7E
    }

    pub fn is_qdtext(c: u8) -> bool {
        // See https://tools.ietf.org/html/rfc7230#section-3.2.6
        b"\t \x21".contains(&c) || (0x23 <= c && c <= 0x5B) || (0x5D <= 0x7E) || is_obs_text(c)
    }

    pub fn is_quoting(c: u8) -> bool {
        b"\t ".contains(&c) || is_vchar(c) || is_obs_text(c)
    }

    impl<'a> Stream<'a> {
        pub fn new(data: &'a [u8]) -> Self {
            Stream(Cell::from(0), data)
        }

        pub fn inc(&self, i: usize) {
            let pos = self.pos();
            self.0.set(pos + i);
        }

        pub fn pos(&self) -> usize {
            self.0.get()
        }

        pub fn is_end(&self) -> bool {
            self.1.len() <= self.pos()
        }

        pub fn cur(&self) -> u8 {
            self.1[self.pos()]
        }

        pub fn skip_a(&self, c: u8) -> Result<()> {
            if self.cur() == c {
                self.inc(1);
                Ok(())
            } else {
                Err(Error::Header)
            }
        }
        pub fn skip_a_next(&self, c: u8) -> Result<()> {
            self.skip_ws()?;
            if self.is_end() {
                return Err(Error::Header);
            }
            self.skip_a(c)
        }

        pub fn take_while<F>(&self, f: F) -> Result<&[u8]>
        where
            F: Fn(u8) -> bool,
        {
            let start = self.pos();
            while !self.is_end() && f(self.cur()) {
                self.inc(1);
            }
            Ok(&self.1[start..self.pos()])
        }

        pub fn take_while1<F>(&self, f: F) -> Result<&[u8]>
        where
            F: Fn(u8) -> bool,
        {
            self.take_while(f).and_then(|b| {
                if b.len() < 1 {
                    Err(Error::Header)
                } else {
                    Ok(b)
                }
            })
        }

        pub fn try<F, T>(&self, f: F) -> Result<T>
        where
            F: FnOnce() -> Result<T>,
        {
            let init = self.pos();
            match f() {
                ok @ Ok(_) => ok,
                err @ Err(_) => {
                    self.0.set(init);
                    err
                }
            }
        }

        pub fn skip_ws(&self) -> Result<()> {
            self.take_while(is_ws).map(|_| ())
        }

        pub fn skip_next_comma(&self) -> Result<()> {
            self.skip_a_next(b',')
        }

        pub fn skip_field_sep(&self) -> Result<()> {
            self.skip_ws()?;
            if self.is_end() {
                return Ok(());
            }
            self.skip_next_comma()?;
            while self.skip_next_comma().is_ok() {}
            self.skip_ws()?;
            Ok(())
        }

        pub fn token(&self) -> Result<&str> {
            self.take_while1(is_token_char)
                .map(|s| unsafe { from_utf8_unchecked(s) })
        }

        pub fn next_token(&self) -> Result<&str> {
            self.skip_ws()?;
            self.token()
        }

        pub fn quoted_string(&self) -> Result<String> {
            // See https://tools.ietf.org/html/rfc7230#section-3.2.6
            if self.is_end() {
                return Err(Error::Header);
            }

            if self.cur() != b'"' {
                return Err(Error::Header);
            }
            self.inc(1);
            let mut s = Vec::new();
            while !self.is_end() && self.cur() != b'"' {
                if self.cur() == b'\\' {
                    self.inc(1);
                    if is_quoting(self.cur()) {
                        s.push(self.cur());
                        self.inc(1);
                    } else {
                        return Err(Error::Header);
                    }
                } else {
                    if is_qdtext(self.cur()) {
                        s.push(self.cur());
                        self.inc(1);
                    } else {
                        return Err(Error::Header);
                    }
                }
            }
            if self.is_end() {
                return Err(Error::Header);
            } else {
                debug_assert!(self.cur() == b'"');
                self.inc(1);
            }
            String::from_utf8(s).map_err(|_| Error::Header)
        }

        pub fn token68(&self) -> Result<&str> {
            let start = self.pos();
            // See https://tools.ietf.org/html/rfc7235#section-2.1
            self.take_while1(|c| {
                b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-._~+/".contains(&c)
            })?;
            self.take_while(|c| c == b'=')?;
            Ok(unsafe { from_utf8_unchecked(&self.1[start..self.pos()]) })
        }

        pub fn kv_token(&self) -> Result<(&str, &str)> {
            let k = self.token()?;
            self.skip_a_next(b'=')?;
            self.skip_ws()?;
            let v = self.token()?;
            Ok((k, v))
        }

        pub fn kv_quoted(&self) -> Result<(&str, String)> {
            let k = self.token()?;
            self.skip_a_next(b'=')?;
            self.skip_ws()?;
            let v = self.quoted_string()?;
            Ok((k, v))
        }

        pub fn field(&self) -> Result<(String, String)> {
            self.try(|| self.kv_token().map(|(k, v)| (k.to_string(), v.to_string())))
                .or_else(|_| self.kv_quoted().map(|(k, v)| (k.to_string(), v)))
        }

        pub fn raw_token68(&self) -> Result<RawChallenge> {
            let ret = self.token68()
                .map(ToString::to_string)
                .map(RawChallenge::Token68)?;
            self.skip_field_sep()?;
            Ok(ret)
        }

        pub fn raw_fields(&self) -> Result<RawChallenge> {
            let mut map = ChallengeFields::new();
            loop {
                match self.try(|| self.field()) {
                    Err(_) => return Ok(RawChallenge::Fields(map)),
                    Ok((k, v)) => {
                        if self.skip_field_sep().is_ok() {
                            if map.insert(k, v).is_some() {
                                // field key must not be duplicated
                                return Err(Error::Header);
                            }
                            if self.is_end() {
                                return Ok(RawChallenge::Fields(map));
                            }
                        } else {
                            return Err(Error::Header);
                        }
                    }
                }
            }
        }

        pub fn challenge(&self) -> Result<(String, RawChallenge)> {
            let scheme = self.next_token()?;
            self.take_while1(is_ws)?;
            let challenge = self.try(|| self.raw_token68())
                .or_else(|_| self.raw_fields())?;
            Ok((scheme.to_string(), challenge))
        }
    }

    #[test]
    fn test_parese_quoted_field() {
        let b = b"realm=\"secret zone\"";
        let stream = Stream::new(b);
        let (k, v) = stream.field().unwrap();
        assert_eq!(k, "realm");
        assert_eq!(v, "secret zone");
        assert!(stream.is_end());
    }

    #[test]
    fn test_parese_quoted_field_nonvchars() {
        let b = b"realm=\"secret zone\t\xe3\x8a\x99\"";
        let stream = Stream::new(b);
        let (k, v) = stream.field().unwrap();
        assert_eq!(k, "realm");
        assert_eq!(v, "secret zone\t㊙");
        assert!(stream.is_end());
    }

    #[test]
    fn test_parese_token_field() {
        let b = b"algorithm=MD5";
        let stream = Stream::new(b);
        let (k, v) = stream.field().unwrap();
        assert_eq!(k, "algorithm");
        assert_eq!(v, "MD5");
        assert!(stream.is_end());
    }

    #[test]
    fn test_parese_raw_quoted_fields() {
        let b = b"realm=\"secret zone\"";
        let stream = Stream::new(b);
        match stream.raw_fields().unwrap() {
            RawChallenge::Token68(_) => panic!(),
            RawChallenge::Fields(fields) => {
                assert_eq!(fields.len(), 1);
                assert_eq!(fields.get("realm").unwrap(), "secret zone");
            }
        }
        assert!(stream.is_end());
    }

    #[test]
    fn test_parese_raw_token_fields() {
        let b = b"algorithm=MD5";
        let stream = Stream::new(b);
        match stream.raw_fields().unwrap() {
            RawChallenge::Token68(_) => panic!(),
            RawChallenge::Fields(fields) => {
                assert_eq!(fields.len(), 1);
                assert_eq!(fields.get("algorithm").unwrap(), "MD5");
            }
        }
        assert!(stream.is_end());
    }
    #[test]
    fn test_parese_token68() {
        let b = b"auea1./+=";
        let stream = Stream::new(b);
        let token = stream.token68().unwrap();
        assert_eq!(token, "auea1./+=");
        assert!(stream.is_end());
    }

    #[test]
    fn test_parese_raw_token68() {
        let b = b"auea1./+=";
        let stream = Stream::new(b);
        match stream.raw_token68().unwrap() {
            RawChallenge::Token68(token) => assert_eq!(token, "auea1./+="),
            RawChallenge::Fields(_) => panic!(),
        }
        assert!(stream.is_end());
    }

    #[test]
    fn test_parese_challenge1() {
        let b = b"Token abceaqj13-.+=";
        let stream = Stream::new(b);
        match stream.challenge().unwrap() {
            (scheme, RawChallenge::Token68(token)) => {
                assert_eq!(scheme, "Token");
                assert_eq!(token, "abceaqj13-.+=");
            }
            (_, RawChallenge::Fields(_)) => panic!(),
        }
        assert!(stream.is_end());
    }

    #[test]
    fn test_parese_challenge2() {
        let b = b"Basic realm=\"secret zone\"";
        let stream = Stream::new(b);
        match stream.challenge().unwrap() {
            (_, RawChallenge::Token68(_)) => panic!(),
            (scheme, RawChallenge::Fields(fields)) => {
                assert_eq!(scheme, "Basic");
                assert_eq!(fields.len(), 1);
                assert_eq!(fields.get("realm").unwrap(), "secret zone");
            }
        }
        assert!(stream.is_end());
    }

    #[test]
    fn test_parese_challenge3() {
        let b = b"Bearer token=aeub8_";
        let stream = Stream::new(b);
        match stream.challenge().unwrap() {
            (_, RawChallenge::Token68(_)) => panic!(),
            (scheme, RawChallenge::Fields(fields)) => {
                assert_eq!(scheme, "Bearer");
                assert_eq!(fields.len(), 1);
                assert_eq!(fields.get("token").unwrap(), "aeub8_");
            }
        }
        assert!(stream.is_end());
    }

    #[test]
    fn test_parese_challenge4() {
        let b = b"Bearer token=aeub8_, user=\"fooo\"";
        let stream = Stream::new(b);
        match stream.challenge().unwrap() {
            (_, RawChallenge::Token68(_)) => panic!(),
            (scheme, RawChallenge::Fields(fields)) => {
                assert_eq!(scheme, "Bearer");
                assert_eq!(fields.len(), 2);
                assert_eq!(fields.get("token").unwrap(), "aeub8_");
                assert_eq!(fields.get("user").unwrap(), "fooo");
            }
        }
        assert!(stream.is_end());
    }

    #[test]
    fn test_parese_challenge5() {
        let b = b"Bearer user=\"fooo\",,, token=aeub8_,,";
        let stream = Stream::new(b);
        match stream.challenge().unwrap() {
            (_, RawChallenge::Token68(_)) => panic!(),
            (scheme, RawChallenge::Fields(fields)) => {
                assert_eq!(scheme, "Bearer");
                assert_eq!(fields.len(), 2);
                assert_eq!(fields.get("token").unwrap(), "aeub8_");
                assert_eq!(fields.get("user").unwrap(), "fooo");
            }
        }
        assert!(stream.is_end());
    }

    #[test]
    #[should_panic]
    fn test_parse_null() {
        let b = b"";
        let stream = Stream::new(b);
        println!("{:?}", stream.challenge().unwrap());
    }
}