forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurl_request_http_job.cc
1560 lines (1358 loc) · 56.2 KB
/
url_request_http_job.cc
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/url_request/url_request_http_job.h"
#include <vector>
#include "base/base_switches.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_version_info.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_macros.h"
#include "base/profiler/scoped_tracker.h"
#include "base/rand_util.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "base/values.h"
#include "net/base/host_port_pair.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/base/network_delegate.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/base/sdch_manager.h"
#include "net/base/sdch_problem_codes.h"
#include "net/base/trace_constants.h"
#include "net/base/url_util.h"
#include "net/cert/cert_status_flags.h"
#include "net/cookies/cookie_store.h"
#include "net/filter/brotli_source_stream.h"
#include "net/filter/filter_source_stream.h"
#include "net/filter/gzip_source_stream.h"
#include "net/filter/sdch_source_stream.h"
#include "net/filter/source_stream.h"
#include "net/http/http_content_disposition.h"
#include "net/http/http_network_session.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/http/http_status_code.h"
#include "net/http/http_transaction.h"
#include "net/http/http_transaction_factory.h"
#include "net/http/http_util.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_with_source.h"
#include "net/nqe/network_quality_estimator.h"
#include "net/proxy/proxy_info.h"
#include "net/proxy/proxy_retry_info.h"
#include "net/proxy/proxy_service.h"
#include "net/ssl/channel_id_service.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "net/ssl/ssl_config_service.h"
#include "net/url_request/http_user_agent_settings.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_error_job.h"
#include "net/url_request/url_request_job_factory.h"
#include "net/url_request/url_request_redirect_job.h"
#include "net/url_request/url_request_throttler_manager.h"
#include "net/websockets/websocket_handshake_stream_base.h"
#include "url/origin.h"
#if defined(OS_ANDROID)
#include "net/android/network_library.h"
#endif
static const char kAvailDictionaryHeader[] = "Avail-Dictionary";
namespace {
const char kDeflate[] = "deflate";
const char kGZip[] = "gzip";
const char kSdch[] = "sdch";
const char kXGZip[] = "x-gzip";
const char kBrotli[] = "br";
// True if the request method is "safe" (per section 4.2.1 of RFC 7231).
bool IsMethodSafe(const std::string& method) {
return method == "GET" || method == "HEAD" || method == "OPTIONS" ||
method == "TRACE";
}
// Logs whether the CookieStore used for this request matches the
// ChannelIDService used when establishing the connection that this request is
// sent over. This logging is only done for requests to accounts.google.com, and
// only for requests where Channel ID was sent when establishing the connection.
void LogChannelIDAndCookieStores(const GURL& url,
const net::URLRequestContext* context,
const net::SSLInfo& ssl_info) {
if (url.host() != "accounts.google.com" || !ssl_info.channel_id_sent)
return;
// This enum is used for an UMA histogram - don't reuse or renumber entries.
enum {
// Value 0 was removed (CID_EPHEMERAL_COOKIE_EPHEMERAL)
// ChannelIDStore is ephemeral, but CookieStore is persistent.
CID_EPHEMERAL_COOKIE_PERSISTENT = 1,
// ChannelIDStore is persistent, but CookieStore is ephemeral.
CID_PERSISTENT_COOKIE_EPHEMERAL = 2,
// Value 3 was removed (CID_PERSISTENT_COOKIE_PERSISTENT)
// There is no CookieStore for this request.
NO_COOKIE_STORE = 4,
// There is no ChannelIDStore for this request. This should never happen,
// because we only log if Channel ID was sent.
NO_CHANNEL_ID_STORE = 5,
// Value 6 was removed (KNOWN_MISMATCH).
// Both stores are ephemeral, and the ChannelIDService used when
// establishing the connection is the same one that the CookieStore was
// created to be used with.
EPHEMERAL_MATCH = 7,
// Both stores are ephemeral, but a different CookieStore should have been
// used on this request.
EPHEMERAL_MISMATCH = 8,
// Both stores are persistent, and the ChannelIDService used when
// establishing the connection is the same one that the CookieStore was
// created to be used with.
PERSISTENT_MATCH = 9,
// Both stores are persistent, but a different CookieStore should have been
// used on this request.
PERSISTENT_MISMATCH = 10,
// Both stores are ephemeral, but it was never recorded in the CookieStore
// which ChannelIDService it was created for, so it is unknown whether the
// stores match.
EPHEMERAL_UNKNOWN = 11,
// Both stores are persistent, but it was never recorded in the CookieStore
// which ChannelIDService it was created for, so it is unknown whether the
// stores match.
PERSISTENT_UNKNOWN = 12,
EPHEMERALITY_MAX
} ephemerality;
const net::HttpNetworkSession::Params* params =
context->GetNetworkSessionParams();
net::CookieStore* cookie_store = context->cookie_store();
if (params == nullptr || params->channel_id_service == nullptr) {
ephemerality = NO_CHANNEL_ID_STORE;
} else if (cookie_store == nullptr) {
ephemerality = NO_COOKIE_STORE;
} else if (params->channel_id_service->GetChannelIDStore()->IsEphemeral()) {
if (cookie_store->IsEphemeral()) {
if (cookie_store->GetChannelIDServiceID() == -1) {
ephemerality = EPHEMERAL_UNKNOWN;
} else if (cookie_store->GetChannelIDServiceID() ==
params->channel_id_service->GetUniqueID()) {
ephemerality = EPHEMERAL_MATCH;
} else {
NOTREACHED();
ephemerality = EPHEMERAL_MISMATCH;
}
} else {
NOTREACHED();
ephemerality = CID_EPHEMERAL_COOKIE_PERSISTENT;
}
} else if (cookie_store->IsEphemeral()) {
NOTREACHED();
ephemerality = CID_PERSISTENT_COOKIE_EPHEMERAL;
} else if (cookie_store->GetChannelIDServiceID() == -1) {
ephemerality = PERSISTENT_UNKNOWN;
} else if (cookie_store->GetChannelIDServiceID() ==
params->channel_id_service->GetUniqueID()) {
ephemerality = PERSISTENT_MATCH;
} else {
NOTREACHED();
ephemerality = PERSISTENT_MISMATCH;
}
UMA_HISTOGRAM_ENUMERATION("Net.TokenBinding.StoreEphemerality", ephemerality,
EPHEMERALITY_MAX);
}
} // namespace
namespace net {
// TODO(darin): make sure the port blocking code is not lost
// static
URLRequestJob* URLRequestHttpJob::Factory(URLRequest* request,
NetworkDelegate* network_delegate,
const std::string& scheme) {
DCHECK(scheme == "http" || scheme == "https" || scheme == "ws" ||
scheme == "wss");
if (!request->context()->http_transaction_factory()) {
NOTREACHED() << "requires a valid context";
return new URLRequestErrorJob(
request, network_delegate, ERR_INVALID_ARGUMENT);
}
const GURL& url = request->url();
// Check for reasons not to return a URLRequestHttpJob. These don't apply to
// https and wss requests.
if (!url.SchemeIsCryptographic()) {
// Check for HSTS upgrade.
TransportSecurityState* hsts =
request->context()->transport_security_state();
if (hsts && hsts->ShouldUpgradeToSSL(url.host())) {
GURL::Replacements replacements;
replacements.SetSchemeStr(
url.SchemeIs(url::kHttpScheme) ? url::kHttpsScheme : url::kWssScheme);
return new URLRequestRedirectJob(
request, network_delegate, url.ReplaceComponents(replacements),
// Use status code 307 to preserve the method, so POST requests work.
URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "HSTS");
}
#if defined(OS_ANDROID)
// Check whether the app allows cleartext traffic to this host, and return
// ERR_CLEARTEXT_NOT_PERMITTED if not.
if (request->context()->check_cleartext_permitted() &&
!android::IsCleartextPermitted(url.host())) {
return new URLRequestErrorJob(request, network_delegate,
ERR_CLEARTEXT_NOT_PERMITTED);
}
#endif
}
return new URLRequestHttpJob(request,
network_delegate,
request->context()->http_user_agent_settings());
}
URLRequestHttpJob::URLRequestHttpJob(
URLRequest* request,
NetworkDelegate* network_delegate,
const HttpUserAgentSettings* http_user_agent_settings)
: URLRequestJob(request, network_delegate),
priority_(DEFAULT_PRIORITY),
response_info_(nullptr),
proxy_auth_state_(AUTH_STATE_DONT_NEED_AUTH),
server_auth_state_(AUTH_STATE_DONT_NEED_AUTH),
read_in_progress_(false),
throttling_entry_(nullptr),
sdch_test_activated_(false),
sdch_test_control_(false),
is_cached_content_(false),
packet_timing_enabled_(false),
done_(false),
bytes_observed_in_packets_(0),
awaiting_callback_(false),
http_user_agent_settings_(http_user_agent_settings),
total_received_bytes_from_previous_transactions_(0),
total_sent_bytes_from_previous_transactions_(0),
weak_factory_(this) {
URLRequestThrottlerManager* manager = request->context()->throttler_manager();
if (manager)
throttling_entry_ = manager->RegisterRequestUrl(request->url());
ResetTimer();
}
URLRequestHttpJob::~URLRequestHttpJob() {
CHECK(!awaiting_callback_);
DCHECK(!sdch_test_control_ || !sdch_test_activated_);
if (!is_cached_content_) {
if (sdch_test_control_)
RecordPacketStats(SdchPolicyDelegate::SDCH_EXPERIMENT_HOLDBACK);
if (sdch_test_activated_)
RecordPacketStats(SdchPolicyDelegate::SDCH_EXPERIMENT_DECODE);
}
// Make sure SdchSourceStream are told to emit histogram data while |this|
// is still alive.
DestroySourceStream();
DoneWithRequest(ABORTED);
}
void URLRequestHttpJob::SetPriority(RequestPriority priority) {
priority_ = priority;
if (transaction_)
transaction_->SetPriority(priority_);
}
void URLRequestHttpJob::Start() {
// TODO(mmenke): Remove ScopedTracker below once crbug.com/456327 is fixed.
tracked_objects::ScopedTracker tracking_profile(
FROM_HERE_WITH_EXPLICIT_FUNCTION("456327 URLRequestHttpJob::Start"));
DCHECK(!transaction_.get());
// URLRequest::SetReferrer ensures that we do not send username and password
// fields in the referrer.
GURL referrer(request_->referrer());
request_info_.url = request_->url();
request_info_.method = request_->method();
request_info_.load_flags = request_->load_flags();
// Enable privacy mode if cookie settings or flags tell us not send or
// save cookies.
bool enable_privacy_mode =
(request_info_.load_flags & LOAD_DO_NOT_SEND_COOKIES) ||
(request_info_.load_flags & LOAD_DO_NOT_SAVE_COOKIES) ||
CanEnablePrivacyMode();
// Privacy mode could still be disabled in SetCookieHeaderAndStart if we are
// going to send previously saved cookies.
request_info_.privacy_mode = enable_privacy_mode ?
PRIVACY_MODE_ENABLED : PRIVACY_MODE_DISABLED;
// Strip Referer from request_info_.extra_headers to prevent, e.g., plugins
// from overriding headers that are controlled using other means. Otherwise a
// plugin could set a referrer although sending the referrer is inhibited.
request_info_.extra_headers.RemoveHeader(HttpRequestHeaders::kReferer);
// Our consumer should have made sure that this is a safe referrer. See for
// instance WebCore::FrameLoader::HideReferrer.
if (referrer.is_valid()) {
request_info_.extra_headers.SetHeader(HttpRequestHeaders::kReferer,
referrer.spec());
}
request_info_.token_binding_referrer = request_->token_binding_referrer();
request_info_.extra_headers.SetHeaderIfMissing(
HttpRequestHeaders::kUserAgent,
http_user_agent_settings_ ?
http_user_agent_settings_->GetUserAgent() : std::string());
AddExtraHeaders();
AddCookieHeaderAndStart();
}
void URLRequestHttpJob::Kill() {
weak_factory_.InvalidateWeakPtrs();
if (transaction_)
DestroyTransaction();
URLRequestJob::Kill();
}
void URLRequestHttpJob::GetConnectionAttempts(ConnectionAttempts* out) const {
if (transaction_)
transaction_->GetConnectionAttempts(out);
else
out->clear();
}
void URLRequestHttpJob::NotifyBeforeSendHeadersCallback(
const ProxyInfo& proxy_info,
HttpRequestHeaders* request_headers) {
DCHECK(request_headers);
DCHECK_NE(URLRequestStatus::CANCELED, GetStatus().status());
if (network_delegate()) {
network_delegate()->NotifyBeforeSendHeaders(
request_, proxy_info,
request_->context()->proxy_service()->proxy_retry_info(),
request_headers);
}
}
void URLRequestHttpJob::NotifyHeadersComplete() {
DCHECK(!response_info_);
response_info_ = transaction_->GetResponseInfo();
// Save boolean, as we'll need this info at destruction time, and filters may
// also need this info.
is_cached_content_ = response_info_->was_cached;
if (!is_cached_content_ && throttling_entry_.get())
throttling_entry_->UpdateWithResponse(GetResponseCode());
// The ordering of these calls is not important.
ProcessStrictTransportSecurityHeader();
ProcessPublicKeyPinsHeader();
ProcessExpectCTHeader();
// Handle the server notification of a new SDCH dictionary.
SdchManager* sdch_manager(request()->context()->sdch_manager());
if (sdch_manager) {
SdchProblemCode rv = sdch_manager->IsInSupportedDomain(request()->url());
if (rv != SDCH_OK) {
SdchManager::LogSdchProblem(request()->net_log(), rv);
} else {
const std::string name = "Get-Dictionary";
std::string url_text;
size_t iter = 0;
// TODO(jar): We need to not fetch dictionaries the first time they are
// seen, but rather wait until we can justify their usefulness.
// For now, we will only fetch the first dictionary, which will at least
// require multiple suggestions before we get additional ones for this
// site. Eventually we should wait until a dictionary is requested
// several times
// before we even download it (so that we don't waste memory or
// bandwidth).
if (GetResponseHeaders()->EnumerateHeader(&iter, name, &url_text)) {
// Resolve suggested URL relative to request url.
GURL sdch_dictionary_url = request_->url().Resolve(url_text);
// Don't try to download Dictionary for cached responses. It's either
// useless or too late.
if (sdch_dictionary_url.is_valid() && !is_cached_content_) {
rv = sdch_manager->OnGetDictionary(request_->url(),
sdch_dictionary_url);
if (rv != SDCH_OK)
SdchManager::LogSdchProblem(request()->net_log(), rv);
}
}
}
}
// Handle the server signalling no SDCH encoding.
if (dictionaries_advertised_) {
// We are wary of proxies that discard or damage SDCH encoding. If a server
// explicitly states that this is not SDCH content, then we can correct our
// assumption that this is an SDCH response, and avoid the need to recover
// as though the content is corrupted (when we discover it is not SDCH
// encoded).
std::string sdch_response_status;
size_t iter = 0;
while (GetResponseHeaders()->EnumerateHeader(&iter, "X-Sdch-Encode",
&sdch_response_status)) {
if (sdch_response_status == "0") {
dictionaries_advertised_.reset();
break;
}
}
}
// The HTTP transaction may be restarted several times for the purposes
// of sending authorization information. Each time it restarts, we get
// notified of the headers completion so that we can update the cookie store.
if (transaction_->IsReadyToRestartForAuth()) {
DCHECK(!response_info_->auth_challenge.get());
// TODO(battre): This breaks the webrequest API for
// URLRequestTestHTTP.BasicAuthWithCookies
// where OnBeforeStartTransaction -> OnStartTransaction ->
// OnBeforeStartTransaction occurs.
RestartTransactionWithAuth(AuthCredentials());
return;
}
URLRequestJob::NotifyHeadersComplete();
}
void URLRequestHttpJob::DestroyTransaction() {
DCHECK(transaction_.get());
DoneWithRequest(ABORTED);
total_received_bytes_from_previous_transactions_ +=
transaction_->GetTotalReceivedBytes();
total_sent_bytes_from_previous_transactions_ +=
transaction_->GetTotalSentBytes();
transaction_.reset();
response_info_ = NULL;
receive_headers_end_ = base::TimeTicks();
}
void URLRequestHttpJob::StartTransaction() {
// TODO(mmenke): Remove ScopedTracker below once crbug.com/456327 is fixed.
tracked_objects::ScopedTracker tracking_profile(
FROM_HERE_WITH_EXPLICIT_FUNCTION(
"456327 URLRequestHttpJob::StartTransaction"));
if (network_delegate()) {
OnCallToDelegate();
// The NetworkDelegate must watch for OnRequestDestroyed and not modify
// |extra_headers| or invoke the callback after it's called. Not using a
// WeakPtr here because it's not enough, the consumer has to watch for
// destruction regardless, due to the headers parameter.
int rv = network_delegate()->NotifyBeforeStartTransaction(
request_,
base::Bind(&URLRequestHttpJob::NotifyBeforeStartTransactionCallback,
base::Unretained(this)),
&request_info_.extra_headers);
// If an extension blocks the request, we rely on the callback to
// MaybeStartTransactionInternal().
if (rv == ERR_IO_PENDING)
return;
MaybeStartTransactionInternal(rv);
return;
}
StartTransactionInternal();
}
void URLRequestHttpJob::NotifyBeforeStartTransactionCallback(int result) {
// Check that there are no callbacks to already canceled requests.
DCHECK_NE(URLRequestStatus::CANCELED, GetStatus().status());
MaybeStartTransactionInternal(result);
}
void URLRequestHttpJob::MaybeStartTransactionInternal(int result) {
// TODO(mmenke): Remove ScopedTracker below once crbug.com/456327 is fixed.
tracked_objects::ScopedTracker tracking_profile(
FROM_HERE_WITH_EXPLICIT_FUNCTION(
"456327 URLRequestHttpJob::MaybeStartTransactionInternal"));
OnCallToDelegateComplete();
if (result == OK) {
StartTransactionInternal();
} else {
std::string source("delegate");
request_->net_log().AddEvent(NetLogEventType::CANCELLED,
NetLog::StringCallback("source", &source));
// Don't call back synchronously to the delegate.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&URLRequestHttpJob::NotifyStartError,
weak_factory_.GetWeakPtr(),
URLRequestStatus(URLRequestStatus::FAILED, result)));
}
}
void URLRequestHttpJob::StartTransactionInternal() {
// This should only be called while the request's status is IO_PENDING.
DCHECK_EQ(URLRequestStatus::IO_PENDING, request_->status().status());
// NOTE: This method assumes that request_info_ is already setup properly.
// If we already have a transaction, then we should restart the transaction
// with auth provided by auth_credentials_.
int rv;
// Notify NetworkQualityEstimator.
NetworkQualityEstimator* network_quality_estimator =
request()->context()->network_quality_estimator();
if (network_quality_estimator)
network_quality_estimator->NotifyStartTransaction(*request_);
if (network_delegate()) {
network_delegate()->NotifyStartTransaction(request_,
request_info_.extra_headers);
}
if (transaction_.get()) {
rv = transaction_->RestartWithAuth(
auth_credentials_, base::Bind(&URLRequestHttpJob::OnStartCompleted,
base::Unretained(this)));
auth_credentials_ = AuthCredentials();
} else {
DCHECK(request_->context()->http_transaction_factory());
rv = request_->context()->http_transaction_factory()->CreateTransaction(
priority_, &transaction_);
if (rv == OK && request_info_.url.SchemeIsWSOrWSS()) {
base::SupportsUserData::Data* data = request_->GetUserData(
WebSocketHandshakeStreamBase::CreateHelper::DataKey());
if (data) {
transaction_->SetWebSocketHandshakeStreamCreateHelper(
static_cast<WebSocketHandshakeStreamBase::CreateHelper*>(data));
} else {
rv = ERR_DISALLOWED_URL_SCHEME;
}
}
if (rv == OK) {
transaction_->SetBeforeHeadersSentCallback(
base::Bind(&URLRequestHttpJob::NotifyBeforeSendHeadersCallback,
base::Unretained(this)));
if (!throttling_entry_.get() ||
!throttling_entry_->ShouldRejectRequest(*request_)) {
rv = transaction_->Start(
&request_info_, base::Bind(&URLRequestHttpJob::OnStartCompleted,
base::Unretained(this)),
request_->net_log());
start_time_ = base::TimeTicks::Now();
} else {
// Special error code for the exponential back-off module.
rv = ERR_TEMPORARILY_THROTTLED;
}
}
}
if (rv == ERR_IO_PENDING)
return;
// The transaction started synchronously, but we need to notify the
// URLRequest delegate via the message loop.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(&URLRequestHttpJob::OnStartCompleted,
weak_factory_.GetWeakPtr(), rv));
}
void URLRequestHttpJob::AddExtraHeaders() {
SdchManager* sdch_manager = request()->context()->sdch_manager();
// Supply Accept-Encoding field only if it is not already provided.
// It should be provided IF the content is known to have restrictions on
// potential encoding, such as streaming multi-media.
// For details see bug 47381.
// TODO(jar, enal): jpeg files etc. should set up a request header if
// possible. Right now it is done only by buffered_resource_loader and
// simple_data_source.
if (!request_info_.extra_headers.HasHeader(
HttpRequestHeaders::kAcceptEncoding)) {
// We don't support SDCH responses to POST as there is a possibility
// of having SDCH encoded responses returned (e.g. by the cache)
// which we cannot decode, and in those situations, we will need
// to retransmit the request without SDCH, which is illegal for a POST.
bool advertise_sdch = sdch_manager != NULL && request()->method() != "POST";
if (advertise_sdch) {
SdchProblemCode rv = sdch_manager->IsInSupportedDomain(request()->url());
if (rv != SDCH_OK) {
advertise_sdch = false;
SdchManager::LogSdchProblem(request()->net_log(), rv);
}
}
if (advertise_sdch) {
dictionaries_advertised_ =
sdch_manager->GetDictionarySet(request_->url());
}
// The AllowLatencyExperiment() is only true if we've successfully done a
// full SDCH compression recently in this browser session for this host.
// Note that for this path, there might be no applicable dictionaries,
// and hence we can't participate in the experiment.
if (dictionaries_advertised_ &&
sdch_manager->AllowLatencyExperiment(request_->url())) {
// We are participating in the test (or control), and hence we'll
// eventually record statistics via either SDCH_EXPERIMENT_DECODE or
// SDCH_EXPERIMENT_HOLDBACK, and we'll need some packet timing data.
packet_timing_enabled_ = true;
if (base::RandDouble() < .01) {
sdch_test_control_ = true; // 1% probability.
dictionaries_advertised_.reset();
advertise_sdch = false;
} else {
sdch_test_activated_ = true;
}
}
// Advertise "br" encoding only if transferred data is opaque to proxy.
bool advertise_brotli = false;
if (request()->context()->enable_brotli()) {
if (request()->url().SchemeIsCryptographic() ||
IsLocalhost(request()->url().HostNoBrackets())) {
advertise_brotli = true;
}
}
// Supply Accept-Encoding headers first so that it is more likely that they
// will be in the first transmitted packet. This can sometimes make it
// easier to filter and analyze the streams to assure that a proxy has not
// damaged these headers. Some proxies deliberately corrupt Accept-Encoding
// headers.
std::string advertised_encodings = "gzip, deflate";
if (advertise_sdch)
advertised_encodings += ", sdch";
if (advertise_brotli)
advertised_encodings += ", br";
// Tell the server what compression formats are supported.
request_info_.extra_headers.SetHeader(HttpRequestHeaders::kAcceptEncoding,
advertised_encodings);
if (dictionaries_advertised_) {
request_info_.extra_headers.SetHeader(
kAvailDictionaryHeader,
dictionaries_advertised_->GetDictionaryClientHashList());
// Since we're tagging this transaction as advertising a dictionary,
// we'll definitely employ an SDCH filter (or tentative sdch filter)
// when we get a response. When done, we'll record histograms via
// SDCH_DECODE or SDCH_PASSTHROUGH. Hence we need to record packet
// arrival times.
packet_timing_enabled_ = true;
}
}
if (http_user_agent_settings_) {
// Only add default Accept-Language if the request didn't have it
// specified.
std::string accept_language =
http_user_agent_settings_->GetAcceptLanguage();
if (!accept_language.empty()) {
request_info_.extra_headers.SetHeaderIfMissing(
HttpRequestHeaders::kAcceptLanguage,
accept_language);
}
}
}
void URLRequestHttpJob::AddCookieHeaderAndStart() {
CookieStore* cookie_store = request_->context()->cookie_store();
if (cookie_store && !(request_info_.load_flags & LOAD_DO_NOT_SEND_COOKIES)) {
CookieOptions options;
options.set_include_httponly();
// Set SameSiteCookieMode according to the rules laid out in
// https://tools.ietf.org/html/draft-west-first-party-cookies:
//
// * Include both "strict" and "lax" same-site cookies if the request's
// |url|, |initiator|, and |first_party_for_cookies| all have the same
// registrable domain. Note: this also covers the case of a request
// without an initiator (only happens for browser-initiated main frame
// navigations).
//
// * Include only "lax" same-site cookies if the request's |URL| and
// |first_party_for_cookies| have the same registrable domain, _and_ the
// request's |method| is "safe" ("GET" or "HEAD").
//
// Note that this will generally be the case only for cross-site requests
// which target a top-level browsing context.
//
// * Otherwise, do not include same-site cookies.
if (registry_controlled_domains::SameDomainOrHost(
request_->url(), request_->first_party_for_cookies(),
registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) {
if (!request_->initiator() ||
registry_controlled_domains::SameDomainOrHost(
request_->url(), request_->initiator().value().GetURL(),
registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) {
options.set_same_site_cookie_mode(
CookieOptions::SameSiteCookieMode::INCLUDE_STRICT_AND_LAX);
} else if (IsMethodSafe(request_->method())) {
options.set_same_site_cookie_mode(
CookieOptions::SameSiteCookieMode::INCLUDE_LAX);
}
}
cookie_store->GetCookieListWithOptionsAsync(
request_->url(), options,
base::Bind(&URLRequestHttpJob::SetCookieHeaderAndStart,
weak_factory_.GetWeakPtr()));
} else {
StartTransaction();
}
}
void URLRequestHttpJob::SetCookieHeaderAndStart(const CookieList& cookie_list) {
if (!cookie_list.empty() && CanGetCookies(cookie_list)) {
request_info_.extra_headers.SetHeader(
HttpRequestHeaders::kCookie, CookieStore::BuildCookieLine(cookie_list));
// Disable privacy mode as we are sending cookies anyway.
request_info_.privacy_mode = PRIVACY_MODE_DISABLED;
}
StartTransaction();
}
void URLRequestHttpJob::SaveCookiesAndNotifyHeadersComplete(int result) {
// End of the call started in OnStartCompleted.
OnCallToDelegateComplete();
if (result != OK) {
std::string source("delegate");
request_->net_log().AddEvent(NetLogEventType::CANCELLED,
NetLog::StringCallback("source", &source));
NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, result));
return;
}
base::Time response_date;
if (!GetResponseHeaders()->GetDateValue(&response_date))
response_date = base::Time();
if (!(request_info_.load_flags & LOAD_DO_NOT_SAVE_COOKIES) &&
request_->context()->cookie_store()) {
CookieOptions options;
options.set_include_httponly();
options.set_server_time(response_date);
// Set all cookies, without waiting for them to be set. Any subsequent read
// will see the combined result of all cookie operation.
const base::StringPiece name("Set-Cookie");
std::string cookie;
size_t iter = 0;
HttpResponseHeaders* headers = GetResponseHeaders();
while (headers->EnumerateHeader(&iter, name, &cookie)) {
if (cookie.empty() || !CanSetCookie(cookie, &options))
continue;
request_->context()->cookie_store()->SetCookieWithOptionsAsync(
request_->url(), cookie, options, CookieStore::SetCookiesCallback());
}
}
NotifyHeadersComplete();
}
// NOTE: |ProcessStrictTransportSecurityHeader| and
// |ProcessPublicKeyPinsHeader| have very similar structures, by design.
void URLRequestHttpJob::ProcessStrictTransportSecurityHeader() {
DCHECK(response_info_);
TransportSecurityState* security_state =
request_->context()->transport_security_state();
const SSLInfo& ssl_info = response_info_->ssl_info;
// Only accept HSTS headers on HTTPS connections that have no
// certificate errors.
if (!ssl_info.is_valid() || IsCertStatusError(ssl_info.cert_status) ||
!security_state) {
return;
}
// Don't accept HSTS headers when the hostname is an IP address.
if (request_info_.url.HostIsIPAddress())
return;
// http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec:
//
// If a UA receives more than one STS header field in a HTTP response
// message over secure transport, then the UA MUST process only the
// first such header field.
HttpResponseHeaders* headers = GetResponseHeaders();
std::string value;
if (headers->EnumerateHeader(nullptr, "Strict-Transport-Security", &value))
security_state->AddHSTSHeader(request_info_.url.host(), value);
}
void URLRequestHttpJob::ProcessPublicKeyPinsHeader() {
DCHECK(response_info_);
TransportSecurityState* security_state =
request_->context()->transport_security_state();
const SSLInfo& ssl_info = response_info_->ssl_info;
// Only accept HPKP headers on HTTPS connections that have no
// certificate errors.
if (!ssl_info.is_valid() || IsCertStatusError(ssl_info.cert_status) ||
!security_state) {
return;
}
// Don't accept HSTS headers when the hostname is an IP address.
if (request_info_.url.HostIsIPAddress())
return;
// http://tools.ietf.org/html/rfc7469:
//
// If a UA receives more than one PKP header field in an HTTP
// response message over secure transport, then the UA MUST process
// only the first such header field.
HttpResponseHeaders* headers = GetResponseHeaders();
std::string value;
if (headers->EnumerateHeader(nullptr, "Public-Key-Pins", &value))
security_state->AddHPKPHeader(request_info_.url.host(), value, ssl_info);
if (headers->EnumerateHeader(nullptr, "Public-Key-Pins-Report-Only",
&value)) {
security_state->ProcessHPKPReportOnlyHeader(
value, HostPortPair::FromURL(request_info_.url), ssl_info);
}
}
void URLRequestHttpJob::ProcessExpectCTHeader() {
DCHECK(response_info_);
TransportSecurityState* security_state =
request_->context()->transport_security_state();
const SSLInfo& ssl_info = response_info_->ssl_info;
// Only accept Expect CT headers on HTTPS connections that have no
// certificate errors.
if (!ssl_info.is_valid() || IsCertStatusError(ssl_info.cert_status) ||
!security_state) {
return;
}
// Only process the first Expect-CT header value.
HttpResponseHeaders* headers = GetResponseHeaders();
std::string value;
if (headers->EnumerateHeader(nullptr, "Expect-CT", &value)) {
security_state->ProcessExpectCTHeader(
value, HostPortPair::FromURL(request_info_.url), ssl_info);
}
}
void URLRequestHttpJob::OnStartCompleted(int result) {
TRACE_EVENT0(kNetTracingCategory, "URLRequestHttpJob::OnStartCompleted");
RecordTimer();
// If the job is done (due to cancellation), can just ignore this
// notification.
if (done_)
return;
receive_headers_end_ = base::TimeTicks::Now();
const URLRequestContext* context = request_->context();
if (result == OK) {
if (transaction_ && transaction_->GetResponseInfo()) {
SetProxyServer(transaction_->GetResponseInfo()->proxy_server);
}
scoped_refptr<HttpResponseHeaders> headers = GetResponseHeaders();
if (network_delegate()) {
// Note that |this| may not be deleted until
// |URLRequestHttpJob::OnHeadersReceivedCallback()| or
// |NetworkDelegate::URLRequestDestroyed()| has been called.
OnCallToDelegate();
allowed_unsafe_redirect_url_ = GURL();
// The NetworkDelegate must watch for OnRequestDestroyed and not modify
// any of the arguments or invoke the callback after it's called. Not
// using a WeakPtr here because it's not enough, the consumer has to watch
// for destruction regardless, due to the pointer parameters.
int error = network_delegate()->NotifyHeadersReceived(
request_, base::Bind(&URLRequestHttpJob::OnHeadersReceivedCallback,
base::Unretained(this)),
headers.get(), &override_response_headers_,
&allowed_unsafe_redirect_url_);
if (error != OK) {
if (error == ERR_IO_PENDING) {
awaiting_callback_ = true;
} else {
std::string source("delegate");
request_->net_log().AddEvent(
NetLogEventType::CANCELLED,
NetLog::StringCallback("source", &source));
OnCallToDelegateComplete();
NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, error));
}
return;
}
}
if (transaction_ && transaction_->GetResponseInfo()) {
LogChannelIDAndCookieStores(request_->url(), request_->context(),
transaction_->GetResponseInfo()->ssl_info);
}
SaveCookiesAndNotifyHeadersComplete(OK);
} else if (IsCertificateError(result)) {
// We encountered an SSL certificate error.
// Maybe overridable, maybe not. Ask the delegate to decide.
TransportSecurityState* state = context->transport_security_state();
NotifySSLCertificateError(
transaction_->GetResponseInfo()->ssl_info,
state->ShouldSSLErrorsBeFatal(request_info_.url.host()));
} else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
NotifyCertificateRequested(
transaction_->GetResponseInfo()->cert_request_info.get());
} else {
// Even on an error, there may be useful information in the response
// info (e.g. whether there's a cached copy).
if (transaction_.get())
response_info_ = transaction_->GetResponseInfo();
NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, result));
}
}
void URLRequestHttpJob::OnHeadersReceivedCallback(int result) {
awaiting_callback_ = false;
// Check that there are no callbacks to already canceled requests.
DCHECK_NE(URLRequestStatus::CANCELED, GetStatus().status());
SaveCookiesAndNotifyHeadersComplete(result);
}
void URLRequestHttpJob::OnReadCompleted(int result) {
TRACE_EVENT0(kNetTracingCategory, "URLRequestHttpJob::OnReadCompleted");
read_in_progress_ = false;
DCHECK_NE(ERR_IO_PENDING, result);
if (ShouldFixMismatchedContentLength(result))
result = OK;
// EOF or error, done with this job.
if (result <= 0)
DoneWithRequest(FINISHED);
ReadRawDataComplete(result);
}
void URLRequestHttpJob::RestartTransactionWithAuth(
const AuthCredentials& credentials) {
auth_credentials_ = credentials;
// These will be reset in OnStartCompleted.
response_info_ = NULL;
receive_headers_end_ = base::TimeTicks();
ResetTimer();
// Update the cookies, since the cookie store may have been updated from the
// headers in the 401/407. Since cookies were already appended to
// extra_headers, we need to strip them out before adding them again.
request_info_.extra_headers.RemoveHeader(HttpRequestHeaders::kCookie);
AddCookieHeaderAndStart();
}
void URLRequestHttpJob::SetUpload(UploadDataStream* upload) {
DCHECK(!transaction_.get()) << "cannot change once started";
request_info_.upload_data_stream = upload;
}
void URLRequestHttpJob::SetExtraRequestHeaders(
const HttpRequestHeaders& headers) {
DCHECK(!transaction_.get()) << "cannot change once started";
request_info_.extra_headers.CopyFrom(headers);
}
LoadState URLRequestHttpJob::GetLoadState() const {
return transaction_.get() ?
transaction_->GetLoadState() : LOAD_STATE_IDLE;
}
bool URLRequestHttpJob::GetMimeType(std::string* mime_type) const {
DCHECK(transaction_.get());
if (!response_info_)
return false;
HttpResponseHeaders* headers = GetResponseHeaders();
if (!headers)
return false;