aboutsummaryrefslogtreecommitdiffstats
path: root/components/net/http_loader.rs
blob: 41fb9027945ef4aa99a4a4df854036fc31a75b7c (plain) (blame)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */


use brotli::Decompressor;
use connector::Connector;
use cookie;
use cookie_storage::CookieStorage;
use devtools_traits::{ChromeToDevtoolsControlMsg, DevtoolsControlMsg, HttpRequest as DevtoolsHttpRequest};
use devtools_traits::{HttpResponse as DevtoolsHttpResponse, NetworkEvent};
use flate2::read::{DeflateDecoder, GzDecoder};
use hsts::{HstsEntry, HstsList, secure_url};
use hyper::Error as HttpError;
use hyper::client::{Pool, Request, Response};
use hyper::header::{Accept, AcceptEncoding, ContentLength, ContentType, Host, Referer};
use hyper::header::{Authorization, Basic};
use hyper::header::{ContentEncoding, Encoding, Header, Headers, Quality, QualityItem};
use hyper::header::{Location, SetCookie, StrictTransportSecurity, UserAgent, qitem};
use hyper::http::RawStatus;
use hyper::method::Method;
use hyper::mime::{Mime, SubLevel, TopLevel};
use hyper::net::Fresh;
use hyper::status::{StatusClass, StatusCode};
use log;
use mime_classifier::MIMEClassifier;
use msg::constellation_msg::{PipelineId, ReferrerPolicy};
use net_traits::ProgressMsg::{Done, Payload};
use net_traits::hosts::replace_hosts;
use net_traits::response::HttpsState;
use net_traits::{CookieSource, IncludeSubdomains, LoadConsumer, LoadContext, LoadData};
use net_traits::{Metadata, NetworkError};
use openssl::ssl::error::{SslError, OpensslError};
use resource_thread::{CancellationListener, send_error, start_sending_sniffed_opt, AuthCache, AuthCacheEntry};
use std::borrow::ToOwned;
use std::boxed::FnBox;
use std::collections::HashSet;
use std::error::Error;
use std::fmt;
use std::io::{self, Read, Write};
use std::sync::mpsc::Sender;
use std::sync::{Arc, RwLock};
use time;
use time::Tm;
#[cfg(any(target_os = "macos", target_os = "linux"))]
use tinyfiledialogs;
use url::{Url, Position};
use util::prefs;
use util::thread::spawn_named;
use uuid;

pub fn factory(user_agent: String,
               http_state: HttpState,
               devtools_chan: Option<Sender<DevtoolsControlMsg>>,
               connector: Arc<Pool<Connector>>)
               -> Box<FnBox(LoadData,
                            LoadConsumer,
                            Arc<MIMEClassifier>,
                            CancellationListener) + Send> {
    box move |load_data: LoadData, senders, classifier, cancel_listener| {
        spawn_named(format!("http_loader for {}", load_data.url), move || {
            load_for_consumer(load_data,
                              senders,
                              classifier,
                              connector,
                              http_state,
                              devtools_chan,
                              cancel_listener,
                              user_agent)
        })
    }
}

pub enum ReadResult {
    Payload(Vec<u8>),
    EOF,
}

pub fn read_block<R: Read>(reader: &mut R) -> Result<ReadResult, ()> {
    let mut buf = vec![0; 1024];

    match reader.read(&mut buf) {
        Ok(len) if len > 0 => {
            buf.truncate(len);
            Ok(ReadResult::Payload(buf))
        }
        Ok(_) => Ok(ReadResult::EOF),
        Err(_) => Err(()),
    }
}

pub struct HttpState {
    pub hsts_list: Arc<RwLock<HstsList>>,
    pub cookie_jar: Arc<RwLock<CookieStorage>>,
    pub auth_cache: Arc<RwLock<AuthCache>>,
}

impl HttpState {
    pub fn new() -> HttpState {
        HttpState {
            hsts_list: Arc::new(RwLock::new(HstsList::new())),
            cookie_jar: Arc::new(RwLock::new(CookieStorage::new())),
            auth_cache: Arc::new(RwLock::new(AuthCache::new())),
        }
    }
}

