1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/url_request/url_request_http_job.h"
7 #include "base/base_switches.h"
9 #include "base/bind_helpers.h"
10 #include "base/command_line.h"
11 #include "base/compiler_specific.h"
12 #include "base/file_version_info.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/field_trial.h"
15 #include "base/metrics/histogram.h"
16 #include "base/profiler/scoped_tracker.h"
17 #include "base/rand_util.h"
18 #include "base/strings/string_util.h"
19 #include "base/time/time.h"
20 #include "net/base/host_port_pair.h"
21 #include "net/base/load_flags.h"
22 #include "net/base/net_errors.h"
23 #include "net/base/net_util.h"
24 #include "net/base/network_delegate.h"
25 #include "net/base/sdch_manager.h"
26 #include "net/base/sdch_net_log_params.h"
27 #include "net/cert/cert_status_flags.h"
28 #include "net/cookies/cookie_store.h"
29 #include "net/http/http_content_disposition.h"
30 #include "net/http/http_network_session.h"
31 #include "net/http/http_request_headers.h"
32 #include "net/http/http_response_headers.h"
33 #include "net/http/http_response_info.h"
34 #include "net/http/http_status_code.h"
35 #include "net/http/http_transaction.h"
36 #include "net/http/http_transaction_factory.h"
37 #include "net/http/http_util.h"
38 #include "net/proxy/proxy_info.h"
39 #include "net/ssl/ssl_cert_request_info.h"
40 #include "net/ssl/ssl_config_service.h"
41 #include "net/url_request/fraudulent_certificate_reporter.h"
42 #include "net/url_request/http_user_agent_settings.h"
43 #include "net/url_request/url_request.h"
44 #include "net/url_request/url_request_context.h"
45 #include "net/url_request/url_request_error_job.h"
46 #include "net/url_request/url_request_job_factory.h"
47 #include "net/url_request/url_request_redirect_job.h"
48 #include "net/url_request/url_request_throttler_header_adapter.h"
49 #include "net/url_request/url_request_throttler_manager.h"
50 #include "net/websockets/websocket_handshake_stream_base.h"
52 static const char kAvailDictionaryHeader
[] = "Avail-Dictionary";
56 class URLRequestHttpJob::HttpFilterContext
: public FilterContext
{
58 explicit HttpFilterContext(URLRequestHttpJob
* job
);
59 ~HttpFilterContext() override
;
61 // FilterContext implementation.
62 bool GetMimeType(std::string
* mime_type
) const override
;
63 bool GetURL(GURL
* gurl
) const override
;
64 base::Time
GetRequestTime() const override
;
65 bool IsCachedContent() const override
;
66 SdchManager::DictionarySet
* SdchDictionariesAdvertised() const override
;
67 int64
GetByteReadCount() const override
;
68 int GetResponseCode() const override
;
69 const URLRequestContext
* GetURLRequestContext() const override
;
70 void RecordPacketStats(StatisticSelector statistic
) const override
;
71 const BoundNetLog
& GetNetLog() const override
;
74 URLRequestHttpJob
* job_
;
76 // URLRequestHttpJob may be detached from URLRequest, but we still need to
78 BoundNetLog dummy_log_
;
80 DISALLOW_COPY_AND_ASSIGN(HttpFilterContext
);
83 URLRequestHttpJob::HttpFilterContext::HttpFilterContext(URLRequestHttpJob
* job
)
88 URLRequestHttpJob::HttpFilterContext::~HttpFilterContext() {
91 bool URLRequestHttpJob::HttpFilterContext::GetMimeType(
92 std::string
* mime_type
) const {
93 return job_
->GetMimeType(mime_type
);
96 bool URLRequestHttpJob::HttpFilterContext::GetURL(GURL
* gurl
) const {
99 *gurl
= job_
->request()->url();
103 base::Time
URLRequestHttpJob::HttpFilterContext::GetRequestTime() const {
104 return job_
->request() ? job_
->request()->request_time() : base::Time();
107 bool URLRequestHttpJob::HttpFilterContext::IsCachedContent() const {
108 return job_
->is_cached_content_
;
111 SdchManager::DictionarySet
*
112 URLRequestHttpJob::HttpFilterContext::SdchDictionariesAdvertised() const {
113 return job_
->dictionaries_advertised_
.get();
116 int64
URLRequestHttpJob::HttpFilterContext::GetByteReadCount() const {
117 return job_
->prefilter_bytes_read();
120 int URLRequestHttpJob::HttpFilterContext::GetResponseCode() const {
121 return job_
->GetResponseCode();
124 const URLRequestContext
*
125 URLRequestHttpJob::HttpFilterContext::GetURLRequestContext() const {
126 return job_
->request() ? job_
->request()->context() : NULL
;
129 void URLRequestHttpJob::HttpFilterContext::RecordPacketStats(
130 StatisticSelector statistic
) const {
131 job_
->RecordPacketStats(statistic
);
134 const BoundNetLog
& URLRequestHttpJob::HttpFilterContext::GetNetLog() const {
135 return job_
->request() ? job_
->request()->net_log() : dummy_log_
;
138 // TODO(darin): make sure the port blocking code is not lost
140 URLRequestJob
* URLRequestHttpJob::Factory(URLRequest
* request
,
141 NetworkDelegate
* network_delegate
,
142 const std::string
& scheme
) {
143 DCHECK(scheme
== "http" || scheme
== "https" || scheme
== "ws" ||
146 if (!request
->context()->http_transaction_factory()) {
147 NOTREACHED() << "requires a valid context";
148 return new URLRequestErrorJob(
149 request
, network_delegate
, ERR_INVALID_ARGUMENT
);
153 if (request
->GetHSTSRedirect(&redirect_url
)) {
154 return new URLRequestRedirectJob(
155 request
, network_delegate
, redirect_url
,
156 // Use status code 307 to preserve the method, so POST requests work.
157 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT
, "HSTS");
159 return new URLRequestHttpJob(request
,
161 request
->context()->http_user_agent_settings());
164 URLRequestHttpJob::URLRequestHttpJob(
166 NetworkDelegate
* network_delegate
,
167 const HttpUserAgentSettings
* http_user_agent_settings
)
168 : URLRequestJob(request
, network_delegate
),
169 priority_(DEFAULT_PRIORITY
),
170 response_info_(NULL
),
171 response_cookies_save_index_(0),
172 proxy_auth_state_(AUTH_STATE_DONT_NEED_AUTH
),
173 server_auth_state_(AUTH_STATE_DONT_NEED_AUTH
),
174 start_callback_(base::Bind(&URLRequestHttpJob::OnStartCompleted
,
175 base::Unretained(this))),
176 notify_before_headers_sent_callback_(
177 base::Bind(&URLRequestHttpJob::NotifyBeforeSendHeadersCallback
,
178 base::Unretained(this))),
179 read_in_progress_(false),
180 throttling_entry_(NULL
),
181 sdch_test_activated_(false),
182 sdch_test_control_(false),
183 is_cached_content_(false),
184 request_creation_time_(),
185 packet_timing_enabled_(false),
187 bytes_observed_in_packets_(0),
188 request_time_snapshot_(),
189 final_packet_time_(),
190 filter_context_(new HttpFilterContext(this)),
191 on_headers_received_callback_(
192 base::Bind(&URLRequestHttpJob::OnHeadersReceivedCallback
,
193 base::Unretained(this))),
194 awaiting_callback_(false),
195 http_user_agent_settings_(http_user_agent_settings
),
196 weak_factory_(this) {
197 URLRequestThrottlerManager
* manager
= request
->context()->throttler_manager();
199 throttling_entry_
= manager
->RegisterRequestUrl(request
->url());
204 URLRequestHttpJob::~URLRequestHttpJob() {
205 CHECK(!awaiting_callback_
);
207 DCHECK(!sdch_test_control_
|| !sdch_test_activated_
);
208 if (!is_cached_content_
) {
209 if (sdch_test_control_
)
210 RecordPacketStats(FilterContext::SDCH_EXPERIMENT_HOLDBACK
);
211 if (sdch_test_activated_
)
212 RecordPacketStats(FilterContext::SDCH_EXPERIMENT_DECODE
);
214 // Make sure SDCH filters are told to emit histogram data while
215 // filter_context_ is still alive.
218 DoneWithRequest(ABORTED
);
221 void URLRequestHttpJob::SetPriority(RequestPriority priority
) {
222 priority_
= priority
;
224 transaction_
->SetPriority(priority_
);
227 void URLRequestHttpJob::Start() {
228 // TODO(mmenke): Remove ScopedTracker below once crbug.com/456327 is fixed.
229 tracked_objects::ScopedTracker
tracking_profile(
230 FROM_HERE_WITH_EXPLICIT_FUNCTION("456327 URLRequestHttpJob::Start"));
232 DCHECK(!transaction_
.get());
234 // URLRequest::SetReferrer ensures that we do not send username and password
235 // fields in the referrer.
236 GURL
referrer(request_
->referrer());
238 request_info_
.url
= request_
->url();
239 request_info_
.method
= request_
->method();
240 request_info_
.load_flags
= request_
->load_flags();
241 // Enable privacy mode if cookie settings or flags tell us not send or
243 bool enable_privacy_mode
=
244 (request_info_
.load_flags
& LOAD_DO_NOT_SEND_COOKIES
) ||
245 (request_info_
.load_flags
& LOAD_DO_NOT_SAVE_COOKIES
) ||
246 CanEnablePrivacyMode();
247 // Privacy mode could still be disabled in OnCookiesLoaded if we are going
248 // to send previously saved cookies.
249 request_info_
.privacy_mode
= enable_privacy_mode
?
250 PRIVACY_MODE_ENABLED
: PRIVACY_MODE_DISABLED
;
252 // Strip Referer from request_info_.extra_headers to prevent, e.g., plugins
253 // from overriding headers that are controlled using other means. Otherwise a
254 // plugin could set a referrer although sending the referrer is inhibited.
255 request_info_
.extra_headers
.RemoveHeader(HttpRequestHeaders::kReferer
);
257 // Our consumer should have made sure that this is a safe referrer. See for
258 // instance WebCore::FrameLoader::HideReferrer.
259 if (referrer
.is_valid()) {
260 request_info_
.extra_headers
.SetHeader(HttpRequestHeaders::kReferer
,
264 request_info_
.extra_headers
.SetHeaderIfMissing(
265 HttpRequestHeaders::kUserAgent
,
266 http_user_agent_settings_
?
267 http_user_agent_settings_
->GetUserAgent() : std::string());
270 AddCookieHeaderAndStart();
273 void URLRequestHttpJob::Kill() {
274 if (!transaction_
.get())
277 weak_factory_
.InvalidateWeakPtrs();
278 DestroyTransaction();
279 URLRequestJob::Kill();
282 void URLRequestHttpJob::NotifyBeforeSendProxyHeadersCallback(
283 const ProxyInfo
& proxy_info
,
284 HttpRequestHeaders
* request_headers
) {
285 DCHECK(request_headers
);
286 DCHECK_NE(URLRequestStatus::CANCELED
, GetStatus().status());
287 if (network_delegate()) {
288 network_delegate()->NotifyBeforeSendProxyHeaders(
295 void URLRequestHttpJob::NotifyHeadersComplete() {
296 DCHECK(!response_info_
);
298 response_info_
= transaction_
->GetResponseInfo();
300 // Save boolean, as we'll need this info at destruction time, and filters may
301 // also need this info.
302 is_cached_content_
= response_info_
->was_cached
;
304 if (!is_cached_content_
&& throttling_entry_
.get()) {
305 URLRequestThrottlerHeaderAdapter
response_adapter(GetResponseHeaders());
306 throttling_entry_
->UpdateWithResponse(request_info_
.url
.host(),
310 // The ordering of these calls is not important.
311 ProcessStrictTransportSecurityHeader();
312 ProcessPublicKeyPinsHeader();
314 // Handle the server notification of a new SDCH dictionary.
315 SdchManager
* sdch_manager(request()->context()->sdch_manager());
317 SdchProblemCode rv
= sdch_manager
->IsInSupportedDomain(request()->url());
319 // If SDCH is just disabled, it is not a real error.
320 if (rv
!= SDCH_DISABLED
&& rv
!= SDCH_SECURE_SCHEME_NOT_SUPPORTED
) {
321 SdchManager::SdchErrorRecovery(rv
);
322 request()->net_log().AddEvent(
323 NetLog::TYPE_SDCH_DECODING_ERROR
,
324 base::Bind(&NetLogSdchResourceProblemCallback
, rv
));
327 const std::string name
= "Get-Dictionary";
328 std::string url_text
;
330 // TODO(jar): We need to not fetch dictionaries the first time they are
331 // seen, but rather wait until we can justify their usefulness.
332 // For now, we will only fetch the first dictionary, which will at least
333 // require multiple suggestions before we get additional ones for this
334 // site. Eventually we should wait until a dictionary is requested
336 // before we even download it (so that we don't waste memory or
338 if (GetResponseHeaders()->EnumerateHeader(&iter
, name
, &url_text
)) {
339 // Resolve suggested URL relative to request url.
340 GURL sdch_dictionary_url
= request_
->url().Resolve(url_text
);
341 if (sdch_dictionary_url
.is_valid()) {
342 rv
= sdch_manager
->OnGetDictionary(request_
->url(),
343 sdch_dictionary_url
);
345 SdchManager::SdchErrorRecovery(rv
);
346 request_
->net_log().AddEvent(
347 NetLog::TYPE_SDCH_DICTIONARY_ERROR
,
348 base::Bind(&NetLogSdchDictionaryFetchProblemCallback
, rv
,
349 sdch_dictionary_url
, false));
356 // Handle the server signalling no SDCH encoding.
357 if (dictionaries_advertised_
) {
358 // We are wary of proxies that discard or damage SDCH encoding. If a server
359 // explicitly states that this is not SDCH content, then we can correct our
360 // assumption that this is an SDCH response, and avoid the need to recover
361 // as though the content is corrupted (when we discover it is not SDCH
363 std::string sdch_response_status
;
365 while (GetResponseHeaders()->EnumerateHeader(&iter
, "X-Sdch-Encode",
366 &sdch_response_status
)) {
367 if (sdch_response_status
== "0") {
368 dictionaries_advertised_
.reset();
374 // The HTTP transaction may be restarted several times for the purposes
375 // of sending authorization information. Each time it restarts, we get
376 // notified of the headers completion so that we can update the cookie store.
377 if (transaction_
->IsReadyToRestartForAuth()) {
378 DCHECK(!response_info_
->auth_challenge
.get());
379 // TODO(battre): This breaks the webrequest API for
380 // URLRequestTestHTTP.BasicAuthWithCookies
381 // where OnBeforeSendHeaders -> OnSendHeaders -> OnBeforeSendHeaders
383 RestartTransactionWithAuth(AuthCredentials());
387 URLRequestJob::NotifyHeadersComplete();
390 void URLRequestHttpJob::NotifyDone(const URLRequestStatus
& status
) {
391 DoneWithRequest(FINISHED
);
392 URLRequestJob::NotifyDone(status
);
395 void URLRequestHttpJob::DestroyTransaction() {
396 DCHECK(transaction_
.get());
398 DoneWithRequest(ABORTED
);
399 transaction_
.reset();
400 response_info_
= NULL
;
401 receive_headers_end_
= base::TimeTicks();
404 void URLRequestHttpJob::StartTransaction() {
405 // TODO(mmenke): Remove ScopedTracker below once crbug.com/456327 is fixed.
406 tracked_objects::ScopedTracker
tracking_profile(
407 FROM_HERE_WITH_EXPLICIT_FUNCTION(
408 "456327 URLRequestHttpJob::StartTransaction"));
410 if (network_delegate()) {
412 int rv
= network_delegate()->NotifyBeforeSendHeaders(
413 request_
, notify_before_headers_sent_callback_
,
414 &request_info_
.extra_headers
);
415 // If an extension blocks the request, we rely on the callback to
416 // MaybeStartTransactionInternal().
417 if (rv
== ERR_IO_PENDING
)
419 MaybeStartTransactionInternal(rv
);
422 StartTransactionInternal();
425 void URLRequestHttpJob::NotifyBeforeSendHeadersCallback(int result
) {
426 // Check that there are no callbacks to already canceled requests.
427 DCHECK_NE(URLRequestStatus::CANCELED
, GetStatus().status());
429 MaybeStartTransactionInternal(result
);
432 void URLRequestHttpJob::MaybeStartTransactionInternal(int result
) {
433 // TODO(mmenke): Remove ScopedTracker below once crbug.com/456327 is fixed.
434 tracked_objects::ScopedTracker
tracking_profile(
435 FROM_HERE_WITH_EXPLICIT_FUNCTION(
436 "456327 URLRequestHttpJob::MaybeStartTransactionInternal"));
438 OnCallToDelegateComplete();
440 StartTransactionInternal();
442 std::string
source("delegate");
443 request_
->net_log().AddEvent(NetLog::TYPE_CANCELLED
,
444 NetLog::StringCallback("source", &source
));
446 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED
, result
));
450 void URLRequestHttpJob::StartTransactionInternal() {
451 // NOTE: This method assumes that request_info_ is already setup properly.
453 // If we already have a transaction, then we should restart the transaction
454 // with auth provided by auth_credentials_.
458 if (network_delegate()) {
459 network_delegate()->NotifySendHeaders(
460 request_
, request_info_
.extra_headers
);
463 if (transaction_
.get()) {
464 rv
= transaction_
->RestartWithAuth(auth_credentials_
, start_callback_
);
465 auth_credentials_
= AuthCredentials();
467 DCHECK(request_
->context()->http_transaction_factory());
469 rv
= request_
->context()->http_transaction_factory()->CreateTransaction(
470 priority_
, &transaction_
);
472 if (rv
== OK
&& request_info_
.url
.SchemeIsWSOrWSS()) {
473 base::SupportsUserData::Data
* data
= request_
->GetUserData(
474 WebSocketHandshakeStreamBase::CreateHelper::DataKey());
476 transaction_
->SetWebSocketHandshakeStreamCreateHelper(
477 static_cast<WebSocketHandshakeStreamBase::CreateHelper
*>(data
));
479 rv
= ERR_DISALLOWED_URL_SCHEME
;
484 transaction_
->SetBeforeNetworkStartCallback(
485 base::Bind(&URLRequestHttpJob::NotifyBeforeNetworkStart
,
486 base::Unretained(this)));
487 transaction_
->SetBeforeProxyHeadersSentCallback(
488 base::Bind(&URLRequestHttpJob::NotifyBeforeSendProxyHeadersCallback
,
489 base::Unretained(this)));
491 if (!throttling_entry_
.get() ||
492 !throttling_entry_
->ShouldRejectRequest(*request_
,
493 network_delegate())) {
494 rv
= transaction_
->Start(
495 &request_info_
, start_callback_
, request_
->net_log());
496 start_time_
= base::TimeTicks::Now();
498 // Special error code for the exponential back-off module.
499 rv
= ERR_TEMPORARILY_THROTTLED
;
504 if (rv
== ERR_IO_PENDING
)
507 // The transaction started synchronously, but we need to notify the
508 // URLRequest delegate via the message loop.
509 base::MessageLoop::current()->PostTask(
511 base::Bind(&URLRequestHttpJob::OnStartCompleted
,
512 weak_factory_
.GetWeakPtr(), rv
));
515 void URLRequestHttpJob::AddExtraHeaders() {
516 SdchManager
* sdch_manager
= request()->context()->sdch_manager();
518 // Supply Accept-Encoding field only if it is not already provided.
519 // It should be provided IF the content is known to have restrictions on
520 // potential encoding, such as streaming multi-media.
521 // For details see bug 47381.
522 // TODO(jar, enal): jpeg files etc. should set up a request header if
523 // possible. Right now it is done only by buffered_resource_loader and
524 // simple_data_source.
525 if (!request_info_
.extra_headers
.HasHeader(
526 HttpRequestHeaders::kAcceptEncoding
)) {
527 // We don't support SDCH responses to POST as there is a possibility
528 // of having SDCH encoded responses returned (e.g. by the cache)
529 // which we cannot decode, and in those situations, we will need
530 // to retransmit the request without SDCH, which is illegal for a POST.
531 bool advertise_sdch
= sdch_manager
!= NULL
&& request()->method() != "POST";
532 if (advertise_sdch
) {
533 SdchProblemCode rv
= sdch_manager
->IsInSupportedDomain(request()->url());
535 advertise_sdch
= false;
536 // If SDCH is just disabled, it is not a real error.
537 if (rv
!= SDCH_DISABLED
&& rv
!= SDCH_SECURE_SCHEME_NOT_SUPPORTED
) {
538 SdchManager::SdchErrorRecovery(rv
);
539 request()->net_log().AddEvent(
540 NetLog::TYPE_SDCH_DECODING_ERROR
,
541 base::Bind(&NetLogSdchResourceProblemCallback
, rv
));
545 if (advertise_sdch
) {
546 dictionaries_advertised_
=
547 sdch_manager
->GetDictionarySet(request_
->url());
550 // The AllowLatencyExperiment() is only true if we've successfully done a
551 // full SDCH compression recently in this browser session for this host.
552 // Note that for this path, there might be no applicable dictionaries,
553 // and hence we can't participate in the experiment.
554 if (dictionaries_advertised_
&&
555 sdch_manager
->AllowLatencyExperiment(request_
->url())) {
556 // We are participating in the test (or control), and hence we'll
557 // eventually record statistics via either SDCH_EXPERIMENT_DECODE or
558 // SDCH_EXPERIMENT_HOLDBACK, and we'll need some packet timing data.
559 packet_timing_enabled_
= true;
560 if (base::RandDouble() < .01) {
561 sdch_test_control_
= true; // 1% probability.
562 dictionaries_advertised_
.reset();
563 advertise_sdch
= false;
565 sdch_test_activated_
= true;
569 // Supply Accept-Encoding headers first so that it is more likely that they
570 // will be in the first transmitted packet. This can sometimes make it
571 // easier to filter and analyze the streams to assure that a proxy has not
572 // damaged these headers. Some proxies deliberately corrupt Accept-Encoding
574 if (!advertise_sdch
) {
575 // Tell the server what compression formats we support (other than SDCH).
576 request_info_
.extra_headers
.SetHeader(
577 HttpRequestHeaders::kAcceptEncoding
, "gzip, deflate");
579 // Include SDCH in acceptable list.
580 request_info_
.extra_headers
.SetHeader(
581 HttpRequestHeaders::kAcceptEncoding
, "gzip, deflate, sdch");
582 if (dictionaries_advertised_
) {
583 request_info_
.extra_headers
.SetHeader(
584 kAvailDictionaryHeader
,
585 dictionaries_advertised_
->GetDictionaryClientHashList());
586 // Since we're tagging this transaction as advertising a dictionary,
587 // we'll definitely employ an SDCH filter (or tentative sdch filter)
588 // when we get a response. When done, we'll record histograms via
589 // SDCH_DECODE or SDCH_PASSTHROUGH. Hence we need to record packet
591 packet_timing_enabled_
= true;
596 if (http_user_agent_settings_
) {
597 // Only add default Accept-Language if the request didn't have it
599 std::string accept_language
=
600 http_user_agent_settings_
->GetAcceptLanguage();
601 if (!accept_language
.empty()) {
602 request_info_
.extra_headers
.SetHeaderIfMissing(
603 HttpRequestHeaders::kAcceptLanguage
,
609 void URLRequestHttpJob::AddCookieHeaderAndStart() {
610 // No matter what, we want to report our status as IO pending since we will
611 // be notifying our consumer asynchronously via OnStartCompleted.
612 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING
, 0));
614 // If the request was destroyed, then there is no more work to do.
618 CookieStore
* cookie_store
= request_
->context()->cookie_store();
619 if (cookie_store
&& !(request_info_
.load_flags
& LOAD_DO_NOT_SEND_COOKIES
)) {
620 cookie_store
->GetAllCookiesForURLAsync(
622 base::Bind(&URLRequestHttpJob::CheckCookiePolicyAndLoad
,
623 weak_factory_
.GetWeakPtr()));
625 DoStartTransaction();
629 void URLRequestHttpJob::DoLoadCookies() {
630 CookieOptions options
;
631 options
.set_include_httponly();
633 // TODO(mkwst): Drop this `if` once we decide whether or not to ship
634 // first-party cookies: https://crbug.com/459154
635 if (network_delegate() &&
636 network_delegate()->FirstPartyOnlyCookieExperimentEnabled())
637 options
.set_first_party_url(request_
->first_party_for_cookies());
639 options
.set_include_first_party_only();
641 request_
->context()->cookie_store()->GetCookiesWithOptionsAsync(
642 request_
->url(), options
, base::Bind(&URLRequestHttpJob::OnCookiesLoaded
,
643 weak_factory_
.GetWeakPtr()));
646 void URLRequestHttpJob::CheckCookiePolicyAndLoad(
647 const CookieList
& cookie_list
) {
648 if (CanGetCookies(cookie_list
))
651 DoStartTransaction();
654 void URLRequestHttpJob::OnCookiesLoaded(const std::string
& cookie_line
) {
655 if (!cookie_line
.empty()) {
656 request_info_
.extra_headers
.SetHeader(
657 HttpRequestHeaders::kCookie
, cookie_line
);
658 // Disable privacy mode as we are sending cookies anyway.
659 request_info_
.privacy_mode
= PRIVACY_MODE_DISABLED
;
661 DoStartTransaction();
664 void URLRequestHttpJob::DoStartTransaction() {
665 // We may have been canceled while retrieving cookies.
666 if (GetStatus().is_success()) {
673 void URLRequestHttpJob::SaveCookiesAndNotifyHeadersComplete(int result
) {
674 // End of the call started in OnStartCompleted.
675 OnCallToDelegateComplete();
678 std::string
source("delegate");
679 request_
->net_log().AddEvent(NetLog::TYPE_CANCELLED
,
680 NetLog::StringCallback("source", &source
));
681 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED
, result
));
685 DCHECK(transaction_
.get());
687 const HttpResponseInfo
* response_info
= transaction_
->GetResponseInfo();
688 DCHECK(response_info
);
690 response_cookies_
.clear();
691 response_cookies_save_index_
= 0;
693 FetchResponseCookies(&response_cookies_
);
695 if (!GetResponseHeaders()->GetDateValue(&response_date_
))
696 response_date_
= base::Time();
698 // Now, loop over the response cookies, and attempt to persist each.
702 // If the save occurs synchronously, SaveNextCookie will loop and save the next
703 // cookie. If the save is deferred, the callback is responsible for continuing
704 // to iterate through the cookies.
705 // TODO(erikwright): Modify the CookieStore API to indicate via return value
706 // whether it completed synchronously or asynchronously.
707 // See http://crbug.com/131066.
708 void URLRequestHttpJob::SaveNextCookie() {
709 // No matter what, we want to report our status as IO pending since we will
710 // be notifying our consumer asynchronously via OnStartCompleted.
711 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING
, 0));
713 // Used to communicate with the callback. See the implementation of
715 scoped_refptr
<SharedBoolean
> callback_pending
= new SharedBoolean(false);
716 scoped_refptr
<SharedBoolean
> save_next_cookie_running
=
717 new SharedBoolean(true);
719 if (!(request_info_
.load_flags
& LOAD_DO_NOT_SAVE_COOKIES
) &&
720 request_
->context()->cookie_store() && response_cookies_
.size() > 0) {
721 CookieOptions options
;
722 options
.set_include_httponly();
723 options
.set_server_time(response_date_
);
725 CookieStore::SetCookiesCallback
callback(base::Bind(
726 &URLRequestHttpJob::OnCookieSaved
, weak_factory_
.GetWeakPtr(),
727 save_next_cookie_running
, callback_pending
));
729 // Loop through the cookies as long as SetCookieWithOptionsAsync completes
731 while (!callback_pending
->data
&&
732 response_cookies_save_index_
< response_cookies_
.size()) {
734 response_cookies_
[response_cookies_save_index_
], &options
)) {
735 callback_pending
->data
= true;
736 request_
->context()->cookie_store()->SetCookieWithOptionsAsync(
737 request_
->url(), response_cookies_
[response_cookies_save_index_
],
740 ++response_cookies_save_index_
;
744 save_next_cookie_running
->data
= false;
746 if (!callback_pending
->data
) {
747 response_cookies_
.clear();
748 response_cookies_save_index_
= 0;
749 SetStatus(URLRequestStatus()); // Clear the IO_PENDING status
750 NotifyHeadersComplete();
755 // |save_next_cookie_running| is true when the callback is bound and set to
756 // false when SaveNextCookie exits, allowing the callback to determine if the
757 // save occurred synchronously or asynchronously.
758 // |callback_pending| is false when the callback is invoked and will be set to
759 // true by the callback, allowing SaveNextCookie to detect whether the save
760 // occurred synchronously.
761 // See SaveNextCookie() for more information.
762 void URLRequestHttpJob::OnCookieSaved(
763 scoped_refptr
<SharedBoolean
> save_next_cookie_running
,
764 scoped_refptr
<SharedBoolean
> callback_pending
,
765 bool cookie_status
) {
766 callback_pending
->data
= false;
768 // If we were called synchronously, return.
769 if (save_next_cookie_running
->data
) {
773 // We were called asynchronously, so trigger the next save.
774 // We may have been canceled within OnSetCookie.
775 if (GetStatus().is_success()) {
782 void URLRequestHttpJob::FetchResponseCookies(
783 std::vector
<std::string
>* cookies
) {
784 const std::string name
= "Set-Cookie";
788 HttpResponseHeaders
* headers
= GetResponseHeaders();
789 while (headers
->EnumerateHeader(&iter
, name
, &value
)) {
791 cookies
->push_back(value
);
795 // NOTE: |ProcessStrictTransportSecurityHeader| and
796 // |ProcessPublicKeyPinsHeader| have very similar structures, by design.
797 void URLRequestHttpJob::ProcessStrictTransportSecurityHeader() {
798 DCHECK(response_info_
);
799 TransportSecurityState
* security_state
=
800 request_
->context()->transport_security_state();
801 const SSLInfo
& ssl_info
= response_info_
->ssl_info
;
803 // Only accept HSTS headers on HTTPS connections that have no
804 // certificate errors.
805 if (!ssl_info
.is_valid() || IsCertStatusError(ssl_info
.cert_status
) ||
809 // Don't accept HSTS headers when the hostname is an IP address.
810 if (request_info_
.url
.HostIsIPAddress())
813 // http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec:
815 // If a UA receives more than one STS header field in a HTTP response
816 // message over secure transport, then the UA MUST process only the
817 // first such header field.
818 HttpResponseHeaders
* headers
= GetResponseHeaders();
820 if (headers
->EnumerateHeader(NULL
, "Strict-Transport-Security", &value
))
821 security_state
->AddHSTSHeader(request_info_
.url
.host(), value
);
824 void URLRequestHttpJob::ProcessPublicKeyPinsHeader() {
825 DCHECK(response_info_
);
826 TransportSecurityState
* security_state
=
827 request_
->context()->transport_security_state();
828 const SSLInfo
& ssl_info
= response_info_
->ssl_info
;
830 // Only accept HPKP headers on HTTPS connections that have no
831 // certificate errors.
832 if (!ssl_info
.is_valid() || IsCertStatusError(ssl_info
.cert_status
) ||
836 // Don't accept HSTS headers when the hostname is an IP address.
837 if (request_info_
.url
.HostIsIPAddress())
840 // http://tools.ietf.org/html/draft-ietf-websec-key-pinning:
842 // If a UA receives more than one PKP header field in an HTTP
843 // response message over secure transport, then the UA MUST process
844 // only the first such header field.
845 HttpResponseHeaders
* headers
= GetResponseHeaders();
847 if (headers
->EnumerateHeader(NULL
, "Public-Key-Pins", &value
))
848 security_state
->AddHPKPHeader(request_info_
.url
.host(), value
, ssl_info
);
851 void URLRequestHttpJob::OnStartCompleted(int result
) {
854 // If the request was destroyed, then there is no more work to do.
858 // If the job is done (due to cancellation), can just ignore this
863 receive_headers_end_
= base::TimeTicks::Now();
865 // Clear the IO_PENDING status
866 SetStatus(URLRequestStatus());
868 const URLRequestContext
* context
= request_
->context();
870 if (result
== ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
&&
871 transaction_
->GetResponseInfo() != NULL
) {
872 FraudulentCertificateReporter
* reporter
=
873 context
->fraudulent_certificate_reporter();
874 if (reporter
!= NULL
) {
875 const SSLInfo
& ssl_info
= transaction_
->GetResponseInfo()->ssl_info
;
876 const std::string
& host
= request_
->url().host();
878 reporter
->SendReport(host
, ssl_info
);
883 if (transaction_
&& transaction_
->GetResponseInfo()) {
884 SetProxyServer(transaction_
->GetResponseInfo()->proxy_server
);
886 scoped_refptr
<HttpResponseHeaders
> headers
= GetResponseHeaders();
887 if (network_delegate()) {
888 // Note that |this| may not be deleted until
889 // |on_headers_received_callback_| or
890 // |NetworkDelegate::URLRequestDestroyed()| has been called.
892 allowed_unsafe_redirect_url_
= GURL();
893 int error
= network_delegate()->NotifyHeadersReceived(
895 on_headers_received_callback_
,
897 &override_response_headers_
,
898 &allowed_unsafe_redirect_url_
);
900 if (error
== ERR_IO_PENDING
) {
901 awaiting_callback_
= true;
903 std::string
source("delegate");
904 request_
->net_log().AddEvent(NetLog::TYPE_CANCELLED
,
905 NetLog::StringCallback("source",
907 OnCallToDelegateComplete();
908 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED
, error
));
914 SaveCookiesAndNotifyHeadersComplete(OK
);
915 } else if (IsCertificateError(result
)) {
916 // We encountered an SSL certificate error.
917 if (result
== ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY
||
918 result
== ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
) {
919 // These are hard failures. They're handled separately and don't have
920 // the correct cert status, so set it here.
921 SSLInfo
info(transaction_
->GetResponseInfo()->ssl_info
);
922 info
.cert_status
= MapNetErrorToCertStatus(result
);
923 NotifySSLCertificateError(info
, true);
925 // Maybe overridable, maybe not. Ask the delegate to decide.
926 TransportSecurityState
* state
= context
->transport_security_state();
928 state
&& state
->ShouldSSLErrorsBeFatal(request_info_
.url
.host());
929 NotifySSLCertificateError(
930 transaction_
->GetResponseInfo()->ssl_info
, fatal
);
932 } else if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
) {
933 NotifyCertificateRequested(
934 transaction_
->GetResponseInfo()->cert_request_info
.get());
936 // Even on an error, there may be useful information in the response
937 // info (e.g. whether there's a cached copy).
938 if (transaction_
.get())
939 response_info_
= transaction_
->GetResponseInfo();
940 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED
, result
));
944 void URLRequestHttpJob::OnHeadersReceivedCallback(int result
) {
945 awaiting_callback_
= false;
947 // Check that there are no callbacks to already canceled requests.
948 DCHECK_NE(URLRequestStatus::CANCELED
, GetStatus().status());
950 SaveCookiesAndNotifyHeadersComplete(result
);
953 void URLRequestHttpJob::OnReadCompleted(int result
) {
954 read_in_progress_
= false;
956 if (ShouldFixMismatchedContentLength(result
))
960 NotifyDone(URLRequestStatus());
961 } else if (result
< 0) {
962 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED
, result
));
964 // Clear the IO_PENDING status
965 SetStatus(URLRequestStatus());
968 NotifyReadComplete(result
);
971 void URLRequestHttpJob::RestartTransactionWithAuth(
972 const AuthCredentials
& credentials
) {
973 auth_credentials_
= credentials
;
975 // These will be reset in OnStartCompleted.
976 response_info_
= NULL
;
977 receive_headers_end_
= base::TimeTicks();
978 response_cookies_
.clear();
982 // Update the cookies, since the cookie store may have been updated from the
983 // headers in the 401/407. Since cookies were already appended to
984 // extra_headers, we need to strip them out before adding them again.
985 request_info_
.extra_headers
.RemoveHeader(HttpRequestHeaders::kCookie
);
987 AddCookieHeaderAndStart();
990 void URLRequestHttpJob::SetUpload(UploadDataStream
* upload
) {
991 DCHECK(!transaction_
.get()) << "cannot change once started";
992 request_info_
.upload_data_stream
= upload
;
995 void URLRequestHttpJob::SetExtraRequestHeaders(
996 const HttpRequestHeaders
& headers
) {
997 DCHECK(!transaction_
.get()) << "cannot change once started";
998 request_info_
.extra_headers
.CopyFrom(headers
);
1001 LoadState
URLRequestHttpJob::GetLoadState() const {
1002 return transaction_
.get() ?
1003 transaction_
->GetLoadState() : LOAD_STATE_IDLE
;
1006 UploadProgress
URLRequestHttpJob::GetUploadProgress() const {
1007 return transaction_
.get() ?
1008 transaction_
->GetUploadProgress() : UploadProgress();
1011 bool URLRequestHttpJob::GetMimeType(std::string
* mime_type
) const {
1012 DCHECK(transaction_
.get());
1014 if (!response_info_
)
1017 HttpResponseHeaders
* headers
= GetResponseHeaders();
1020 return headers
->GetMimeType(mime_type
);
1023 bool URLRequestHttpJob::GetCharset(std::string
* charset
) {
1024 DCHECK(transaction_
.get());
1026 if (!response_info_
)
1029 return GetResponseHeaders()->GetCharset(charset
);
1032 void URLRequestHttpJob::GetResponseInfo(HttpResponseInfo
* info
) {
1035 if (response_info_
) {
1036 DCHECK(transaction_
.get());
1038 *info
= *response_info_
;
1039 if (override_response_headers_
.get())
1040 info
->headers
= override_response_headers_
;
1044 void URLRequestHttpJob::GetLoadTimingInfo(
1045 LoadTimingInfo
* load_timing_info
) const {
1046 // If haven't made it far enough to receive any headers, don't return
1047 // anything. This makes for more consistent behavior in the case of errors.
1048 if (!transaction_
|| receive_headers_end_
.is_null())
1050 if (transaction_
->GetLoadTimingInfo(load_timing_info
))
1051 load_timing_info
->receive_headers_end
= receive_headers_end_
;
1054 bool URLRequestHttpJob::GetResponseCookies(std::vector
<std::string
>* cookies
) {
1055 DCHECK(transaction_
.get());
1057 if (!response_info_
)
1060 // TODO(darin): Why are we extracting response cookies again? Perhaps we
1061 // should just leverage response_cookies_.
1064 FetchResponseCookies(cookies
);
1068 int URLRequestHttpJob::GetResponseCode() const {
1069 DCHECK(transaction_
.get());
1071 if (!response_info_
)
1074 return GetResponseHeaders()->response_code();
1077 Filter
* URLRequestHttpJob::SetupFilter() const {
1078 DCHECK(transaction_
.get());
1079 if (!response_info_
)
1082 std::vector
<Filter::FilterType
> encoding_types
;
1083 std::string encoding_type
;
1084 HttpResponseHeaders
* headers
= GetResponseHeaders();
1086 while (headers
->EnumerateHeader(&iter
, "Content-Encoding", &encoding_type
)) {
1087 encoding_types
.push_back(Filter::ConvertEncodingToType(encoding_type
));
1090 // Even if encoding types are empty, there is a chance that we need to add
1091 // some decoding, as some proxies strip encoding completely. In such cases,
1092 // we may need to add (for example) SDCH filtering (when the context suggests
1093 // it is appropriate).
1094 Filter::FixupEncodingTypes(*filter_context_
, &encoding_types
);
1096 return !encoding_types
.empty()
1097 ? Filter::Factory(encoding_types
, *filter_context_
) : NULL
;
1100 bool URLRequestHttpJob::CopyFragmentOnRedirect(const GURL
& location
) const {
1101 // Allow modification of reference fragments by default, unless
1102 // |allowed_unsafe_redirect_url_| is set and equal to the redirect URL.
1103 // When this is the case, we assume that the network delegate has set the
1104 // desired redirect URL (with or without fragment), so it must not be changed
1106 return !allowed_unsafe_redirect_url_
.is_valid() ||
1107 allowed_unsafe_redirect_url_
!= location
;
1110 bool URLRequestHttpJob::IsSafeRedirect(const GURL
& location
) {
1111 // HTTP is always safe.
1112 // TODO(pauljensen): Remove once crbug.com/146591 is fixed.
1113 if (location
.is_valid() &&
1114 (location
.scheme() == "http" || location
.scheme() == "https")) {
1117 // Delegates may mark a URL as safe for redirection.
1118 if (allowed_unsafe_redirect_url_
.is_valid() &&
1119 allowed_unsafe_redirect_url_
== location
) {
1122 // Query URLRequestJobFactory as to whether |location| would be safe to
1124 return request_
->context()->job_factory() &&
1125 request_
->context()->job_factory()->IsSafeRedirectTarget(location
);
1128 bool URLRequestHttpJob::NeedsAuth() {
1129 int code
= GetResponseCode();
1133 // Check if we need either Proxy or WWW Authentication. This could happen
1134 // because we either provided no auth info, or provided incorrect info.
1137 if (proxy_auth_state_
== AUTH_STATE_CANCELED
)
1139 proxy_auth_state_
= AUTH_STATE_NEED_AUTH
;
1142 if (server_auth_state_
== AUTH_STATE_CANCELED
)
1144 server_auth_state_
= AUTH_STATE_NEED_AUTH
;
1150 void URLRequestHttpJob::GetAuthChallengeInfo(
1151 scoped_refptr
<AuthChallengeInfo
>* result
) {
1152 DCHECK(transaction_
.get());
1153 DCHECK(response_info_
);
1156 DCHECK(proxy_auth_state_
== AUTH_STATE_NEED_AUTH
||
1157 server_auth_state_
== AUTH_STATE_NEED_AUTH
);
1158 DCHECK((GetResponseHeaders()->response_code() == HTTP_UNAUTHORIZED
) ||
1159 (GetResponseHeaders()->response_code() ==
1160 HTTP_PROXY_AUTHENTICATION_REQUIRED
));
1162 *result
= response_info_
->auth_challenge
;
1165 void URLRequestHttpJob::SetAuth(const AuthCredentials
& credentials
) {
1166 DCHECK(transaction_
.get());
1168 // Proxy gets set first, then WWW.
1169 if (proxy_auth_state_
== AUTH_STATE_NEED_AUTH
) {
1170 proxy_auth_state_
= AUTH_STATE_HAVE_AUTH
;
1172 DCHECK_EQ(server_auth_state_
, AUTH_STATE_NEED_AUTH
);
1173 server_auth_state_
= AUTH_STATE_HAVE_AUTH
;
1176 RestartTransactionWithAuth(credentials
);
1179 void URLRequestHttpJob::CancelAuth() {
1180 // Proxy gets set first, then WWW.
1181 if (proxy_auth_state_
== AUTH_STATE_NEED_AUTH
) {
1182 proxy_auth_state_
= AUTH_STATE_CANCELED
;
1184 DCHECK_EQ(server_auth_state_
, AUTH_STATE_NEED_AUTH
);
1185 server_auth_state_
= AUTH_STATE_CANCELED
;
1188 // These will be reset in OnStartCompleted.
1189 response_info_
= NULL
;
1190 receive_headers_end_
= base::TimeTicks::Now();
1191 response_cookies_
.clear();
1195 // OK, let the consumer read the error page...
1197 // Because we set the AUTH_STATE_CANCELED flag, NeedsAuth will return false,
1198 // which will cause the consumer to receive OnResponseStarted instead of
1201 // We have to do this via InvokeLater to avoid "recursing" the consumer.
1203 base::MessageLoop::current()->PostTask(
1205 base::Bind(&URLRequestHttpJob::OnStartCompleted
,
1206 weak_factory_
.GetWeakPtr(), OK
));
1209 void URLRequestHttpJob::ContinueWithCertificate(
1210 X509Certificate
* client_cert
) {
1211 DCHECK(transaction_
.get());
1213 DCHECK(!response_info_
) << "should not have a response yet";
1214 receive_headers_end_
= base::TimeTicks();
1218 // No matter what, we want to report our status as IO pending since we will
1219 // be notifying our consumer asynchronously via OnStartCompleted.
1220 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING
, 0));
1222 int rv
= transaction_
->RestartWithCertificate(client_cert
, start_callback_
);
1223 if (rv
== ERR_IO_PENDING
)
1226 // The transaction started synchronously, but we need to notify the
1227 // URLRequest delegate via the message loop.
1228 base::MessageLoop::current()->PostTask(
1230 base::Bind(&URLRequestHttpJob::OnStartCompleted
,
1231 weak_factory_
.GetWeakPtr(), rv
));
1234 void URLRequestHttpJob::ContinueDespiteLastError() {
1235 // If the transaction was destroyed, then the job was cancelled.
1236 if (!transaction_
.get())
1239 DCHECK(!response_info_
) << "should not have a response yet";
1240 receive_headers_end_
= base::TimeTicks();
1244 // No matter what, we want to report our status as IO pending since we will
1245 // be notifying our consumer asynchronously via OnStartCompleted.
1246 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING
, 0));
1248 int rv
= transaction_
->RestartIgnoringLastError(start_callback_
);
1249 if (rv
== ERR_IO_PENDING
)
1252 // The transaction started synchronously, but we need to notify the
1253 // URLRequest delegate via the message loop.
1254 base::MessageLoop::current()->PostTask(
1256 base::Bind(&URLRequestHttpJob::OnStartCompleted
,
1257 weak_factory_
.GetWeakPtr(), rv
));
1260 void URLRequestHttpJob::ResumeNetworkStart() {
1261 DCHECK(transaction_
.get());
1262 transaction_
->ResumeNetworkStart();
1265 bool URLRequestHttpJob::ShouldFixMismatchedContentLength(int rv
) const {
1266 // Some servers send the body compressed, but specify the content length as
1267 // the uncompressed size. Although this violates the HTTP spec we want to
1268 // support it (as IE and FireFox do), but *only* for an exact match.
1269 // See http://crbug.com/79694.
1270 if (rv
== ERR_CONTENT_LENGTH_MISMATCH
||
1271 rv
== ERR_INCOMPLETE_CHUNKED_ENCODING
) {
1272 if (request_
&& request_
->response_headers()) {
1273 int64 expected_length
= request_
->response_headers()->GetContentLength();
1274 VLOG(1) << __FUNCTION__
<< "() "
1275 << "\"" << request_
->url().spec() << "\""
1276 << " content-length = " << expected_length
1277 << " pre total = " << prefilter_bytes_read()
1278 << " post total = " << postfilter_bytes_read();
1279 if (postfilter_bytes_read() == expected_length
) {
1288 bool URLRequestHttpJob::ReadRawData(IOBuffer
* buf
, int buf_size
,
1290 DCHECK_NE(buf_size
, 0);
1292 DCHECK(!read_in_progress_
);
1294 int rv
= transaction_
->Read(
1296 base::Bind(&URLRequestHttpJob::OnReadCompleted
, base::Unretained(this)));
1298 if (ShouldFixMismatchedContentLength(rv
))
1304 DoneWithRequest(FINISHED
);
1308 if (rv
== ERR_IO_PENDING
) {
1309 read_in_progress_
= true;
1310 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING
, 0));
1312 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED
, rv
));
1318 void URLRequestHttpJob::StopCaching() {
1319 if (transaction_
.get())
1320 transaction_
->StopCaching();
1323 bool URLRequestHttpJob::GetFullRequestHeaders(
1324 HttpRequestHeaders
* headers
) const {
1328 return transaction_
->GetFullRequestHeaders(headers
);
1331 int64
URLRequestHttpJob::GetTotalReceivedBytes() const {
1335 return transaction_
->GetTotalReceivedBytes();
1338 void URLRequestHttpJob::DoneReading() {
1340 transaction_
->DoneReading();
1342 DoneWithRequest(FINISHED
);
1345 void URLRequestHttpJob::DoneReadingRedirectResponse() {
1347 if (transaction_
->GetResponseInfo()->headers
->IsRedirect(NULL
)) {
1348 // If the original headers indicate a redirect, go ahead and cache the
1349 // response, even if the |override_response_headers_| are a redirect to
1350 // another location.
1351 transaction_
->DoneReading();
1353 // Otherwise, |override_response_headers_| must be non-NULL and contain
1354 // bogus headers indicating a redirect.
1355 DCHECK(override_response_headers_
.get());
1356 DCHECK(override_response_headers_
->IsRedirect(NULL
));
1357 transaction_
->StopCaching();
1360 DoneWithRequest(FINISHED
);
1363 HostPortPair
URLRequestHttpJob::GetSocketAddress() const {
1364 return response_info_
? response_info_
->socket_address
: HostPortPair();
1367 void URLRequestHttpJob::RecordTimer() {
1368 if (request_creation_time_
.is_null()) {
1370 << "The same transaction shouldn't start twice without new timing.";
1374 base::TimeDelta to_start
= base::Time::Now() - request_creation_time_
;
1375 request_creation_time_
= base::Time();
1377 UMA_HISTOGRAM_MEDIUM_TIMES("Net.HttpTimeToFirstByte", to_start
);
1380 void URLRequestHttpJob::ResetTimer() {
1381 if (!request_creation_time_
.is_null()) {
1383 << "The timer was reset before it was recorded.";
1386 request_creation_time_
= base::Time::Now();
1389 void URLRequestHttpJob::UpdatePacketReadTimes() {
1390 if (!packet_timing_enabled_
)
1393 DCHECK_GT(prefilter_bytes_read(), bytes_observed_in_packets_
);
1395 base::Time
now(base::Time::Now());
1396 if (!bytes_observed_in_packets_
)
1397 request_time_snapshot_
= now
;
1398 final_packet_time_
= now
;
1400 bytes_observed_in_packets_
= prefilter_bytes_read();
1403 void URLRequestHttpJob::RecordPacketStats(
1404 FilterContext::StatisticSelector statistic
) const {
1405 if (!packet_timing_enabled_
|| (final_packet_time_
== base::Time()))
1408 base::TimeDelta duration
= final_packet_time_
- request_time_snapshot_
;
1409 switch (statistic
) {
1410 case FilterContext::SDCH_DECODE
: {
1411 UMA_HISTOGRAM_CUSTOM_COUNTS("Sdch3.Network_Decode_Bytes_Processed_b",
1412 static_cast<int>(bytes_observed_in_packets_
), 500, 100000, 100);
1415 case FilterContext::SDCH_PASSTHROUGH
: {
1416 // Despite advertising a dictionary, we handled non-sdch compressed
1421 case FilterContext::SDCH_EXPERIMENT_DECODE
: {
1422 UMA_HISTOGRAM_CUSTOM_TIMES("Sdch3.Experiment3_Decode",
1424 base::TimeDelta::FromMilliseconds(20),
1425 base::TimeDelta::FromMinutes(10), 100);
1428 case FilterContext::SDCH_EXPERIMENT_HOLDBACK
: {
1429 UMA_HISTOGRAM_CUSTOM_TIMES("Sdch3.Experiment3_Holdback",
1431 base::TimeDelta::FromMilliseconds(20),
1432 base::TimeDelta::FromMinutes(10), 100);
1441 void URLRequestHttpJob::RecordPerfHistograms(CompletionCause reason
) {
1442 if (start_time_
.is_null())
1445 base::TimeDelta total_time
= base::TimeTicks::Now() - start_time_
;
1446 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTime", total_time
);
1448 if (reason
== FINISHED
) {
1449 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeSuccess", total_time
);
1451 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeCancel", total_time
);
1454 if (response_info_
) {
1455 if (response_info_
->was_cached
) {
1456 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeCached", total_time
);
1458 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeNotCached", total_time
);
1462 if (request_info_
.load_flags
& LOAD_PREFETCH
&& !request_
->was_cached())
1463 UMA_HISTOGRAM_COUNTS("Net.Prefetch.PrefilterBytesReadFromNetwork",
1464 prefilter_bytes_read());
1466 start_time_
= base::TimeTicks();
1469 void URLRequestHttpJob::DoneWithRequest(CompletionCause reason
) {
1473 RecordPerfHistograms(reason
);
1474 if (reason
== FINISHED
) {
1475 request_
->set_received_response_content_length(prefilter_bytes_read());
1479 HttpResponseHeaders
* URLRequestHttpJob::GetResponseHeaders() const {
1480 DCHECK(transaction_
.get());
1481 DCHECK(transaction_
->GetResponseInfo());
1482 return override_response_headers_
.get() ?
1483 override_response_headers_
.get() :
1484 transaction_
->GetResponseInfo()->headers
.get();
1487 void URLRequestHttpJob::NotifyURLRequestDestroyed() {
1488 awaiting_callback_
= false;