forked from sanyaade-mobiledev/chromium.src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurl_request_http_job.cc
1510 lines (1282 loc) · 50.9 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 "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_util.h"
#include "base/file_version_info.h"
#include "base/message_loop.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "base/time.h"
#include "net/base/cert_status_flags.h"
#include "net/base/filter.h"
#include "net/base/host_port_pair.h"
#include "net/base/load_flags.h"
#include "net/base/mime_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/base/network_delegate.h"
#include "net/base/sdch_manager.h"
#include "net/base/ssl_cert_request_info.h"
#include "net/base/ssl_config_service.h"
#include "net/cookies/cookie_monster.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_delegate.h"
#include "net/http/http_transaction_factory.h"
#include "net/http/http_util.h"
#include "net/url_request/fraudulent_certificate_reporter.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_redirect_job.h"
#include "net/url_request/url_request_throttler_header_adapter.h"
#include "net/url_request/url_request_throttler_manager.h"
static const char kAvailDictionaryHeader[] = "Avail-Dictionary";
namespace net {
class URLRequestHttpJob::HttpFilterContext : public FilterContext {
public:
explicit HttpFilterContext(URLRequestHttpJob* job);
virtual ~HttpFilterContext();
// FilterContext implementation.
virtual bool GetMimeType(std::string* mime_type) const OVERRIDE;
virtual bool GetURL(GURL* gurl) const OVERRIDE;
virtual base::Time GetRequestTime() const OVERRIDE;
virtual bool IsCachedContent() const OVERRIDE;
virtual bool IsDownload() const OVERRIDE;
virtual bool IsSdchResponse() const OVERRIDE;
virtual int64 GetByteReadCount() const OVERRIDE;
virtual int GetResponseCode() const OVERRIDE;
virtual void RecordPacketStats(StatisticSelector statistic) const OVERRIDE;
// Method to allow us to reset filter context for a response that should have
// been SDCH encoded when there is an update due to an explicit HTTP header.
void ResetSdchResponseToFalse();
private:
URLRequestHttpJob* job_;
DISALLOW_COPY_AND_ASSIGN(HttpFilterContext);
};
class URLRequestHttpJob::HttpTransactionDelegateImpl
: public HttpTransactionDelegate {
public:
explicit HttpTransactionDelegateImpl(URLRequest* request)
: request_(request),
network_delegate_(request->context()->network_delegate()),
cache_active_(false),
network_active_(false) {
}
virtual ~HttpTransactionDelegateImpl() {
OnDetachRequest();
}
void OnDetachRequest() {
if (request_ == NULL || network_delegate_ == NULL)
return;
network_delegate_->NotifyRequestWaitStateChange(
*request_,
NetworkDelegate::REQUEST_WAIT_STATE_RESET);
cache_active_ = false;
network_active_ = false;
request_ = NULL;
}
virtual void OnCacheActionStart() OVERRIDE {
if (request_ == NULL || network_delegate_ == NULL)
return;
DCHECK(!cache_active_ && !network_active_);
cache_active_ = true;
network_delegate_->NotifyRequestWaitStateChange(
*request_,
NetworkDelegate::REQUEST_WAIT_STATE_CACHE_START);
}
virtual void OnCacheActionFinish() OVERRIDE {
if (request_ == NULL || network_delegate_ == NULL)
return;
DCHECK(cache_active_ && !network_active_);
cache_active_ = false;
network_delegate_->NotifyRequestWaitStateChange(
*request_,
NetworkDelegate::REQUEST_WAIT_STATE_CACHE_FINISH);
}
virtual void OnNetworkActionStart() OVERRIDE {
if (request_ == NULL || network_delegate_ == NULL)
return;
DCHECK(!cache_active_ && !network_active_);
network_active_ = true;
network_delegate_->NotifyRequestWaitStateChange(
*request_,
NetworkDelegate::REQUEST_WAIT_STATE_NETWORK_START);
}
virtual void OnNetworkActionFinish() OVERRIDE {
if (request_ == NULL || network_delegate_ == NULL)
return;
DCHECK(!cache_active_ && network_active_);
network_active_ = false;
network_delegate_->NotifyRequestWaitStateChange(
*request_,
NetworkDelegate::REQUEST_WAIT_STATE_NETWORK_FINISH);
}
private:
URLRequest* request_;
NetworkDelegate* network_delegate_;
bool cache_active_;
bool network_active_;
};
URLRequestHttpJob::HttpFilterContext::HttpFilterContext(URLRequestHttpJob* job)
: job_(job) {
DCHECK(job_);
}
URLRequestHttpJob::HttpFilterContext::~HttpFilterContext() {
}
bool URLRequestHttpJob::HttpFilterContext::GetMimeType(
std::string* mime_type) const {
return job_->GetMimeType(mime_type);
}
bool URLRequestHttpJob::HttpFilterContext::GetURL(GURL* gurl) const {
if (!job_->request())
return false;
*gurl = job_->request()->url();
return true;
}
base::Time URLRequestHttpJob::HttpFilterContext::GetRequestTime() const {
return job_->request() ? job_->request()->request_time() : base::Time();
}
bool URLRequestHttpJob::HttpFilterContext::IsCachedContent() const {
return job_->is_cached_content_;
}
bool URLRequestHttpJob::HttpFilterContext::IsDownload() const {
return (job_->request_info_.load_flags & LOAD_IS_DOWNLOAD) != 0;
}
void URLRequestHttpJob::HttpFilterContext::ResetSdchResponseToFalse() {
DCHECK(job_->sdch_dictionary_advertised_);
job_->sdch_dictionary_advertised_ = false;
}
bool URLRequestHttpJob::HttpFilterContext::IsSdchResponse() const {
return job_->sdch_dictionary_advertised_;
}
int64 URLRequestHttpJob::HttpFilterContext::GetByteReadCount() const {
return job_->filter_input_byte_count();
}
int URLRequestHttpJob::HttpFilterContext::GetResponseCode() const {
return job_->GetResponseCode();
}
void URLRequestHttpJob::HttpFilterContext::RecordPacketStats(
StatisticSelector statistic) const {
job_->RecordPacketStats(statistic);
}
// 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");
if (!request->context()->http_transaction_factory()) {
NOTREACHED() << "requires a valid context";
return new URLRequestErrorJob(
request, network_delegate, ERR_INVALID_ARGUMENT);
}
GURL redirect_url;
if (request->GetHSTSRedirect(&redirect_url))
return new URLRequestRedirectJob(request, network_delegate, redirect_url);
return new URLRequestHttpJob(request, network_delegate);
}
URLRequestHttpJob::URLRequestHttpJob(URLRequest* request,
NetworkDelegate* network_delegate)
: URLRequestJob(request, network_delegate),
response_info_(NULL),
response_cookies_save_index_(0),
proxy_auth_state_(AUTH_STATE_DONT_NEED_AUTH),
server_auth_state_(AUTH_STATE_DONT_NEED_AUTH),
ALLOW_THIS_IN_INITIALIZER_LIST(start_callback_(
base::Bind(&URLRequestHttpJob::OnStartCompleted,
base::Unretained(this)))),
ALLOW_THIS_IN_INITIALIZER_LIST(notify_before_headers_sent_callback_(
base::Bind(&URLRequestHttpJob::NotifyBeforeSendHeadersCallback,
base::Unretained(this)))),
read_in_progress_(false),
transaction_(NULL),
throttling_entry_(NULL),
sdch_dictionary_advertised_(false),
sdch_test_activated_(false),
sdch_test_control_(false),
is_cached_content_(false),
request_creation_time_(),
packet_timing_enabled_(false),
done_(false),
bytes_observed_in_packets_(0),
request_time_snapshot_(),
final_packet_time_(),
ALLOW_THIS_IN_INITIALIZER_LIST(
filter_context_(new HttpFilterContext(this))),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(on_headers_received_callback_(
base::Bind(&URLRequestHttpJob::OnHeadersReceivedCallback,
base::Unretained(this)))),
awaiting_callback_(false),
http_transaction_delegate_(new HttpTransactionDelegateImpl(request)) {
URLRequestThrottlerManager* manager = request->context()->throttler_manager();
if (manager)
throttling_entry_ = manager->RegisterRequestUrl(request->url());
ResetTimer();
}
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_) {
URLRequestThrottlerHeaderAdapter response_adapter(GetResponseHeaders());
throttling_entry_->UpdateWithResponse(request_info_.url.host(),
&response_adapter);
}
// The ordering of these calls is not important.
ProcessStrictTransportSecurityHeader();
ProcessPublicKeyPinsHeader();
if (SdchManager::Global() &&
SdchManager::Global()->IsInSupportedDomain(request_->url())) {
const std::string name = "Get-Dictionary";
std::string url_text;
void* iter = NULL;
// 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)) {
// request_->url() won't be valid in the destructor, so we use an
// alternate copy.
DCHECK_EQ(request_->url(), request_info_.url);
// Resolve suggested URL relative to request url.
sdch_dictionary_url_ = request_info_.url.Resolve(url_text);
}
}
// 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 OnBeforeSendHeaders -> OnSendHeaders -> OnBeforeSendHeaders
// occurs.
RestartTransactionWithAuth(AuthCredentials());
return;
}
URLRequestJob::NotifyHeadersComplete();
}
void URLRequestHttpJob::NotifyDone(const URLRequestStatus& status) {
DoneWithRequest(FINISHED);
URLRequestJob::NotifyDone(status);
}
void URLRequestHttpJob::DestroyTransaction() {
DCHECK(transaction_.get());
DoneWithRequest(ABORTED);
transaction_.reset();
response_info_ = NULL;
}
void URLRequestHttpJob::StartTransaction() {
if (request_->context()->network_delegate()) {
int rv = request_->context()->network_delegate()->NotifyBeforeSendHeaders(
request_, notify_before_headers_sent_callback_,
&request_info_.extra_headers);
// If an extension blocks the request, we rely on the callback to
// StartTransactionInternal().
if (rv == ERR_IO_PENDING) {
SetBlockedOnDelegate();
return;
}
}
StartTransactionInternal();
}
void URLRequestHttpJob::NotifyBeforeSendHeadersCallback(int result) {
SetUnblockedOnDelegate();
// Check that there are no callbacks to already canceled requests.
DCHECK_NE(URLRequestStatus::CANCELED, GetStatus().status());
if (result == OK) {
StartTransactionInternal();
} else {
std::string source("delegate");
request_->net_log().AddEvent(NetLog::TYPE_CANCELLED,
NetLog::StringCallback("source", &source));
NotifyCanceled();
}
}
void URLRequestHttpJob::StartTransactionInternal() {
// 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;
if (request_->context()->network_delegate()) {
request_->context()->network_delegate()->NotifySendHeaders(
request_, request_info_.extra_headers);
}
if (transaction_.get()) {
rv = transaction_->RestartWithAuth(auth_credentials_, start_callback_);
auth_credentials_ = AuthCredentials();
} else {
DCHECK(request_->context()->http_transaction_factory());
rv = request_->context()->http_transaction_factory()->CreateTransaction(
&transaction_, http_transaction_delegate_.get());
if (rv == OK) {
if (!throttling_entry_ ||
!throttling_entry_->ShouldRejectRequest(*request_)) {
rv = transaction_->Start(
&request_info_, start_callback_, 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.
MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&URLRequestHttpJob::OnStartCompleted,
weak_factory_.GetWeakPtr(), rv));
}
void URLRequestHttpJob::AddExtraHeaders() {
// 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)) {
bool advertise_sdch = SdchManager::Global() &&
SdchManager::Global()->IsInSupportedDomain(request_->url());
std::string avail_dictionaries;
if (advertise_sdch) {
SdchManager::Global()->GetAvailDictionaryList(request_->url(),
&avail_dictionaries);
// 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 (!avail_dictionaries.empty() &&
SdchManager::Global()->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.
advertise_sdch = false;
} else {
sdch_test_activated_ = 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.
if (!advertise_sdch) {
// Tell the server what compression formats we support (other than SDCH).
request_info_.extra_headers.SetHeader(
HttpRequestHeaders::kAcceptEncoding, "gzip,deflate");
} else {
// Include SDCH in acceptable list.
request_info_.extra_headers.SetHeader(
HttpRequestHeaders::kAcceptEncoding, "gzip,deflate,sdch");
if (!avail_dictionaries.empty()) {
request_info_.extra_headers.SetHeader(
kAvailDictionaryHeader,
avail_dictionaries);
sdch_dictionary_advertised_ = true;
// 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;
}
}
}
const URLRequestContext* context = request_->context();
// Only add default Accept-Language and Accept-Charset if the request
// didn't have them specified.
if (!context->accept_language().empty()) {
request_info_.extra_headers.SetHeaderIfMissing(
HttpRequestHeaders::kAcceptLanguage,
context->accept_language());
}
if (!context->accept_charset().empty()) {
request_info_.extra_headers.SetHeaderIfMissing(
HttpRequestHeaders::kAcceptCharset,
context->accept_charset());
}
}
void URLRequestHttpJob::AddCookieHeaderAndStart() {
// No matter what, we want to report our status as IO pending since we will
// be notifying our consumer asynchronously via OnStartCompleted.
SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
// If the request was destroyed, then there is no more work to do.
if (!request_)
return;
CookieStore* cookie_store = request_->context()->cookie_store();
if (cookie_store && !(request_info_.load_flags & LOAD_DO_NOT_SEND_COOKIES)) {
net::CookieMonster* cookie_monster = cookie_store->GetCookieMonster();
if (cookie_monster) {
cookie_monster->GetAllCookiesForURLAsync(
request_->url(),
base::Bind(&URLRequestHttpJob::CheckCookiePolicyAndLoad,
weak_factory_.GetWeakPtr()));
} else {
DoLoadCookies();
}
} else {
DoStartTransaction();
}
}
void URLRequestHttpJob::DoLoadCookies() {
CookieOptions options;
options.set_include_httponly();
request_->context()->cookie_store()->GetCookiesWithInfoAsync(
request_->url(), options,
base::Bind(&URLRequestHttpJob::OnCookiesLoaded,
weak_factory_.GetWeakPtr()));
}
void URLRequestHttpJob::CheckCookiePolicyAndLoad(
const CookieList& cookie_list) {
if (CanGetCookies(cookie_list))
DoLoadCookies();
else
DoStartTransaction();
}
void URLRequestHttpJob::OnCookiesLoaded(
const std::string& cookie_line,
const std::vector<net::CookieStore::CookieInfo>& cookie_infos) {
if (!cookie_line.empty()) {
request_info_.extra_headers.SetHeader(
HttpRequestHeaders::kCookie, cookie_line);
}
DoStartTransaction();
}
void URLRequestHttpJob::DoStartTransaction() {
// We may have been canceled while retrieving cookies.
if (GetStatus().is_success()) {
StartTransaction();
} else {
NotifyCanceled();
}
}
void URLRequestHttpJob::SaveCookiesAndNotifyHeadersComplete(int result) {
if (result != net::OK) {
std::string source("delegate");
request_->net_log().AddEvent(NetLog::TYPE_CANCELLED,
NetLog::StringCallback("source", &source));
NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, result));
return;
}
DCHECK(transaction_.get());
const HttpResponseInfo* response_info = transaction_->GetResponseInfo();
DCHECK(response_info);
response_cookies_.clear();
response_cookies_save_index_ = 0;
FetchResponseCookies(&response_cookies_);
if (!GetResponseHeaders()->GetDateValue(&response_date_))
response_date_ = base::Time();
// Now, loop over the response cookies, and attempt to persist each.
SaveNextCookie();
}
// If the save occurs synchronously, SaveNextCookie will loop and save the next
// cookie. If the save is deferred, the callback is responsible for continuing
// to iterate through the cookies.
// TODO(erikwright): Modify the CookieStore API to indicate via return value
// whether it completed synchronously or asynchronously.
// See http://crbug.com/131066.
void URLRequestHttpJob::SaveNextCookie() {
// No matter what, we want to report our status as IO pending since we will
// be notifying our consumer asynchronously via OnStartCompleted.
SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
// Used to communicate with the callback. See the implementation of
// OnCookieSaved.
scoped_refptr<SharedBoolean> callback_pending = new SharedBoolean(false);
scoped_refptr<SharedBoolean> save_next_cookie_running =
new SharedBoolean(true);
if (!(request_info_.load_flags & LOAD_DO_NOT_SAVE_COOKIES) &&
request_->context()->cookie_store() &&
response_cookies_.size() > 0) {
CookieOptions options;
options.set_include_httponly();
options.set_server_time(response_date_);
net::CookieStore::SetCookiesCallback callback(
base::Bind(&URLRequestHttpJob::OnCookieSaved,
weak_factory_.GetWeakPtr(),
save_next_cookie_running,
callback_pending));
// Loop through the cookies as long as SetCookieWithOptionsAsync completes
// synchronously.
while (!callback_pending->data &&
response_cookies_save_index_ < response_cookies_.size()) {
if (CanSetCookie(
response_cookies_[response_cookies_save_index_], &options)) {
callback_pending->data = true;
request_->context()->cookie_store()->SetCookieWithOptionsAsync(
request_->url(), response_cookies_[response_cookies_save_index_],
options, callback);
}
++response_cookies_save_index_;
}
}
save_next_cookie_running->data = false;
if (!callback_pending->data) {
response_cookies_.clear();
response_cookies_save_index_ = 0;
SetStatus(URLRequestStatus()); // Clear the IO_PENDING status
NotifyHeadersComplete();
return;
}
}
// |save_next_cookie_running| is true when the callback is bound and set to
// false when SaveNextCookie exits, allowing the callback to determine if the
// save occurred synchronously or asynchronously.
// |callback_pending| is false when the callback is invoked and will be set to
// true by the callback, allowing SaveNextCookie to detect whether the save
// occurred synchronously.
// See SaveNextCookie() for more information.
void URLRequestHttpJob::OnCookieSaved(
scoped_refptr<SharedBoolean> save_next_cookie_running,
scoped_refptr<SharedBoolean> callback_pending,
bool cookie_status) {
callback_pending->data = false;
// If we were called synchronously, return.
if (save_next_cookie_running->data) {
return;
}
// We were called asynchronously, so trigger the next save.
// We may have been canceled within OnSetCookie.
if (GetStatus().is_success()) {
SaveNextCookie();
} else {
NotifyCanceled();
}
}
void URLRequestHttpJob::FetchResponseCookies(
std::vector<std::string>* cookies) {
const std::string name = "Set-Cookie";
std::string value;
void* iter = NULL;
HttpResponseHeaders* headers = GetResponseHeaders();
while (headers->EnumerateHeader(&iter, name, &value)) {
if (!value.empty())
cookies->push_back(value);
}
}
// NOTE: |ProcessStrictTransportSecurityHeader| and
// |ProcessPublicKeyPinsHeader| have very similar structures, by design.
// They manipulate different parts of |TransportSecurityState::DomainState|,
// and they must remain complementary. If, in future changes here, there is
// any conflict between their policies (such as in |domain_state.mode|), you
// should resolve the conflict in favor of the more strict policy.
void URLRequestHttpJob::ProcessStrictTransportSecurityHeader() {
DCHECK(response_info_);
const URLRequestContext* ctx = request_->context();
const SSLInfo& ssl_info = response_info_->ssl_info;
// Only accept strict transport security headers on HTTPS connections that
// have no certificate errors.
if (!ssl_info.is_valid() || IsCertStatusError(ssl_info.cert_status) ||
!ctx->transport_security_state()) {
return;
}
TransportSecurityState* security_state = ctx->transport_security_state();
TransportSecurityState::DomainState domain_state;
const std::string& host = request_info_.url.host();
bool sni_available =
SSLConfigService::IsSNIAvailable(ctx->ssl_config_service());
if (!security_state->GetDomainState(host, sni_available, &domain_state))
// |GetDomainState| may have altered |domain_state| while searching. If
// not found, start with a fresh state.
domain_state.upgrade_mode =
TransportSecurityState::DomainState::MODE_FORCE_HTTPS;
HttpResponseHeaders* headers = GetResponseHeaders();
std::string value;
void* iter = NULL;
base::Time now = base::Time::Now();
while (headers->EnumerateHeader(&iter, "Strict-Transport-Security", &value)) {
TransportSecurityState::DomainState domain_state;
if (domain_state.ParseSTSHeader(now, value))
security_state->EnableHost(host, domain_state);
}
}
void URLRequestHttpJob::ProcessPublicKeyPinsHeader() {
DCHECK(response_info_);
const URLRequestContext* ctx = request_->context();
const SSLInfo& ssl_info = response_info_->ssl_info;
// Only accept public key pins headers on HTTPS connections that have no
// certificate errors.
if (!ssl_info.is_valid() || IsCertStatusError(ssl_info.cert_status) ||
!ctx->transport_security_state()) {
return;
}
TransportSecurityState* security_state = ctx->transport_security_state();
TransportSecurityState::DomainState domain_state;
const std::string& host = request_info_.url.host();
bool sni_available =
SSLConfigService::IsSNIAvailable(ctx->ssl_config_service());
if (!security_state->GetDomainState(host, sni_available, &domain_state))
// |GetDomainState| may have altered |domain_state| while searching. If
// not found, start with a fresh state.
domain_state.upgrade_mode =
TransportSecurityState::DomainState::MODE_DEFAULT;
HttpResponseHeaders* headers = GetResponseHeaders();
void* iter = NULL;
std::string value;
base::Time now = base::Time::Now();
while (headers->EnumerateHeader(&iter, "Public-Key-Pins", &value)) {
// Note that ParsePinsHeader updates |domain_state| (iff the header parses
// correctly), but does not completely overwrite it. It just updates the
// dynamic pinning metadata.
if (domain_state.ParsePinsHeader(now, value, ssl_info))
security_state->EnableHost(host, domain_state);
}
}
void URLRequestHttpJob::OnStartCompleted(int result) {
RecordTimer();
// If the request was destroyed, then there is no more work to do.
if (!request_)
return;
// If the transaction was destroyed, then the job was cancelled, and
// we can just ignore this notification.
if (!transaction_.get())
return;
// Clear the IO_PENDING status
SetStatus(URLRequestStatus());
const URLRequestContext* context = request_->context();
if (result == ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN &&
transaction_->GetResponseInfo() != NULL) {
FraudulentCertificateReporter* reporter =
context->fraudulent_certificate_reporter();
if (reporter != NULL) {
const SSLInfo& ssl_info = transaction_->GetResponseInfo()->ssl_info;
bool sni_available = SSLConfigService::IsSNIAvailable(
context->ssl_config_service());
const std::string& host = request_->url().host();
reporter->SendReport(host, ssl_info, sni_available);
}
}
if (result == OK) {
scoped_refptr<HttpResponseHeaders> headers = GetResponseHeaders();
if (context->network_delegate()) {
// Note that |this| may not be deleted until
// |on_headers_received_callback_| or
// |NetworkDelegate::URLRequestDestroyed()| has been called.
int error = context->network_delegate()->
NotifyHeadersReceived(request_, on_headers_received_callback_,
headers, &override_response_headers_);
if (error != net::OK) {
if (error == net::ERR_IO_PENDING) {
awaiting_callback_ = true;
request_->net_log().BeginEvent(
NetLog::TYPE_URL_REQUEST_BLOCKED_ON_DELEGATE);
} else {
std::string source("delegate");
request_->net_log().AddEvent(NetLog::TYPE_CANCELLED,
NetLog::StringCallback("source",
&source));
NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, error));
}
return;
}
}
SaveCookiesAndNotifyHeadersComplete(net::OK);
} else if (IsCertificateError(result)) {
// We encountered an SSL certificate error. Ask our delegate to decide
// what we should do.
TransportSecurityState::DomainState domain_state;
const URLRequestContext* context = request_->context();
const bool fatal =
context->transport_security_state() &&
context->transport_security_state()->GetDomainState(
request_info_.url.host(),
SSLConfigService::IsSNIAvailable(context->ssl_config_service()),
&domain_state);
NotifySSLCertificateError(transaction_->GetResponseInfo()->ssl_info, fatal);
} else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
NotifyCertificateRequested(
transaction_->GetResponseInfo()->cert_request_info);
} else {
NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, result));
}
}
void URLRequestHttpJob::OnHeadersReceivedCallback(int result) {
request_->net_log().EndEvent(NetLog::TYPE_URL_REQUEST_BLOCKED_ON_DELEGATE);
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) {
read_in_progress_ = false;
if (ShouldFixMismatchedContentLength(result))
result = OK;
if (result == OK) {
NotifyDone(URLRequestStatus());
} else if (result < 0) {
NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, result));
} else {
// Clear the IO_PENDING status
SetStatus(URLRequestStatus());
}
NotifyReadComplete(result);
}
void URLRequestHttpJob::RestartTransactionWithAuth(
const AuthCredentials& credentials) {
auth_credentials_ = credentials;
// These will be reset in OnStartCompleted.
response_info_ = NULL;
response_cookies_.clear();
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(UploadData* upload) {
DCHECK(!transaction_.get()) << "cannot change once started";
request_info_.upload_data = upload;
}
void URLRequestHttpJob::SetExtraRequestHeaders(
const HttpRequestHeaders& headers) {
DCHECK(!transaction_.get()) << "cannot change once started";
request_info_.extra_headers.CopyFrom(headers);
}
void URLRequestHttpJob::Start() {
DCHECK(!transaction_.get());
// Ensure that we do not send username and password fields in the referrer.
GURL referrer(request_->GetSanitizedReferrer());
request_info_.url = request_->url();
request_info_.method = request_->method();
request_info_.load_flags = request_->load_flags();
request_info_.priority = request_->priority();
request_info_.request_id = request_->identifier();
// 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_.extra_headers.SetHeaderIfMissing(
HttpRequestHeaders::kUserAgent,
request_->context()->GetUserAgent(request_->url()));
AddExtraHeaders();
AddCookieHeaderAndStart();
}
void URLRequestHttpJob::Kill() {
http_transaction_delegate_->OnDetachRequest();
if (!transaction_.get())
return;
weak_factory_.InvalidateWeakPtrs();
DestroyTransaction();
URLRequestJob::Kill();
}
LoadState URLRequestHttpJob::GetLoadState() const {
return transaction_.get() ?
transaction_->GetLoadState() : LOAD_STATE_IDLE;
}
UploadProgress URLRequestHttpJob::GetUploadProgress() const {
return transaction_.get() ?
transaction_->GetUploadProgress() : UploadProgress();
}
bool URLRequestHttpJob::GetMimeType(std::string* mime_type) const {
DCHECK(transaction_.get());
if (!response_info_)
return false;
return GetResponseHeaders()->GetMimeType(mime_type);
}
bool URLRequestHttpJob::GetCharset(std::string* charset) {
DCHECK(transaction_.get());
if (!response_info_)
return false;
return GetResponseHeaders()->GetCharset(charset);
}
void URLRequestHttpJob::GetResponseInfo(HttpResponseInfo* info) {
DCHECK(request_);
DCHECK(transaction_.get());
if (response_info_) {
*info = *response_info_;
if (override_response_headers_)
info->headers = override_response_headers_;
}
}
bool URLRequestHttpJob::GetResponseCookies(std::vector<std::string>* cookies) {
DCHECK(transaction_.get());
if (!response_info_)
return false;
// TODO(darin): Why are we extracting response cookies again? Perhaps we
// should just leverage response_cookies_.
cookies->clear();
FetchResponseCookies(cookies);
return true;
}
int URLRequestHttpJob::GetResponseCode() const {
DCHECK(transaction_.get());
if (!response_info_)
return -1;
return GetResponseHeaders()->response_code();
}
Filter* URLRequestHttpJob::SetupFilter() const {
DCHECK(transaction_.get());
if (!response_info_)
return NULL;
std::vector<Filter::FilterType> encoding_types;
std::string encoding_type;
HttpResponseHeaders* headers = GetResponseHeaders();
void* iter = NULL;
while (headers->EnumerateHeader(&iter, "Content-Encoding", &encoding_type)) {
encoding_types.push_back(Filter::ConvertEncodingToType(encoding_type));
}
if (filter_context_->IsSdchResponse()) {
// We are wary of proxies that discard or damage SDCH encoding. If a server