fn load_for_consumer(load_data: LoadData,
                     start_chan: LoadConsumer,
                     classifier: Arc<MIMEClassifier>,
                     connector: Arc<Pool<Connector>>,
                     http_state: HttpState,
                     devtools_chan: Option<Sender<DevtoolsControlMsg>>,
                     cancel_listener: CancellationListener,
                     user_agent: String) {

    let factory = NetworkHttpRequestFactory {
        connector: connector,
    };

    let ui_provider = TFDProvider;
    match load(&load_data, &ui_provider, &http_state,
               devtools_chan, &factory,
               user_agent, &cancel_listener) {
        Err(error) => {
            match error.error {
                LoadErrorType::ConnectionAborted { .. } => unreachable!(),
                LoadErrorType::Ssl { .. } => send_error(error.url.clone(),
                                                        NetworkError::SslValidation(error.url),
                                                        start_chan),
                LoadErrorType::Cancelled => send_error(error.url, NetworkError::LoadCancelled, start_chan),
                _ => send_error(error.url, NetworkError::Internal(error.error.description().to_owned()), start_chan)
            }
        }
        Ok(mut load_response) => {
            let metadata = load_response.metadata.clone();
            send_data(load_data.context, &mut load_response, start_chan, metadata, classifier, &cancel_listener)
        }
    }
}

pub trait HttpResponse: Read {
    fn headers(&self) -> &Headers;
    fn status(&self) -> StatusCode;
    fn status_raw(&self) -> &RawStatus;
    fn http_version(&self) -> String {
        "HTTP/1.1".to_owned()
    }
    fn content_encoding(&self) -> Option<Encoding> {
        let encodings = match self.headers().get::<ContentEncoding>() {
            Some(&ContentEncoding(ref encodings)) => encodings,
            None => return None,
        };
        if encodings.contains(&Encoding::Gzip) {
            Some(Encoding::Gzip)
        } else if encodings.contains(&Encoding::Deflate) {
            Some(Encoding::Deflate)
        } else if encodings.contains(&Encoding::EncodingExt("br".to_owned())) {
            Some(Encoding::EncodingExt("br".to_owned()))
        } else {
            None
        }
    }
}


pub struct WrappedHttpResponse {
    pub response: Response
}

impl Read for WrappedHttpResponse {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.response.read(buf)
    }
}



impl HttpResponse for WrappedHttpResponse {
    fn headers(&self) -> &Headers {
        &self.response.headers
    }

    fn status(&self) -> StatusCode {
        self.response.status
    }

    fn status_raw(&self) -> &RawStatus {
        self.response.status_raw()
    }

    fn http_version(&self) -> String {
        self.response.version.to_string()
    }
}

pub trait HttpRequestFactory {
    type R: HttpRequest;

    fn create(&self, url: Url, method: Method, headers: Headers) -> Result<Self::R, LoadError>;
}

pub struct NetworkHttpRequestFactory {
    pub connector: Arc<Pool<Connector>>,
}

impl HttpRequestFactory for NetworkHttpRequestFactory {
    type R = WrappedHttpRequest;

    fn create(&self, url: Url, method: Method, headers: Headers)
              -> Result<WrappedHttpRequest, LoadError> {
        let connection = Request::with_connector(method, url.clone(), &*self.connector);

        if let Err(HttpError::Ssl(ref error)) = connection {
            let error: &(Error + Send + 'static) = &**error;
            if let Some(&SslError::OpenSslErrors(ref errors)) = error.downcast_ref::<SslError>() {
                if errors.iter().any(is_cert_verify_error) {
                    let msg = format!("ssl error: {:?} {:?}", error.description(), error.cause());
                    return Err(LoadError::new(url, LoadErrorType::Ssl { reason: msg }));
                }
            }
        }

        let mut request = match connection {
            Ok(req) => req,
            Err(e) => return Err(
                LoadError::new(url, LoadErrorType::Connection { reason: e.description().to_owned() })),
        };
        *request.headers_mut() = headers;

        Ok(WrappedHttpRequest { request: request })
    }
}

pub trait HttpRequest {
    type R: HttpResponse + 'static;

    fn send(self, body: &Option<Vec<u8>>) -> Result<Self::R, LoadError>;
}

pub struct WrappedHttpRequest {
    request: Request<Fresh>
}

impl HttpRequest for WrappedHttpRequest {
    type R = WrappedHttpResponse;

