forked from servo/servo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_loader.rs
2197 lines (1946 loc) · 74.4 KB
/
http_loader.rs
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
/* 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 https://mozilla.org/MPL/2.0/. */
use core::convert::Infallible;
use std::collections::{HashMap, HashSet};
use std::iter::FromIterator;
use std::sync::{Arc as StdArc, Condvar, Mutex, RwLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use async_recursion::async_recursion;
use crossbeam_channel::Sender;
use devtools_traits::{
ChromeToDevtoolsControlMsg, DevtoolsControlMsg, HttpRequest as DevtoolsHttpRequest,
HttpResponse as DevtoolsHttpResponse, NetworkEvent,
};
use futures::{future, StreamExt, TryFutureExt, TryStreamExt};
use headers::authorization::Basic;
use headers::{
AccessControlAllowCredentials, AccessControlAllowHeaders, AccessControlAllowMethods,
AccessControlAllowOrigin, AccessControlMaxAge, AccessControlRequestHeaders,
AccessControlRequestMethod, Authorization, CacheControl, ContentLength, HeaderMapExt,
IfModifiedSince, LastModified, Origin as HyperOrigin, Pragma, Referer, UserAgent,
};
use http::header::{
self, HeaderValue, ACCEPT, CONTENT_ENCODING, CONTENT_LANGUAGE, CONTENT_LOCATION, CONTENT_TYPE,
};
use http::{HeaderMap, Method, Request as HyperRequest, StatusCode};
use hyper::header::{HeaderName, TRANSFER_ENCODING};
use hyper::{Body, Client, Response as HyperResponse};
use hyper_serde::Serde;
use ipc_channel::ipc::{self, IpcSender};
use ipc_channel::router::ROUTER;
use lazy_static::lazy_static;
use log::{debug, error, info, log_enabled, warn};
use msg::constellation_msg::{HistoryStateId, PipelineId};
use net_traits::pub_domains::reg_suffix;
use net_traits::quality::{quality_to_value, Quality, QualityItem};
use net_traits::request::Origin::Origin as SpecificOrigin;
use net_traits::request::{
get_cors_unsafe_header_names, is_cors_non_wildcard_request_header_name,
is_cors_safelisted_method, is_cors_safelisted_request_header, BodyChunkRequest,
BodyChunkResponse, CacheMode, CredentialsMode, Destination, Origin, RedirectMode, Referrer,
Request, RequestBuilder, RequestMode, ResponseTainting, ServiceWorkersMode,
};
use net_traits::response::{HttpsState, Response, ResponseBody, ResponseType};
use net_traits::{
CookieSource, FetchMetadata, NetworkError, RedirectEndValue, RedirectStartValue,
ReferrerPolicy, ResourceAttribute, ResourceFetchTiming, ResourceTimeValue,
};
use servo_arc::Arc;
use servo_url::{ImmutableOrigin, ServoUrl};
use tokio::runtime::Runtime;
use tokio::sync::mpsc::{
channel, unbounded_channel, Receiver as TokioReceiver, Sender as TokioSender,
UnboundedReceiver, UnboundedSender,
};
use tokio_stream::wrappers::ReceiverStream;
use crate::connector::{
create_http_client, create_tls_config, CACertificates, CertificateErrorOverrideManager,
Connector,
};
use crate::cookie;
use crate::cookie_storage::CookieStorage;
use crate::decoder::Decoder;
use crate::fetch::cors_cache::CorsCache;
use crate::fetch::methods::{main_fetch, Data, DoneChannel, FetchContext, Target};
use crate::hsts::HstsList;
use crate::http_cache::{CacheKey, HttpCache};
use crate::resource_thread::AuthCache;
lazy_static! {
pub static ref HANDLE: Mutex<Option<Runtime>> = Mutex::new(Some(Runtime::new().unwrap()));
}
/// The various states an entry of the HttpCache can be in.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum HttpCacheEntryState {
/// The entry is fully up-to-date,
/// there are no pending concurrent stores,
/// and it is ready to construct cached responses.
ReadyToConstruct,
/// The entry is pending a number of concurrent stores.
PendingStore(usize),
}
type HttpCacheState = Mutex<HashMap<CacheKey, Arc<(Mutex<HttpCacheEntryState>, Condvar)>>>;
pub struct HttpState {
pub hsts_list: RwLock<HstsList>,
pub cookie_jar: RwLock<CookieStorage>,
pub http_cache: RwLock<HttpCache>,
/// A map of cache key to entry state,
/// reflecting whether the cache entry is ready to read from,
/// or whether a concurrent pending store should be awaited.
pub http_cache_state: HttpCacheState,
pub auth_cache: RwLock<AuthCache>,
pub history_states: RwLock<HashMap<HistoryStateId, Vec<u8>>>,
pub client: Client<Connector, Body>,
pub override_manager: CertificateErrorOverrideManager,
}
impl Default for HttpState {
fn default() -> Self {
let override_manager = CertificateErrorOverrideManager::new();
Self {
hsts_list: RwLock::new(HstsList::default()),
cookie_jar: RwLock::new(CookieStorage::new(150)),
auth_cache: RwLock::new(AuthCache::default()),
history_states: RwLock::new(HashMap::new()),
http_cache: RwLock::new(HttpCache::default()),
http_cache_state: Mutex::new(HashMap::new()),
client: create_http_client(create_tls_config(
CACertificates::Default,
false, /* ignore_certificate_errors */
override_manager.clone(),
)),
override_manager,
}
}
}
fn precise_time_ms() -> u64 {
time::precise_time_ns() / (1000 * 1000)
}
// Step 3 of https://fetch.spec.whatwg.org/#concept-fetch.
pub fn set_default_accept(destination: Destination, headers: &mut HeaderMap) {
if headers.contains_key(header::ACCEPT) {
return;
}
let value = match destination {
// Step 3.2.
Destination::Document => vec![
QualityItem::new(mime::TEXT_HTML, Quality::from_u16(1000)),
QualityItem::new(
"application/xhtml+xml".parse().unwrap(),
Quality::from_u16(1000),
),
QualityItem::new("application/xml".parse().unwrap(), Quality::from_u16(900)),
QualityItem::new(mime::STAR_STAR, Quality::from_u16(800)),
],
// Step 3.3.
Destination::Image => vec![
QualityItem::new(mime::IMAGE_PNG, Quality::from_u16(1000)),
QualityItem::new(mime::IMAGE_SVG, Quality::from_u16(1000)),
QualityItem::new(mime::IMAGE_STAR, Quality::from_u16(800)),
QualityItem::new(mime::STAR_STAR, Quality::from_u16(500)),
],
// Step 3.3.
Destination::Style => vec![
QualityItem::new(mime::TEXT_CSS, Quality::from_u16(1000)),
QualityItem::new(mime::STAR_STAR, Quality::from_u16(100)),
],
// Step 3.1.
_ => vec![QualityItem::new(mime::STAR_STAR, Quality::from_u16(1000))],
};
// Step 3.4.
// TODO(eijebong): Change this once typed headers are done
headers.insert(header::ACCEPT, quality_to_value(value));
}
fn set_default_accept_encoding(headers: &mut HeaderMap) {
if headers.contains_key(header::ACCEPT_ENCODING) {
return;
}
// TODO(eijebong): Change this once typed headers are done
headers.insert(
header::ACCEPT_ENCODING,
HeaderValue::from_static("gzip, deflate, br"),
);
}
pub fn set_default_accept_language(headers: &mut HeaderMap) {
if headers.contains_key(header::ACCEPT_LANGUAGE) {
return;
}
// TODO(eijebong): Change this once typed headers are done
headers.insert(
header::ACCEPT_LANGUAGE,
HeaderValue::from_static("en-US, en; q=0.5"),
);
}
/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-state-no-referrer-when-downgrade>
fn no_referrer_when_downgrade(referrer_url: ServoUrl, current_url: ServoUrl) -> Option<ServoUrl> {
// Step 1
if referrer_url.is_potentially_trustworthy() && !current_url.is_potentially_trustworthy() {
return None;
}
// Step 2
strip_url_for_use_as_referrer(referrer_url, false)
}
/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-strict-origin>
fn strict_origin(referrer_url: ServoUrl, current_url: ServoUrl) -> Option<ServoUrl> {
// Step 1
if referrer_url.is_potentially_trustworthy() && !current_url.is_potentially_trustworthy() {
return None;
}
// Step 2
strip_url_for_use_as_referrer(referrer_url, true)
}
/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-strict-origin-when-cross-origin>
fn strict_origin_when_cross_origin(
referrer_url: ServoUrl,
current_url: ServoUrl,
) -> Option<ServoUrl> {
// Step 1
if referrer_url.origin() == current_url.origin() {
return strip_url_for_use_as_referrer(referrer_url, false);
}
// Step 2
if referrer_url.is_potentially_trustworthy() && !current_url.is_potentially_trustworthy() {
return None;
}
// Step 3
strip_url_for_use_as_referrer(referrer_url, true)
}
/// <https://html.spec.whatwg.org/multipage/#schemelessly-same-site>
fn is_schemelessy_same_site(site_a: &ImmutableOrigin, site_b: &ImmutableOrigin) -> bool {
// Step 1
if !site_a.is_tuple() && !site_b.is_tuple() && site_a == site_b {
true
} else if site_a.is_tuple() && site_b.is_tuple() {
// Step 2.1
let host_a = site_a.host().map(|h| h.to_string()).unwrap_or_default();
let host_b = site_b.host().map(|h| h.to_string()).unwrap_or_default();
let host_a_reg = reg_suffix(&host_a);
let host_b_reg = reg_suffix(&host_b);
// Step 2.2-2.3
(site_a.host() == site_b.host() && host_a_reg.is_empty()) ||
(host_a_reg == host_b_reg && !host_a_reg.is_empty())
} else {
// Step 3
false
}
}
/// <https://w3c.github.io/webappsec-referrer-policy/#strip-url>
fn strip_url_for_use_as_referrer(mut url: ServoUrl, origin_only: bool) -> Option<ServoUrl> {
const MAX_REFERRER_URL_LENGTH: usize = 4096;
// Step 2
if url.is_local_scheme() {
return None;
}
// Step 3-6
{
let url = url.as_mut_url();
let _ = url.set_username("");
let _ = url.set_password(None);
url.set_fragment(None);
// Note: The result of serializing referrer url should not be
// greater than 4096 as specified in Step 6 of
// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
if origin_only || url.as_str().len() > MAX_REFERRER_URL_LENGTH {
url.set_path("");
url.set_query(None);
}
}
// Step 7
Some(url)
}
/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-same-origin>
fn same_origin(referrer_url: ServoUrl, current_url: ServoUrl) -> Option<ServoUrl> {
// Step 1
if referrer_url.origin() == current_url.origin() {
return strip_url_for_use_as_referrer(referrer_url, false);
}
// Step 2
None
}
/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-origin-when-cross-origin>
fn origin_when_cross_origin(referrer_url: ServoUrl, current_url: ServoUrl) -> Option<ServoUrl> {
// Step 1
if referrer_url.origin() == current_url.origin() {
return strip_url_for_use_as_referrer(referrer_url, false);
}
// Step 2
strip_url_for_use_as_referrer(referrer_url, true)
}
/// <https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer>
pub fn determine_requests_referrer(
referrer_policy: ReferrerPolicy,
referrer_source: ServoUrl,
current_url: ServoUrl,
) -> Option<ServoUrl> {
match referrer_policy {
ReferrerPolicy::NoReferrer => None,
ReferrerPolicy::Origin => strip_url_for_use_as_referrer(referrer_source, true),
ReferrerPolicy::UnsafeUrl => strip_url_for_use_as_referrer(referrer_source, false),
ReferrerPolicy::StrictOrigin => strict_origin(referrer_source, current_url),
ReferrerPolicy::StrictOriginWhenCrossOrigin => {
strict_origin_when_cross_origin(referrer_source, current_url)
},
ReferrerPolicy::SameOrigin => same_origin(referrer_source, current_url),
ReferrerPolicy::OriginWhenCrossOrigin => {
origin_when_cross_origin(referrer_source, current_url)
},
ReferrerPolicy::NoReferrerWhenDowngrade => {
no_referrer_when_downgrade(referrer_source, current_url)
},
}
}
pub fn set_request_cookies(
url: &ServoUrl,
headers: &mut HeaderMap,
cookie_jar: &RwLock<CookieStorage>,
) {
let mut cookie_jar = cookie_jar.write().unwrap();
cookie_jar.remove_expired_cookies_for_url(url);
if let Some(cookie_list) = cookie_jar.cookies_for_url(url, CookieSource::HTTP) {
headers.insert(
header::COOKIE,
HeaderValue::from_bytes(cookie_list.as_bytes()).unwrap(),
);
}
}
fn set_cookie_for_url(cookie_jar: &RwLock<CookieStorage>, request: &ServoUrl, cookie_val: &str) {
let mut cookie_jar = cookie_jar.write().unwrap();
let source = CookieSource::HTTP;
if let Some(cookie) = cookie::Cookie::from_cookie_string(cookie_val.into(), request, source) {
cookie_jar.push(cookie, request, source);
}
}
fn set_cookies_from_headers(
url: &ServoUrl,
headers: &HeaderMap,
cookie_jar: &RwLock<CookieStorage>,
) {
for cookie in headers.get_all(header::SET_COOKIE) {
if let Ok(cookie_str) = std::str::from_utf8(cookie.as_bytes()) {
set_cookie_for_url(cookie_jar, url, cookie_str);
}
}
}
#[allow(clippy::too_many_arguments)]
fn prepare_devtools_request(
request_id: String,
url: ServoUrl,
method: Method,
headers: HeaderMap,
body: Option<Vec<u8>>,
pipeline_id: PipelineId,
now: SystemTime,
connect_time: u64,
send_time: u64,
is_xhr: bool,
) -> ChromeToDevtoolsControlMsg {
let request = DevtoolsHttpRequest {
url,
method,
headers,
body,
pipeline_id,
startedDateTime: now,
timeStamp: now.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs() as i64,
connect_time,
send_time,
is_xhr,
};
let net_event = NetworkEvent::HttpRequest(request);
ChromeToDevtoolsControlMsg::NetworkEvent(request_id, net_event)
}
fn send_request_to_devtools(
msg: ChromeToDevtoolsControlMsg,
devtools_chan: &Sender<DevtoolsControlMsg>,
) {
devtools_chan
.send(DevtoolsControlMsg::FromChrome(msg))
.unwrap();
}
fn send_response_to_devtools(
devtools_chan: &Sender<DevtoolsControlMsg>,
request_id: String,
headers: Option<HeaderMap>,
status: Option<(u16, Vec<u8>)>,
pipeline_id: PipelineId,
) {
let response = DevtoolsHttpResponse {
headers,
status,
body: None,
pipeline_id,
};
let net_event_response = NetworkEvent::HttpResponse(response);
let msg = ChromeToDevtoolsControlMsg::NetworkEvent(request_id, net_event_response);
let _ = devtools_chan.send(DevtoolsControlMsg::FromChrome(msg));
}
fn auth_from_cache(
auth_cache: &RwLock<AuthCache>,
origin: &ImmutableOrigin,
) -> Option<Authorization<Basic>> {
if let Some(auth_entry) = auth_cache
.read()
.unwrap()
.entries
.get(&origin.ascii_serialization())
{
let user_name = &auth_entry.user_name;
let password = &auth_entry.password;
Some(Authorization::basic(user_name, password))
} else {
None
}
}
/// Messages from the IPC route to the fetch worker,
/// used to fill the body with bytes coming-in over IPC.
enum BodyChunk {
/// A chunk of bytes.
Chunk(Vec<u8>),
/// Body is done.
Done,
}
/// The stream side of the body passed to hyper.
enum BodyStream {
/// A receiver that can be used in Body::wrap_stream,
/// for streaming the request over the network.
Chunked(TokioReceiver<Vec<u8>>),
/// A body whose bytes are buffered
/// and sent in one chunk over the network.
Buffered(UnboundedReceiver<BodyChunk>),
}
/// The sink side of the body passed to hyper,
/// used to enqueue chunks.
enum BodySink {
/// A Tokio sender used to feed chunks to the network stream.
Chunked(TokioSender<Vec<u8>>),
/// A Crossbeam sender used to send chunks to the fetch worker,
/// where they will be buffered
/// in order to ensure they are not streamed them over the network.
Buffered(UnboundedSender<BodyChunk>),
}
impl BodySink {
pub fn transmit_bytes(&self, bytes: Vec<u8>) {
match self {
BodySink::Chunked(ref sender) => {
let sender = sender.clone();
HANDLE.lock().unwrap().as_mut().unwrap().spawn(async move {
let _ = sender.send(bytes).await;
});
},
BodySink::Buffered(ref sender) => {
let _ = sender.send(BodyChunk::Chunk(bytes));
},
}
}
pub fn close(&self) {
match self {
BodySink::Chunked(_) => { /* no need to close sender */ },
BodySink::Buffered(ref sender) => {
let _ = sender.send(BodyChunk::Done);
},
}
}
}
#[allow(clippy::too_many_arguments)]
async fn obtain_response(
client: &Client<Connector, Body>,
url: &ServoUrl,
method: &Method,
request_headers: &mut HeaderMap,
body: Option<StdArc<Mutex<IpcSender<BodyChunkRequest>>>>,
source_is_null: bool,
pipeline_id: &Option<PipelineId>,
request_id: Option<&str>,
is_xhr: bool,
context: &FetchContext,
fetch_terminated: UnboundedSender<bool>,
) -> Result<(HyperResponse<Decoder>, Option<ChromeToDevtoolsControlMsg>), NetworkError> {
{
let mut headers = request_headers.clone();
let devtools_bytes = StdArc::new(Mutex::new(vec![]));
// https://url.spec.whatwg.org/#percent-encoded-bytes
let encoded_url = url
.clone()
.into_url()
.as_ref()
.replace('|', "%7C")
.replace('{', "%7B")
.replace('}', "%7D");
let request = if let Some(chunk_requester) = body {
let (sink, stream) = if source_is_null {
// Step 4.2 of https://fetch.spec.whatwg.org/#concept-http-network-fetch
// TODO: this should not be set for HTTP/2(currently not supported?).
headers.insert(TRANSFER_ENCODING, HeaderValue::from_static("chunked"));
let (sender, receiver) = channel(1);
(BodySink::Chunked(sender), BodyStream::Chunked(receiver))
} else {
// Note: Hyper seems to already buffer bytes when the request appears not stream-able,
// see https://github.com/hyperium/hyper/issues/2232#issuecomment-644322104
//
// However since this doesn't appear documented, and we're using an ancient version,
// for now we buffer manually to ensure we don't stream requests
// to servers that might not know how to handle them.
let (sender, receiver) = unbounded_channel();
(BodySink::Buffered(sender), BodyStream::Buffered(receiver))
};
let (body_chan, body_port) = ipc::channel().unwrap();
if let Ok(requester) = chunk_requester.lock() {
let _ = requester.send(BodyChunkRequest::Connect(body_chan));
// https://fetch.spec.whatwg.org/#concept-request-transmit-body
// Request the first chunk, corresponding to Step 3 and 4.
let _ = requester.send(BodyChunkRequest::Chunk);
}
let devtools_bytes = devtools_bytes.clone();
let chunk_requester2 = chunk_requester.clone();
ROUTER.add_route(
body_port.to_opaque(),
Box::new(move |message| {
info!("Received message");
let bytes: Vec<u8> = match message.to().unwrap() {
BodyChunkResponse::Chunk(bytes) => bytes,
BodyChunkResponse::Done => {
// Step 3, abort these parallel steps.
let _ = fetch_terminated.send(false);
sink.close();
return;
},
BodyChunkResponse::Error => {
// Step 4 and/or 5.
// TODO: differentiate between the two steps,
// where step 5 requires setting an `aborted` flag on the fetch.
let _ = fetch_terminated.send(true);
sink.close();
return;
},
};
devtools_bytes.lock().unwrap().append(&mut bytes.clone());
// Step 5.1.2.2, transmit chunk over the network,
// currently implemented by sending the bytes to the fetch worker.
sink.transmit_bytes(bytes);
// Step 5.1.2.3
// Request the next chunk.
let _ = chunk_requester2
.lock()
.unwrap()
.send(BodyChunkRequest::Chunk);
}),
);
let body = match stream {
BodyStream::Chunked(receiver) => {
let stream = ReceiverStream::new(receiver);
Body::wrap_stream(stream.map(Ok::<_, Infallible>))
},
BodyStream::Buffered(mut receiver) => {
// Accumulate bytes received over IPC into a vector.
let mut body = vec![];
loop {
match receiver.recv().await {
Some(BodyChunk::Chunk(mut bytes)) => {
body.append(&mut bytes);
},
Some(BodyChunk::Done) => break,
None => warn!("Failed to read all chunks from request body."),
}
}
body.into()
},
};
HyperRequest::builder()
.method(method)
.uri(encoded_url)
.body(body)
} else {
HyperRequest::builder()
.method(method)
.uri(encoded_url)
.body(Body::empty())
};
context
.timing
.lock()
.unwrap()
.set_attribute(ResourceAttribute::DomainLookupStart);
// TODO(#21261) connect_start: set if a persistent connection is *not* used and the last non-redirected
// fetch passes the timing allow check
let connect_start = precise_time_ms();
context
.timing
.lock()
.unwrap()
.set_attribute(ResourceAttribute::ConnectStart(connect_start));
// TODO: We currently don't know when the handhhake before the connection is done
// so our best bet would be to set `secure_connection_start` here when we are currently
// fetching on a HTTPS url.
if url.scheme() == "https" {
context
.timing
.lock()
.unwrap()
.set_attribute(ResourceAttribute::SecureConnectionStart);
}
let mut request = match request {
Ok(request) => request,
Err(e) => return Err(NetworkError::from_http_error(&e)),
};
*request.headers_mut() = headers.clone();
let connect_end = precise_time_ms();
context
.timing
.lock()
.unwrap()
.set_attribute(ResourceAttribute::ConnectEnd(connect_end));
let request_id = request_id.map(|v| v.to_owned());
let pipeline_id = *pipeline_id;
let closure_url = url.clone();
let method = method.clone();
let send_start = precise_time_ms();
let host = request.uri().host().unwrap_or("").to_owned();
let override_manager = context.state.override_manager.clone();
let headers = headers.clone();
client
.request(request)
.and_then(move |res| {
let send_end = precise_time_ms();
// TODO(#21271) response_start: immediately after receiving first byte of response
let msg = if let Some(request_id) = request_id {
if let Some(pipeline_id) = pipeline_id {
Some(prepare_devtools_request(
request_id,
closure_url,
method.clone(),
headers,
Some(devtools_bytes.lock().unwrap().clone()),
pipeline_id,
SystemTime::now(),
connect_end - connect_start,
send_end - send_start,
is_xhr,
))
// TODO: ^This is not right, connect_start is taken before contructing the
// request and connect_end at the end of it. send_start is takend before the
// connection too. I'm not sure it's currently possible to get the time at the
// point between the connection and the start of a request.
} else {
debug!("Not notifying devtools (no pipeline_id)");
None
}
} else {
debug!("Not notifying devtools (no request_id)");
None
};
future::ready(Ok((Decoder::detect(res), msg)))
})
.map_err(move |error| {
NetworkError::from_hyper_error(
&error,
override_manager.remove_certificate_failing_verification(host.as_str()),
)
})
.await
}
}
/// [HTTP fetch](https://fetch.spec.whatwg.org#http-fetch)
#[async_recursion]
#[allow(clippy::too_many_arguments)]
pub async fn http_fetch(
request: &mut Request,
cache: &mut CorsCache,
cors_flag: bool,
cors_preflight_flag: bool,
authentication_fetch_flag: bool,
target: Target<'async_recursion>,
done_chan: &mut DoneChannel,
context: &FetchContext,
) -> Response {
// This is a new async fetch, reset the channel we are waiting on
*done_chan = None;
// Step 1
let mut response: Option<Response> = None;
// Step 2
// nothing to do, since actual_response is a function on response
// Step 3
if request.service_workers_mode == ServiceWorkersMode::All {
// TODO: Substep 1
// Set response to the result of invoking handle fetch for request.
// Substep 2
if let Some(ref res) = response {
// Subsubstep 1
// TODO: transmit body for request
// Subsubstep 2
// nothing to do, since actual_response is a function on response
// Subsubstep 3
if (res.response_type == ResponseType::Opaque && request.mode != RequestMode::NoCors) ||
(res.response_type == ResponseType::OpaqueRedirect &&
request.redirect_mode != RedirectMode::Manual) ||
(res.url_list.len() > 1 && request.redirect_mode != RedirectMode::Follow) ||
res.is_network_error()
{
return Response::network_error(NetworkError::Internal("Request failed".into()));
}
// Subsubstep 4
// TODO: set response's CSP list on actual_response
}
}
// Step 4
if response.is_none() {
// Substep 1
if cors_preflight_flag {
let method_cache_match = cache.match_method(&*request, request.method.clone());
let method_mismatch = !method_cache_match &&
(!is_cors_safelisted_method(&request.method) || request.use_cors_preflight);
let header_mismatch = request.headers.iter().any(|(name, value)| {
!cache.match_header(&*request, name) &&
!is_cors_safelisted_request_header(&name, &value)
});
// Sub-substep 1
if method_mismatch || header_mismatch {
let preflight_result = cors_preflight_fetch(request, cache, context).await;
// Sub-substep 2
if let Some(e) = preflight_result.get_network_error() {
return Response::network_error(e.clone());
}
}
}
// Substep 2
if request.redirect_mode == RedirectMode::Follow {
request.service_workers_mode = ServiceWorkersMode::None;
}
// Generally, we use a persistent connection, so we will also set other PerformanceResourceTiming
// attributes to this as well (domain_lookup_start, domain_lookup_end, connect_start, connect_end,
// secure_connection_start)
context
.timing
.lock()
.unwrap()
.set_attribute(ResourceAttribute::RequestStart);
let mut fetch_result = http_network_or_cache_fetch(
request,
authentication_fetch_flag,
cors_flag,
done_chan,
context,
)
.await;
// Substep 4
if cors_flag && cors_check(request, &fetch_result).is_err() {
return Response::network_error(NetworkError::Internal("CORS check failed".into()));
}
fetch_result.return_internal = false;
response = Some(fetch_result);
}
// response is guaranteed to be something by now
let mut response = response.unwrap();
// Step 5
if response
.actual_response()
.status
.as_ref()
.map_or(false, is_redirect_status)
{
// Substep 1.
if response
.actual_response()
.status
.as_ref()
.map_or(true, |s| s.0 != StatusCode::SEE_OTHER)
{
// TODO: send RST_STREAM frame
}
// Substep 2-3.
let mut location = response
.actual_response()
.headers
.get(header::LOCATION)
.and_then(|v| {
HeaderValue::to_str(v)
.map(|l| {
ServoUrl::parse_with_base(response.actual_response().url(), l)
.map_err(|err| err.to_string())
})
.ok()
});
// Substep 4.
if let Some(Ok(ref mut location)) = location {
if location.fragment().is_none() {
let current_url = request.current_url();
location.set_fragment(current_url.fragment());
}
}
response.actual_response_mut().location_url = location;
// Substep 5.
response = match request.redirect_mode {
RedirectMode::Error => {
Response::network_error(NetworkError::Internal("Redirect mode error".into()))
},
RedirectMode::Manual => response.to_filtered(ResponseType::OpaqueRedirect),
RedirectMode::Follow => {
// set back to default
response.return_internal = true;
http_redirect_fetch(
request, cache, response, cors_flag, target, done_chan, context,
)
.await
},
};
}
// set back to default
response.return_internal = true;
context
.timing
.lock()
.unwrap()
.set_attribute(ResourceAttribute::RedirectCount(
request.redirect_count as u16,
));
response.resource_timing = Arc::clone(&context.timing);
// Step 6
response
}
// Convenience struct that implements Drop, for setting redirectEnd on function return
struct RedirectEndTimer(Option<Arc<Mutex<ResourceFetchTiming>>>);
impl RedirectEndTimer {
fn neuter(&mut self) {
self.0 = None;
}
}
impl Drop for RedirectEndTimer {
fn drop(&mut self) {
let RedirectEndTimer(resource_fetch_timing_opt) = self;
resource_fetch_timing_opt.as_ref().map_or((), |t| {
t.lock()
.unwrap()
.set_attribute(ResourceAttribute::RedirectEnd(RedirectEndValue::Zero));
})
}
}
/// [HTTP redirect fetch](https://fetch.spec.whatwg.org#http-redirect-fetch)
#[async_recursion]
pub async fn http_redirect_fetch(
request: &mut Request,
cache: &mut CorsCache,
response: Response,
cors_flag: bool,
target: Target<'async_recursion>,
done_chan: &mut DoneChannel,
context: &FetchContext,
) -> Response {
let mut redirect_end_timer = RedirectEndTimer(Some(context.timing.clone()));
// Step 1
assert!(response.return_internal);
let location_url = response.actual_response().location_url.clone();
let location_url = match location_url {
// Step 2
None => return response,
// Step 3
Some(Err(err)) => {
return Response::network_error(NetworkError::Internal(
"Location URL parse failure: ".to_owned() + &err,
));
},
// Step 4
Some(Ok(ref url)) if !matches!(url.scheme(), "http" | "https") => {
return Response::network_error(NetworkError::Internal(
"Location URL not an HTTP(S) scheme".into(),
));
},
Some(Ok(url)) => url,
};
// Step 1 of https://w3c.github.io/resource-timing/#dom-performanceresourcetiming-fetchstart
// TODO: check origin and timing allow check
context
.timing
.lock()
.unwrap()
.set_attribute(ResourceAttribute::RedirectStart(
RedirectStartValue::FetchStart,
));
context
.timing
.lock()
.unwrap()
.set_attribute(ResourceAttribute::FetchStart);
// start_time should equal redirect_start if nonzero; else fetch_start
context
.timing
.lock()
.unwrap()
.set_attribute(ResourceAttribute::StartTime(ResourceTimeValue::FetchStart));
context
.timing
.lock()
.unwrap()
.set_attribute(ResourceAttribute::StartTime(
ResourceTimeValue::RedirectStart,
)); // updates start_time only if redirect_start is nonzero (implying TAO)
// Step 5
if request.redirect_count >= 20 {
return Response::network_error(NetworkError::Internal("Too many redirects".into()));
}
// Step 6
request.redirect_count += 1;
// Step 7
let same_origin = match request.origin {
Origin::Origin(ref origin) => *origin == location_url.origin(),
Origin::Client => panic!(
"Request origin should not be client for {}",
request.current_url()
),
};
let has_credentials = has_credentials(&location_url);
if request.mode == RequestMode::CorsMode && !same_origin && has_credentials {
return Response::network_error(NetworkError::Internal(
"Cross-origin credentials check failed".into(),
));
}
// Step 8
if cors_flag && has_credentials {