    fn send(self, body: &Option<Vec<u8>>) -> Result<WrappedHttpResponse, LoadError> {
        let url = self.request.url.clone();
        let mut request_writer = match self.request.start() {
            Ok(streaming) => streaming,
            Err(e) => return Err(LoadError::new(url, LoadErrorType::Connection { reason: e.description().to_owned() })),
        };

        if let Some(ref data) = *body {
            if let Err(e) = request_writer.write_all(&data) {
                return Err(LoadError::new(url, LoadErrorType::Connection { reason: e.description().to_owned() }))
            }
        }

        let response = match request_writer.send() {
            Ok(w) => w,
            Err(HttpError::Io(ref io_error)) if io_error.kind() == io::ErrorKind::ConnectionAborted => {
                let error_type = LoadErrorType::ConnectionAborted { reason: io_error.description().to_owned() };
                return Err(LoadError::new(url, error_type));
            },
            Err(e) => return Err(LoadError::new(url, LoadErrorType::Connection { reason: e.description().to_owned() })),
        };

        Ok(WrappedHttpResponse { response: response })
    }
}

#[derive(Debug)]
pub struct LoadError {
    pub url: Url,
    pub error: LoadErrorType,
}

impl LoadError {
    pub fn new(url: Url, error: LoadErrorType) -> LoadError {
        LoadError {
            url: url,
            error: error,
        }
    }
}

#[derive(Eq, PartialEq, Debug)]
pub enum LoadErrorType {
    Cancelled,
    Connection { reason: String },
    ConnectionAborted { reason: String },
    // Preflight fetch inconsistent with main fetch
    CorsPreflightFetchInconsistent,
    Decoding { reason: String },
    InvalidRedirect { reason: String },
    MaxRedirects(u32), // u32 indicates number of redirects that occurred
    RedirectLoop,
    Ssl { reason: String },
    UnsupportedScheme { scheme: String },
}

impl fmt::Display for LoadErrorType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl Error for LoadErrorType {
    fn description(&self) -> &str {
        match *self {
            LoadErrorType::Cancelled => "load cancelled",
            LoadErrorType::Connection { ref reason } => reason,
            LoadErrorType::ConnectionAborted { ref reason } => reason,
            LoadErrorType::CorsPreflightFetchInconsistent => "preflight fetch inconsistent with main fetch",
            LoadErrorType::Decoding { ref reason } => reason,
            LoadErrorType::InvalidRedirect { ref reason } => reason,
            LoadErrorType::MaxRedirects(_) => "too many redirects",
            LoadErrorType::RedirectLoop => "redirect loop",
            LoadErrorType::Ssl { ref reason } => reason,
            LoadErrorType::UnsupportedScheme { .. } => "unsupported url scheme",
        }
    }
}

fn set_default_accept_encoding(headers: &mut Headers) {
    if headers.has::<AcceptEncoding>() {
        return
    }

    headers.set(AcceptEncoding(vec![
        qitem(Encoding::Gzip),
        qitem(Encoding::Deflate),
        qitem(Encoding::EncodingExt("br".to_owned()))
    ]));
}

fn set_default_accept(headers: &mut Headers) {
    if !headers.has::<Accept>() {
        let accept = Accept(vec![
                            qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])),
                            qitem(Mime(TopLevel::Application, SubLevel::Ext("xhtml+xml".to_owned()), vec![])),
                            QualityItem::new(Mime(TopLevel::Application, SubLevel::Xml, vec![]), Quality(900u16)),
                            QualityItem::new(Mime(TopLevel::Star, SubLevel::Star, vec![]), Quality(800u16)),
                            ]);
        headers.set(accept);
    }
}

/// https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-state-no-referrer-when-downgrade
fn no_ref_when_downgrade_header(referrer_url: Url, url: Url) -> Option<Url> {
    if referrer_url.scheme() == "https" && url.scheme() != "https" {
        return None;
    }
    return strip_url(referrer_url, false);
}

/// https://w3c.github.io/webappsec-referrer-policy/#strip-url
fn strip_url(mut referrer_url: Url, origin_only: bool) -> Option<Url> {
    if referrer_url.scheme() == "https" || referrer_url.scheme() == "http" {
        referrer_url.set_username("").unwrap();
        referrer_url.set_password(None).unwrap();
        referrer_url.set_fragment(None);
        if origin_only {
            referrer_url.set_path("");
            referrer_url.set_query(None);
        }
        return Some(referrer_url);
    }
    return None;
}

/// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
fn determine_request_referrer(headers: &mut Headers,
                              referrer_policy: Option<ReferrerPolicy>,
                              referrer_url: Option<Url>,
                              url: Url) -> Option<Url> {
    //TODO - algorithm step 2 not addressed
    assert!(!headers.has::<Referer>());
    if let Some(ref_url) = referrer_url {
        let cross_origin = ref_url.origin() != url.origin();
        return match referrer_policy {
            Some(ReferrerPolicy::NoReferrer) => None,
            Some(ReferrerPolicy::OriginOnly) => strip_url(ref_url, true),
            Some(ReferrerPolicy::UnsafeUrl) => strip_url(ref_url, false),
            Some(ReferrerPolicy::OriginWhenCrossOrigin) => strip_url(ref_url, cross_origin),
            Some(ReferrerPolicy::NoRefWhenDowngrade) | None => no_ref_when_downgrade_header(ref_url, url),
        };
    }
    return None;
}

pub fn set_request_cookies(url: Url, headers: &mut Headers, cookie_jar: &Arc<RwLock<CookieStorage>>) {
    let mut cookie_jar = cookie_jar.write().unwrap();
    if let Some(cookie_list) = cookie_jar.cookies_for_url(&url, CookieSource::HTTP) {
        let mut v = Vec::new();
        v.push(cookie_list.into_bytes());
        headers.set_raw("Cookie".to_owned(), v);
    }
}

fn set_cookie_for_url(cookie_jar: &Arc<RwLock<CookieStorage>>,
                      request: Url,
                      cookie_val: String) {
    let mut cookie_jar = cookie_jar.write().unwrap();
    let source = CookieSource::HTTP;
    let header = Header::parse_header(&[cookie_val.into_bytes()]);

    if let Ok(SetCookie(cookies)) = header {
        for bare_cookie in cookies {
            if let Some(cookie) = cookie::Cookie::new_wrapped(bare_cookie, &request, source) {
                cookie_jar.push(cookie, source);
            }
        }
    }
}

fn set_cookies_from_response(url: Url, response: &HttpResponse, cookie_jar: &Arc<RwLock<CookieStorage>>) {
    if let Some(cookies) = response.headers().get_raw("set-cookie") {
        for cookie in cookies.iter() {
            if let Ok(cookie_value) = String::from_utf8(cookie.clone()) {
                set_cookie_for_url(&cookie_jar,
                                   url.clone(),
                                   cookie_value);
            }
        }
    }
}

fn update_sts_list_from_response(url: &Url, response: &HttpResponse, hsts_list: &Arc<RwLock<HstsList>>) {
    if url.scheme() != "https" {
        return;
    }

    if let Some(header) = response.headers().get::<StrictTransportSecurity>() {
        if let Some(host) = url.domain() {
            let mut hsts_list = hsts_list.write().unwrap();
            let include_subdomains = if header.include_subdomains {
                IncludeSubdomains::Included
            } else {
                IncludeSubdomains::NotIncluded
            };

            if let Some(entry) = HstsEntry::new(host.to_owned(), include_subdomains, Some(header.max_age)) {
                info!("adding host {} to the strict transport security list", host);
                info!("- max-age {}", header.max_age);
                if header.include_subdomains {
                    info!("- includeSubdomains");
                }

                hsts_list.push(entry);
            }
        }
    }
}

pub struct StreamedResponse<R: HttpResponse> {
    decoder: Decoder<R>,
    pub metadata: Metadata
}


impl<R: HttpResponse> Read for StreamedResponse<R> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self.decoder {
            Decoder::Gzip(ref mut d) => d.read(buf),
            Decoder::Deflate(ref mut d) => d.read(buf),
            Decoder::Brotli(ref mut d) => d.read(buf),
            Decoder::Plain(ref mut d) => d.read(buf)
        }
    }
}

impl<R: HttpResponse> StreamedResponse<R> {
    fn new(m: Metadata, d: Decoder<R>) -> StreamedResponse<R> {
        StreamedResponse { metadata: m, decoder: d }
    }

    fn from_http_response(response: R, m: Metadata) -> Result<StreamedResponse<R>, LoadError> {
        let decoder = match response.content_encoding() {
            Some(Encoding::Gzip) => {
                let result = GzDecoder::new(response);
                match result {
                    Ok(response_decoding) => Decoder::Gzip(response_decoding),
                    Err(err) => {
                        return Err(
                            LoadError::new(m.final_url, LoadErrorType::Decoding { reason: err.to_string() }))
                    }
                }
            }
            Some(Encoding::Deflate) => {
                Decoder::Deflate(DeflateDecoder::new(response))
            }
            Some(Encoding::EncodingExt(ref ext)) if ext == "br" => {
                Decoder::Brotli(Decompressor::new(response))
            }
            _ => {
                Decoder::Plain(response)
            }
        };
        Ok(StreamedResponse::new(m, decoder))
    }
}

enum Decoder<R: Read> {
    Gzip(GzDecoder<R>),
    Deflate(DeflateDecoder<R>),
    Brotli(Decompressor<R>),
    Plain(R)
}

fn send_request_to_devtools(devtools_chan: Option<Sender<DevtoolsControlMsg>>,
                            request_id: String,
                            url: Url,
                            method: Method,
                            headers: Headers,
                            body: Option<Vec<u8>>,
                            pipeline_id: PipelineId, now: Tm) {

    if let Some(ref chan) = devtools_chan {
        let request = DevtoolsHttpRequest {
            url: url, method: method, headers: headers, body: body, pipeline_id: pipeline_id, startedDateTime: now };
        let net_event = NetworkEvent::HttpRequest(request);

        let msg = ChromeToDevtoolsControlMsg::NetworkEvent(request_id, net_event);
        chan.send(DevtoolsControlMsg::FromChrome(msg)).unwrap();
    }
}

fn send_response_to_devtools(devtools_chan: Option<Sender<DevtoolsControlMsg>>,
                             request_id: String,
                             headers: Option<Headers>,
                             status: Option<RawStatus>,
                             pipeline_id: PipelineId) {
    if let Some(ref chan) = devtools_chan {
        let response = DevtoolsHttpResponse { headers: headers, status: status, body: None, pipeline_id: pipeline_id };
        let net_event_response = NetworkEvent::HttpResponse(response);

        let msg = ChromeToDevtoolsControlMsg::NetworkEvent(request_id, net_event_response);
        chan.send(DevtoolsControlMsg::FromChrome(msg)).unwrap();
    }
}

fn request_must_be_secured(url: &Url, hsts_list: &Arc<RwLock<HstsList>>) -> bool {
    match url.domain() {
        Some(domain) => hsts_list.read().unwrap().is_host_secure(domain),
        None => false
    }
}

pub fn modify_request_headers(headers: &mut Headers,
                              url: &Url,
                              user_agent: &str,
                              cookie_jar: &Arc<RwLock<CookieStorage>>,
                              auth_cache: &Arc<RwLock<AuthCache>>,
                              load_data: &LoadData) {
    // Ensure that the host header is set from the original url
    let host = Host {
        hostname: url.host_str().unwrap().to_owned(),
        port: url.port_or_known_default()
    };
    headers.set(host);

    // If the user-agent has not already been set, then use the
    // browser's default user-agent or the user-agent override
    // from the command line. If the user-agent is set, don't
    // modify it, as setting of the user-agent by the user is
    // allowed.
    // https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch step 8
    if !headers.has::<UserAgent>() {
        headers.set(UserAgent(user_agent.to_owned()));
    }

    set_default_accept(headers);
    set_default_accept_encoding(headers);

    if let Some(referer_val) = determine_request_referrer(headers,
                                                          load_data.referrer_policy.clone(),
                                                          load_data.referrer_url.clone(),
                                                          url.clone()) {
        headers.set(Referer(referer_val.into_string()));
    }

    // https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch step 11
    if load_data.credentials_flag {
        set_request_cookies(url.clone(), headers, cookie_jar);

        // https://fetch.spec.whatwg.org/#http-network-or-cache-fetch step 12
        set_auth_header(headers, url, auth_cache);
    }
}

fn set_auth_header(headers: &mut Headers,
                   url: &Url,
                   auth_cache: &Arc<RwLock<AuthCache>>) {

    if !headers.has::<Authorization<Basic>>() {
        if let Some(auth) = auth_from_url(url) {
            headers.set(auth);
        } else {
            if let Some(ref auth_entry) = auth_cache.read().unwrap().entries.get(url) {
                auth_from_entry(&auth_entry, headers);
            }
        }
    }
}

fn auth_from_entry(auth_entry: &AuthCacheEntry, headers: &mut Headers) {
    let user_name = auth_entry.user_name.clone();
    let password  = Some(auth_entry.password.clone());

    headers.set(Authorization(Basic { username: user_name, password: password }));
}

fn auth_from_url(doc_url: &Url) -> Option<Authorization<Basic>> {
    let username = doc_url.username();
    if username != "" {
        Some(Authorization(Basic {
            username: username.to_owned(),
            password: Some(doc_url.password().unwrap_or("").to_owned())
        }))
    } else {
        None
    }
}

pub fn process_response_headers(response: &HttpResponse,
                                url: &Url,
                                cookie_jar: &Arc<RwLock<CookieStorage>>,
                                hsts_list: &Arc<RwLock<HstsList>>,
                                load_data: &LoadData) {
    info!("got HTTP response {}, headers:", response.status());
    if log_enabled!(log::LogLevel::Info) {
        for header in response.headers().iter() {
            info!(" - {}", header);
        }
    }

    // https://fetch.spec.whatwg.org/#concept-http-network-fetch step 9
    if load_data.credentials_flag {
        set_cookies_from_response(url.clone(), response, cookie_jar);
    }
    update_sts_list_from_response(url, response, hsts_list);
}

pub fn obtain_response<A>(request_factory: &HttpRequestFactory<R=A>,
                          url: &Url,
                          method: &Method,
                          request_headers: &Headers,
                          cancel_listener: &CancellationListener,
                          data: &Option<Vec<u8>>,
                          load_data_method: &Method,
                          pipeline_id: &Option<PipelineId>,
                          iters: u32,
                          devtools_chan: &Option<Sender<DevtoolsControlMsg>>,
                          request_id: &str)
                          -> Result<A::R, LoadError> where A: HttpRequest + 'static  {

    let null_data = None;
    let response;
    let connection_url = replace_hosts(&url);

    // loop trying connections in connection pool
    // they may have grown stale (disconnected), in which case we'll get
    // a ConnectionAborted error. this loop tries again with a new
    // connection.
    loop {
        let mut headers = request_headers.clone();

        // Avoid automatically sending request body if a redirect has occurred.
        //
        // TODO - This is the wrong behaviour according to the RFC. However, I'm not
        // sure how much "correctness" vs. real-world is important in this case.
        //
        // https://tools.ietf.org/html/rfc7231#section-6.4
        let is_redirected_request = iters != 1;
        let request_body;
        match data {
            &Some(ref d) if !is_redirected_request => {
                headers.set(ContentLength(d.len() as u64));
                request_body = data;
            }
            _ => {
                if *load_data_method != Method::Get && *load_data_method != Method::Head {
                    headers.set(ContentLength(0))
                }
                request_body = &null_data;
            }
        }

        if log_enabled!(log::LogLevel::Info) {
            info!("{}", method);
            for header in headers.iter() {
                info!(" - {}", header);
            }
            info!("{:?}", data);
        }

        let req = try!(request_factory.create(connection_url.clone(), method.clone(),
                                              headers.clone()));

        if cancel_listener.is_cancelled() {
            return Err(LoadError::new(connection_url.clone(), LoadErrorType::Cancelled));
        }

        let maybe_response = req.send(request_body);

        if let Some(pipeline_id) = *pipeline_id {
            send_request_to_devtools(
                devtools_chan.clone(), request_id.clone().into(),
                url.clone(), method.clone(), headers,
                request_body.clone(), pipeline_id, time::now()
            );
        }

        response = match maybe_response {
            Ok(r) => r,
            Err(e) => {
                if let LoadErrorType::ConnectionAborted { reason } = e.error {
                    debug!("connection aborted ({:?}), possibly stale, trying new connection", reason);
                    continue;
                } else {
                    return Err(e)
                }
            },
        };

        // if no ConnectionAborted, break the loop
        break;
    }

    Ok(response)
}

pub trait UIProvider {
    fn input_username_and_password(&self, prompt: &str) -> (Option<String>, Option<String>);
}

impl UIProvider for TFDProvider {
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    fn input_username_and_password(&self, prompt: &str) -> (Option<String>, Option<String>) {
        (tinyfiledialogs::input_box(prompt, "Username:", ""),
        tinyfiledialogs::input_box(prompt, "Password:", ""))
    }

    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    fn input_username_and_password(&self, _prompt: &str) -> (Option<String>, Option<String>) {
        (None, None)
    }
}

struct TFDProvider;

pub fn load<A, B>(load_data: &LoadData,
                  ui_provider: &B,
                  http_state: &HttpState,
                  devtools_chan: Option<Sender<DevtoolsControlMsg>>,
                  request_factory: &HttpRequestFactory<R=A>,
                  user_agent: String,
                  cancel_listener: &CancellationListener)
                  -> Result<StreamedResponse<A::R>, LoadError> where A: HttpRequest + 'static, B: UIProvider {
    let max_redirects = prefs::get_pref("network.http.redirection-limit").as_i64().unwrap() as u32;
    let mut iters = 0;
    // URL of the document being loaded, as seen by all the higher-level code.
    let mut doc_url = load_data.url.clone();
    let mut redirected_to = HashSet::new();
    let mut method = load_data.method.clone();

    let mut new_auth_header: Option<Authorization<Basic>> = None;

    if cancel_listener.is_cancelled() {
        return Err(LoadError::new(doc_url, LoadErrorType::Cancelled));
    }

    // If the URL is a view-source scheme then the scheme data contains the
    // real URL that should be used for which the source is to be viewed.
    // Change our existing URL to that and keep note that we are viewing
    // the source rather than rendering the contents of the URL.
    let viewing_source = doc_url.scheme() == "view-source";
    if viewing_source {
        doc_url = Url::parse(&load_data.url[Position::BeforeUsername..]).unwrap();
    }

    // Loop to handle redirects.
    loop {
        iters = iters + 1;

        if doc_url.scheme() == "http" && request_must_be_secured(&doc_url, &http_state.hsts_list) {
            info!("{} is in the strict transport security list, requesting secure host", doc_url);
            doc_url = secure_url(&doc_url);
        }

        if iters > max_redirects {
            return Err(LoadError::new(doc_url, LoadErrorType::MaxRedirects(iters - 1)));
        }

        if !matches!(doc_url.scheme(), "http" | "https") {
            let scheme = doc_url.scheme().to_owned();
            return Err(LoadError::new(doc_url, LoadErrorType::UnsupportedScheme { scheme: scheme }));
        }

        if cancel_listener.is_cancelled() {
            return Err(LoadError::new(doc_url, LoadErrorType::Cancelled));
        }

        info!("requesting {}", doc_url);

        // Avoid automatically preserving request headers when redirects occur.
        // See https://bugzilla.mozilla.org/show_bug.cgi?id=401564 and
        // https://bugzilla.mozilla.org/show_bug.cgi?id=216828 .
        // Only preserve ones which have been explicitly marked as such.
        let mut request_headers = if iters == 1 {
            let mut combined_headers = load_data.headers.clone();
            combined_headers.extend(load_data.preserved_headers.iter());
            combined_headers
        } else {
            load_data.preserved_headers.clone()
        };

        let request_id = uuid::Uuid::new_v4().simple().to_string();

        modify_request_headers(&mut request_headers, &doc_url,
                               &user_agent, &http_state.cookie_jar,
                               &http_state.auth_cache, &load_data);

        //if there is a new auth header then set the request headers with it
        if let Some(ref auth_header) = new_auth_header {
            request_headers.set(auth_header.clone());
        }

        let response = try!(obtain_response(request_factory, &doc_url, &method, &request_headers,
                                            &cancel_listener, &load_data.data, &load_data.method,
                                            &load_data.pipeline_id, iters, &devtools_chan, &request_id));

        process_response_headers(&response, &doc_url, &http_state.cookie_jar, &http_state.hsts_list, &load_data);

        //if response status is unauthorized then prompt user for username and password
        if response.status() == StatusCode::Unauthorized &&
           response.headers().get_raw("WWW-Authenticate").is_some() {
            let (username_option, password_option) =
                ui_provider.input_username_and_password(doc_url.as_str());

            match username_option {
                Some(name) => {
                    new_auth_header =  Some(Authorization(Basic { username: name, password: password_option }));
                    continue;
                },
                None => {},
            }
        }

        new_auth_header = None;

        if let Some(auth_header) = request_headers.get::<Authorization<Basic>>() {
            if response.status().class() == StatusClass::Success {
                let auth_entry = AuthCacheEntry {
                    user_name: auth_header.username.to_owned(),
                    password: auth_header.password.to_owned().unwrap(),
                };

                http_state.auth_cache.write().unwrap().entries.insert(doc_url.clone(), auth_entry);
            }
        }

        // --- Loop if there's a redirect
        if response.status().class() == StatusClass::Redirection {
            if let Some(&Location(ref new_url)) = response.headers().get::<Location>() {
                // CORS (https://fetch.spec.whatwg.org/#http-fetch, status section, point 9, 10)
                if let Some(ref c) = load_data.cors {
                    if c.preflight {
                        return Err(LoadError::new(doc_url, LoadErrorType::CorsPreflightFetchInconsistent));
                    } else {
                        // XXXManishearth There are some CORS-related steps here,
                        // but they don't seem necessary until credentials are implemented
                    }
                }

                let new_doc_url = match doc_url.join(&new_url) {
                    Ok(u) => u,
                    Err(e) => return Err(
                        LoadError::new(doc_url, LoadErrorType::InvalidRedirect { reason: e.to_string() })),
                };

                // According to https://tools.ietf.org/html/rfc7231#section-6.4.2,
                // historically UAs have rewritten POST->GET on 301 and 302 responses.
                if method == Method::Post &&
                    (response.status() == StatusCode::MovedPermanently ||
                        response.status() == StatusCode::Found) {
                    method = Method::Get;
                }

                if redirected_to.contains(&new_doc_url) {
                    return Err(LoadError::new(doc_url, LoadErrorType::RedirectLoop));
                }

                info!("redirecting to {}", new_doc_url);
                doc_url = new_doc_url;

                redirected_to.insert(doc_url.clone());
                continue;
            }
        }

        let mut adjusted_headers = response.headers().clone();

        if viewing_source {
            adjusted_headers.set(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec![])));
        }

        let mut metadata: Metadata = Metadata::default(doc_url.clone());
        metadata.set_content_type(match adjusted_headers.get() {
            Some(&ContentType(ref mime)) => Some(mime),
            None => None
        });
        metadata.headers = Some(adjusted_headers);
        metadata.status = Some(response.status_raw().clone());
        metadata.https_state = if doc_url.scheme() == "https" {
            HttpsState::Modern
        } else {
            HttpsState::None
        };

        // --- Tell devtools that we got a response
        // Send an HttpResponse message to devtools with the corresponding request_id
        // TODO: Send this message even when the load fails?
        if let Some(pipeline_id) = load_data.pipeline_id {
                send_response_to_devtools(
                    devtools_chan, request_id,
                    metadata.headers.clone(), metadata.status.clone(),
                    pipeline_id);
         }
        return StreamedResponse::from_http_response(response, metadata)
    }
}

fn send_data<R: Read>(context: LoadContext,
                      reader: &mut R,
                      start_chan: LoadConsumer,
                      metadata: Metadata,
                      classifier: Arc<MIMEClassifier>,
                      cancel_listener: &CancellationListener) {
    let (progress_chan, mut chunk) = {
        let buf = match read_block(reader) {
            Ok(ReadResult::Payload(buf)) => buf,
            _ => vec!(),
        };
        let p = match start_sending_sniffed_opt(start_chan, metadata, classifier, &buf, context) {
            Ok(p) => p,
            _ => return
        };
        (p, buf)
    };

    loop {
        if cancel_listener.is_cancelled() {
            let _ = progress_chan.send(Done(Err(NetworkError::LoadCancelled)));
            return;
        }

        if progress_chan.send(Payload(chunk)).is_err() {
            // The send errors when the receiver is out of scope,
            // which will happen if the fetch has timed out (or has been aborted)
            // so we don't need to continue with the loading of the file here.
            return;
        }

        chunk = match read_block(reader) {
            Ok(ReadResult::Payload(buf)) => buf,
            Ok(ReadResult::EOF) | Err(_) => break,
        };
    }

    let _ = progress_chan.send(Done(Ok(())));
}

// FIXME: This incredibly hacky. Make it more robust, and at least test it.
fn is_cert_verify_error(error: &OpensslError) -> bool {
    match error {
        &OpensslError::UnknownError { ref library, ref function, ref reason } => {
            library == "SSL routines" &&
            function == "SSL3_GET_SERVER_CERTIFICATE" &&
            reason == "certificate verify failed"
        }
    }
}