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/mime_util.h"
23 #include "net/base/net_errors.h"
24 #include "net/base/net_util.h"
25 #include "net/base/network_delegate.h"
26 #include "net/base/sdch_manager.h"
27 #include "net/base/sdch_net_log_params.h"
28 #include "net/cert/cert_status_flags.h"
29 #include "net/cookies/cookie_store.h"
30 #include "net/http/http_content_disposition.h"
31 #include "net/http/http_network_session.h"
32 #include "net/http/http_request_headers.h"
33 #include "net/http/http_response_headers.h"
34 #include "net/http/http_response_info.h"
35 #include "net/http/http_status_code.h"
36 #include "net/http/http_transaction.h"
37 #include "net/http/http_transaction_factory.h"
38 #include "net/http/http_util.h"
39 #include "net/proxy/proxy_info.h"
40 #include "net/ssl/ssl_cert_request_info.h"
41 #include "net/ssl/ssl_config_service.h"
42 #include "net/url_request/fraudulent_certificate_reporter.h"
43 #include "net/url_request/http_user_agent_settings.h"
44 #include "net/url_request/url_request.h"
45 #include "net/url_request/url_request_context.h"
46 #include "net/url_request/url_request_error_job.h"
47 #include "net/url_request/url_request_job_factory.h"
48 #include "net/url_request/url_request_redirect_job.h"
49 #include "net/url_request/url_request_throttler_header_adapter.h"
50 #include "net/url_request/url_request_throttler_manager.h"
51 #include "net/websockets/websocket_handshake_stream_base.h"
53 static const char kAvailDictionaryHeader
[] = "Avail-Dictionary";
57 class URLRequestHttpJob::HttpFilterContext
: public FilterContext
{
59 explicit HttpFilterContext(URLRequestHttpJob
* job
);
60 ~HttpFilterContext() override
;
62 // FilterContext implementation.
63 bool GetMimeType(std::string
* mime_type
) const override
;
64 bool GetURL(GURL
* gurl
) const override
;
65 bool GetContentDisposition(std::string
* disposition
) const override
;
66 base::Time
GetRequestTime() const override
;
67 bool IsCachedContent() const override
;
68 bool IsDownload() const override
;
69 bool SdchResponseExpected() const override
;
70 int64
GetByteReadCount() const override
;
71 int GetResponseCode() const override
;
72 const URLRequestContext
* GetURLRequestContext() const override
;
73 void RecordPacketStats(StatisticSelector statistic
) const override
;
74 const BoundNetLog
& GetNetLog() const override
;
76 // Method to allow us to reset filter context for a response that should have
77 // been SDCH encoded when there is an update due to an explicit HTTP header.
78 void ResetSdchResponseToFalse();
81 URLRequestHttpJob
* job_
;
83 // URLRequestHttpJob may be detached from URLRequest, but we still need to
85 BoundNetLog dummy_log_
;
87 DISALLOW_COPY_AND_ASSIGN(HttpFilterContext
);
90 URLRequestHttpJob::HttpFilterContext::HttpFilterContext(URLRequestHttpJob
* job
)
95 URLRequestHttpJob::HttpFilterContext::~HttpFilterContext() {
98 bool URLRequestHttpJob::HttpFilterContext::GetMimeType(
99 std::string
* mime_type
) const {
100 return job_
->GetMimeType(mime_type
);
103 bool URLRequestHttpJob::HttpFilterContext::GetURL(GURL
* gurl
) const {
104 if (!job_
->request())
106 *gurl
= job_
->request()->url();
110 bool URLRequestHttpJob::HttpFilterContext::GetContentDisposition(
111 std::string
* disposition
) const {
112 HttpResponseHeaders
* headers
= job_
->GetResponseHeaders();
114 return headers
->EnumerateHeader(&iter
, "Content-Disposition", disposition
);
117 base::Time
URLRequestHttpJob::HttpFilterContext::GetRequestTime() const {
118 return job_
->request() ? job_
->request()->request_time() : base::Time();
121 bool URLRequestHttpJob::HttpFilterContext::IsCachedContent() const {
122 return job_
->is_cached_content_
;
125 bool URLRequestHttpJob::HttpFilterContext::IsDownload() const {
126 return (job_
->request_info_
.load_flags
& LOAD_IS_DOWNLOAD
) != 0;
129 void URLRequestHttpJob::HttpFilterContext::ResetSdchResponseToFalse() {
130 DCHECK(job_
->sdch_dictionary_advertised_
);
131 job_
->sdch_dictionary_advertised_
= false;
134 bool URLRequestHttpJob::HttpFilterContext::SdchResponseExpected() const {
135 return job_
->sdch_dictionary_advertised_
;
138 int64
URLRequestHttpJob::HttpFilterContext::GetByteReadCount() const {
139 return job_
->filter_input_byte_count();
142 int URLRequestHttpJob::HttpFilterContext::GetResponseCode() const {
143 return job_
->GetResponseCode();
146 const URLRequestContext
*
147 URLRequestHttpJob::HttpFilterContext::GetURLRequestContext() const {
148 return job_
->request() ? job_
->request()->context() : NULL
;
151 void URLRequestHttpJob::HttpFilterContext::RecordPacketStats(
152 StatisticSelector statistic
) const {
153 job_
->RecordPacketStats(statistic
);
156 const BoundNetLog
& URLRequestHttpJob::HttpFilterContext::GetNetLog() const {
157 return job_
->request() ? job_
->request()->net_log() : dummy_log_
;
160 // TODO(darin): make sure the port blocking code is not lost
162 URLRequestJob
* URLRequestHttpJob::Factory(URLRequest
* request
,
163 NetworkDelegate
* network_delegate
,
164 const std::string
& scheme
) {
165 DCHECK(scheme
== "http" || scheme
== "https" || scheme
== "ws" ||
168 if (!request
->context()->http_transaction_factory()) {
169 NOTREACHED() << "requires a valid context";
170 return new URLRequestErrorJob(
171 request
, network_delegate
, ERR_INVALID_ARGUMENT
);
175 if (request
->GetHSTSRedirect(&redirect_url
)) {
176 return new URLRequestRedirectJob(
177 request
, network_delegate
, redirect_url
,
178 // Use status code 307 to preserve the method, so POST requests work.
179 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT
, "HSTS");
181 return new URLRequestHttpJob(request
,
183 request
->context()->http_user_agent_settings());
186 URLRequestHttpJob::URLRequestHttpJob(
188 NetworkDelegate
* network_delegate
,
189 const HttpUserAgentSettings
* http_user_agent_settings
)
190 : URLRequestJob(request
, network_delegate
),
191 priority_(DEFAULT_PRIORITY
),
192 response_info_(NULL
),
193 response_cookies_save_index_(0),
194 proxy_auth_state_(AUTH_STATE_DONT_NEED_AUTH
),
195 server_auth_state_(AUTH_STATE_DONT_NEED_AUTH
),
196 start_callback_(base::Bind(&URLRequestHttpJob::OnStartCompleted
,
197 base::Unretained(this))),
198 notify_before_headers_sent_callback_(
199 base::Bind(&URLRequestHttpJob::NotifyBeforeSendHeadersCallback
,
200 base::Unretained(this))),
201 read_in_progress_(false),
202 throttling_entry_(NULL
),
203 sdch_dictionary_advertised_(false),
204 sdch_test_activated_(false),
205 sdch_test_control_(false),
206 is_cached_content_(false),
207 request_creation_time_(),
208 packet_timing_enabled_(false),
210 bytes_observed_in_packets_(0),
211 request_time_snapshot_(),
212 final_packet_time_(),
213 filter_context_(new HttpFilterContext(this)),
214 on_headers_received_callback_(
215 base::Bind(&URLRequestHttpJob::OnHeadersReceivedCallback
,
216 base::Unretained(this))),
217 awaiting_callback_(false),
218 http_user_agent_settings_(http_user_agent_settings
),
219 weak_factory_(this) {
220 URLRequestThrottlerManager
* manager
= request
->context()->throttler_manager();
222 throttling_entry_
= manager
->RegisterRequestUrl(request
->url());
227 URLRequestHttpJob::~URLRequestHttpJob() {
228 CHECK(!awaiting_callback_
);
230 DCHECK(!sdch_test_control_
|| !sdch_test_activated_
);
231 if (!is_cached_content_
) {
232 if (sdch_test_control_
)
233 RecordPacketStats(FilterContext::SDCH_EXPERIMENT_HOLDBACK
);
234 if (sdch_test_activated_
)
235 RecordPacketStats(FilterContext::SDCH_EXPERIMENT_DECODE
);
237 // Make sure SDCH filters are told to emit histogram data while
238 // filter_context_ is still alive.
241 DoneWithRequest(ABORTED
);
244 void URLRequestHttpJob::SetPriority(RequestPriority priority
) {
245 priority_
= priority
;
247 transaction_
->SetPriority(priority_
);
250 void URLRequestHttpJob::Start() {
251 DCHECK(!transaction_
.get());
253 // URLRequest::SetReferrer ensures that we do not send username and password
254 // fields in the referrer.
255 GURL
referrer(request_
->referrer());
257 request_info_
.url
= request_
->url();
258 request_info_
.method
= request_
->method();
259 request_info_
.load_flags
= request_
->load_flags();
260 // Enable privacy mode if cookie settings or flags tell us not send or
262 bool enable_privacy_mode
=
263 (request_info_
.load_flags
& LOAD_DO_NOT_SEND_COOKIES
) ||
264 (request_info_
.load_flags
& LOAD_DO_NOT_SAVE_COOKIES
) ||
265 CanEnablePrivacyMode();
266 // Privacy mode could still be disabled in OnCookiesLoaded if we are going
267 // to send previously saved cookies.
268 request_info_
.privacy_mode
= enable_privacy_mode
?
269 PRIVACY_MODE_ENABLED
: PRIVACY_MODE_DISABLED
;
271 // Strip Referer from request_info_.extra_headers to prevent, e.g., plugins
272 // from overriding headers that are controlled using other means. Otherwise a
273 // plugin could set a referrer although sending the referrer is inhibited.
274 request_info_
.extra_headers
.RemoveHeader(HttpRequestHeaders::kReferer
);
276 // Our consumer should have made sure that this is a safe referrer. See for
277 // instance WebCore::FrameLoader::HideReferrer.
278 if (referrer
.is_valid()) {
279 request_info_
.extra_headers
.SetHeader(HttpRequestHeaders::kReferer
,
283 request_info_
.extra_headers
.SetHeaderIfMissing(
284 HttpRequestHeaders::kUserAgent
,
285 http_user_agent_settings_
?
286 http_user_agent_settings_
->GetUserAgent() : std::string());
289 AddCookieHeaderAndStart();
292 void URLRequestHttpJob::Kill() {
293 if (!transaction_
.get())
296 weak_factory_
.InvalidateWeakPtrs();
297 DestroyTransaction();
298 URLRequestJob::Kill();
301 void URLRequestHttpJob::NotifyBeforeSendProxyHeadersCallback(
302 const ProxyInfo
& proxy_info
,
303 HttpRequestHeaders
* request_headers
) {
304 DCHECK(request_headers
);
305 DCHECK_NE(URLRequestStatus::CANCELED
, GetStatus().status());
306 if (network_delegate()) {
307 network_delegate()->NotifyBeforeSendProxyHeaders(
314 void URLRequestHttpJob::NotifyHeadersComplete() {
315 DCHECK(!response_info_
);
317 response_info_
= transaction_
->GetResponseInfo();
319 // Save boolean, as we'll need this info at destruction time, and filters may
320 // also need this info.
321 is_cached_content_
= response_info_
->was_cached
;
323 if (!is_cached_content_
&& throttling_entry_
.get()) {
324 URLRequestThrottlerHeaderAdapter
response_adapter(GetResponseHeaders());
325 throttling_entry_
->UpdateWithResponse(request_info_
.url
.host(),
329 // The ordering of these calls is not important.
330 ProcessStrictTransportSecurityHeader();
331 ProcessPublicKeyPinsHeader();
333 SdchManager
* sdch_manager(request()->context()->sdch_manager());
335 SdchProblemCode rv
= sdch_manager
->IsInSupportedDomain(request()->url());
337 // If SDCH is just disabled, it is not a real error.
338 if (rv
!= SDCH_DISABLED
&& rv
!= SDCH_SECURE_SCHEME_NOT_SUPPORTED
) {
339 SdchManager::SdchErrorRecovery(rv
);
340 request()->net_log().AddEvent(
341 NetLog::TYPE_SDCH_DECODING_ERROR
,
342 base::Bind(&NetLogSdchResourceProblemCallback
, rv
));
345 const std::string name
= "Get-Dictionary";
346 std::string url_text
;
348 // TODO(jar): We need to not fetch dictionaries the first time they are
349 // seen, but rather wait until we can justify their usefulness.
350 // For now, we will only fetch the first dictionary, which will at least
351 // require multiple suggestions before we get additional ones for this
352 // site. Eventually we should wait until a dictionary is requested
354 // before we even download it (so that we don't waste memory or
356 if (GetResponseHeaders()->EnumerateHeader(&iter
, name
, &url_text
)) {
357 // Resolve suggested URL relative to request url.
358 GURL sdch_dictionary_url
= request_
->url().Resolve(url_text
);
359 if (sdch_dictionary_url
.is_valid()) {
360 rv
= sdch_manager
->OnGetDictionary(request_
->url(),
361 sdch_dictionary_url
);
363 SdchManager::SdchErrorRecovery(rv
);
364 request_
->net_log().AddEvent(
365 NetLog::TYPE_SDCH_DICTIONARY_ERROR
,
366 base::Bind(&NetLogSdchDictionaryFetchProblemCallback
, rv
,
367 sdch_dictionary_url
, false));
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 if (network_delegate()) {
407 int rv
= network_delegate()->NotifyBeforeSendHeaders(
408 request_
, notify_before_headers_sent_callback_
,
409 &request_info_
.extra_headers
);
410 // If an extension blocks the request, we rely on the callback to
411 // MaybeStartTransactionInternal().
412 if (rv
== ERR_IO_PENDING
)
414 MaybeStartTransactionInternal(rv
);
417 StartTransactionInternal();
420 void URLRequestHttpJob::NotifyBeforeSendHeadersCallback(int result
) {
421 // Check that there are no callbacks to already canceled requests.
422 DCHECK_NE(URLRequestStatus::CANCELED
, GetStatus().status());
424 MaybeStartTransactionInternal(result
);
427 void URLRequestHttpJob::MaybeStartTransactionInternal(int result
) {
428 OnCallToDelegateComplete();
430 StartTransactionInternal();
432 std::string
source("delegate");
433 request_
->net_log().AddEvent(NetLog::TYPE_CANCELLED
,
434 NetLog::StringCallback("source", &source
));
436 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED
, result
));
440 void URLRequestHttpJob::StartTransactionInternal() {
441 // NOTE: This method assumes that request_info_ is already setup properly.
443 // If we already have a transaction, then we should restart the transaction
444 // with auth provided by auth_credentials_.
448 if (network_delegate()) {
449 network_delegate()->NotifySendHeaders(
450 request_
, request_info_
.extra_headers
);
453 if (transaction_
.get()) {
454 rv
= transaction_
->RestartWithAuth(auth_credentials_
, start_callback_
);
455 auth_credentials_
= AuthCredentials();
457 DCHECK(request_
->context()->http_transaction_factory());
459 rv
= request_
->context()->http_transaction_factory()->CreateTransaction(
460 priority_
, &transaction_
);
462 if (rv
== OK
&& request_info_
.url
.SchemeIsWSOrWSS()) {
463 base::SupportsUserData::Data
* data
= request_
->GetUserData(
464 WebSocketHandshakeStreamBase::CreateHelper::DataKey());
466 transaction_
->SetWebSocketHandshakeStreamCreateHelper(
467 static_cast<WebSocketHandshakeStreamBase::CreateHelper
*>(data
));
469 rv
= ERR_DISALLOWED_URL_SCHEME
;
474 transaction_
->SetBeforeNetworkStartCallback(
475 base::Bind(&URLRequestHttpJob::NotifyBeforeNetworkStart
,
476 base::Unretained(this)));
477 transaction_
->SetBeforeProxyHeadersSentCallback(
478 base::Bind(&URLRequestHttpJob::NotifyBeforeSendProxyHeadersCallback
,
479 base::Unretained(this)));
481 if (!throttling_entry_
.get() ||
482 !throttling_entry_
->ShouldRejectRequest(*request_
,
483 network_delegate())) {
484 rv
= transaction_
->Start(
485 &request_info_
, start_callback_
, request_
->net_log());
486 start_time_
= base::TimeTicks::Now();
488 // Special error code for the exponential back-off module.
489 rv
= ERR_TEMPORARILY_THROTTLED
;
494 if (rv
== ERR_IO_PENDING
)
497 // The transaction started synchronously, but we need to notify the
498 // URLRequest delegate via the message loop.
499 base::MessageLoop::current()->PostTask(
501 base::Bind(&URLRequestHttpJob::OnStartCompleted
,
502 weak_factory_
.GetWeakPtr(), rv
));
505 void URLRequestHttpJob::AddExtraHeaders() {
506 SdchManager
* sdch_manager
= request()->context()->sdch_manager();
508 // Supply Accept-Encoding field only if it is not already provided.
509 // It should be provided IF the content is known to have restrictions on
510 // potential encoding, such as streaming multi-media.
511 // For details see bug 47381.
512 // TODO(jar, enal): jpeg files etc. should set up a request header if
513 // possible. Right now it is done only by buffered_resource_loader and
514 // simple_data_source.
515 if (!request_info_
.extra_headers
.HasHeader(
516 HttpRequestHeaders::kAcceptEncoding
)) {
517 // We don't support SDCH responses to POST as there is a possibility
518 // of having SDCH encoded responses returned (e.g. by the cache)
519 // which we cannot decode, and in those situations, we will need
520 // to retransmit the request without SDCH, which is illegal for a POST.
521 bool advertise_sdch
= sdch_manager
!= NULL
&& request()->method() != "POST";
522 if (advertise_sdch
) {
523 SdchProblemCode rv
= sdch_manager
->IsInSupportedDomain(request()->url());
525 advertise_sdch
= false;
526 // If SDCH is just disabled, it is not a real error.
527 if (rv
!= SDCH_DISABLED
&& rv
!= SDCH_SECURE_SCHEME_NOT_SUPPORTED
) {
528 SdchManager::SdchErrorRecovery(rv
);
529 request()->net_log().AddEvent(
530 NetLog::TYPE_SDCH_DECODING_ERROR
,
531 base::Bind(&NetLogSdchResourceProblemCallback
, rv
));
535 std::string avail_dictionaries
;
536 if (advertise_sdch
) {
537 sdch_manager
->GetAvailDictionaryList(request_
->url(),
538 &avail_dictionaries
);
540 // The AllowLatencyExperiment() is only true if we've successfully done a
541 // full SDCH compression recently in this browser session for this host.
542 // Note that for this path, there might be no applicable dictionaries,
543 // and hence we can't participate in the experiment.
544 if (!avail_dictionaries
.empty() &&
545 sdch_manager
->AllowLatencyExperiment(request_
->url())) {
546 // We are participating in the test (or control), and hence we'll
547 // eventually record statistics via either SDCH_EXPERIMENT_DECODE or
548 // SDCH_EXPERIMENT_HOLDBACK, and we'll need some packet timing data.
549 packet_timing_enabled_
= true;
550 if (base::RandDouble() < .01) {
551 sdch_test_control_
= true; // 1% probability.
552 advertise_sdch
= false;
554 sdch_test_activated_
= true;
559 // Supply Accept-Encoding headers first so that it is more likely that they
560 // will be in the first transmitted packet. This can sometimes make it
561 // easier to filter and analyze the streams to assure that a proxy has not
562 // damaged these headers. Some proxies deliberately corrupt Accept-Encoding
564 if (!advertise_sdch
) {
565 // Tell the server what compression formats we support (other than SDCH).
566 request_info_
.extra_headers
.SetHeader(
567 HttpRequestHeaders::kAcceptEncoding
, "gzip, deflate");
569 // Include SDCH in acceptable list.
570 request_info_
.extra_headers
.SetHeader(
571 HttpRequestHeaders::kAcceptEncoding
, "gzip, deflate, sdch");
572 if (!avail_dictionaries
.empty()) {
573 request_info_
.extra_headers
.SetHeader(
574 kAvailDictionaryHeader
,
576 sdch_dictionary_advertised_
= true;
577 // Since we're tagging this transaction as advertising a dictionary,
578 // we'll definitely employ an SDCH filter (or tentative sdch filter)
579 // when we get a response. When done, we'll record histograms via
580 // SDCH_DECODE or SDCH_PASSTHROUGH. Hence we need to record packet
582 packet_timing_enabled_
= true;
587 if (http_user_agent_settings_
) {
588 // Only add default Accept-Language if the request didn't have it
590 std::string accept_language
=
591 http_user_agent_settings_
->GetAcceptLanguage();
592 if (!accept_language
.empty()) {
593 request_info_
.extra_headers
.SetHeaderIfMissing(
594 HttpRequestHeaders::kAcceptLanguage
,
600 void URLRequestHttpJob::AddCookieHeaderAndStart() {
601 // No matter what, we want to report our status as IO pending since we will
602 // be notifying our consumer asynchronously via OnStartCompleted.
603 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING
, 0));
605 // If the request was destroyed, then there is no more work to do.
609 CookieStore
* cookie_store
= GetCookieStore();
610 if (cookie_store
&& !(request_info_
.load_flags
& LOAD_DO_NOT_SEND_COOKIES
)) {
611 cookie_store
->GetAllCookiesForURLAsync(
613 base::Bind(&URLRequestHttpJob::CheckCookiePolicyAndLoad
,
614 weak_factory_
.GetWeakPtr()));
616 DoStartTransaction();
620 void URLRequestHttpJob::DoLoadCookies() {
621 CookieOptions options
;
622 options
.set_include_httponly();
623 GetCookieStore()->GetCookiesWithOptionsAsync(
624 request_
->url(), options
,
625 base::Bind(&URLRequestHttpJob::OnCookiesLoaded
,
626 weak_factory_
.GetWeakPtr()));
629 void URLRequestHttpJob::CheckCookiePolicyAndLoad(
630 const CookieList
& cookie_list
) {
631 if (CanGetCookies(cookie_list
))
634 DoStartTransaction();
637 void URLRequestHttpJob::OnCookiesLoaded(const std::string
& cookie_line
) {
638 if (!cookie_line
.empty()) {
639 request_info_
.extra_headers
.SetHeader(
640 HttpRequestHeaders::kCookie
, cookie_line
);
641 // Disable privacy mode as we are sending cookies anyway.
642 request_info_
.privacy_mode
= PRIVACY_MODE_DISABLED
;
644 DoStartTransaction();
647 void URLRequestHttpJob::DoStartTransaction() {
648 // We may have been canceled while retrieving cookies.
649 if (GetStatus().is_success()) {
656 void URLRequestHttpJob::SaveCookiesAndNotifyHeadersComplete(int result
) {
657 // End of the call started in OnStartCompleted.
658 OnCallToDelegateComplete();
660 if (result
!= net::OK
) {
661 std::string
source("delegate");
662 request_
->net_log().AddEvent(NetLog::TYPE_CANCELLED
,
663 NetLog::StringCallback("source", &source
));
664 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED
, result
));
668 DCHECK(transaction_
.get());
670 const HttpResponseInfo
* response_info
= transaction_
->GetResponseInfo();
671 DCHECK(response_info
);
673 response_cookies_
.clear();
674 response_cookies_save_index_
= 0;
676 FetchResponseCookies(&response_cookies_
);
678 if (!GetResponseHeaders()->GetDateValue(&response_date_
))
679 response_date_
= base::Time();
681 // Now, loop over the response cookies, and attempt to persist each.
685 // If the save occurs synchronously, SaveNextCookie will loop and save the next
686 // cookie. If the save is deferred, the callback is responsible for continuing
687 // to iterate through the cookies.
688 // TODO(erikwright): Modify the CookieStore API to indicate via return value
689 // whether it completed synchronously or asynchronously.
690 // See http://crbug.com/131066.
691 void URLRequestHttpJob::SaveNextCookie() {
692 // No matter what, we want to report our status as IO pending since we will
693 // be notifying our consumer asynchronously via OnStartCompleted.
694 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING
, 0));
696 // Used to communicate with the callback. See the implementation of
698 scoped_refptr
<SharedBoolean
> callback_pending
= new SharedBoolean(false);
699 scoped_refptr
<SharedBoolean
> save_next_cookie_running
=
700 new SharedBoolean(true);
702 if (!(request_info_
.load_flags
& LOAD_DO_NOT_SAVE_COOKIES
) &&
703 GetCookieStore() && response_cookies_
.size() > 0) {
704 CookieOptions options
;
705 options
.set_include_httponly();
706 options
.set_server_time(response_date_
);
708 net::CookieStore::SetCookiesCallback
callback(
709 base::Bind(&URLRequestHttpJob::OnCookieSaved
,
710 weak_factory_
.GetWeakPtr(),
711 save_next_cookie_running
,
714 // Loop through the cookies as long as SetCookieWithOptionsAsync completes
716 while (!callback_pending
->data
&&
717 response_cookies_save_index_
< response_cookies_
.size()) {
719 response_cookies_
[response_cookies_save_index_
], &options
)) {
720 callback_pending
->data
= true;
721 GetCookieStore()->SetCookieWithOptionsAsync(
722 request_
->url(), response_cookies_
[response_cookies_save_index_
],
725 ++response_cookies_save_index_
;
729 save_next_cookie_running
->data
= false;
731 if (!callback_pending
->data
) {
732 response_cookies_
.clear();
733 response_cookies_save_index_
= 0;
734 SetStatus(URLRequestStatus()); // Clear the IO_PENDING status
735 NotifyHeadersComplete();
740 // |save_next_cookie_running| is true when the callback is bound and set to
741 // false when SaveNextCookie exits, allowing the callback to determine if the
742 // save occurred synchronously or asynchronously.
743 // |callback_pending| is false when the callback is invoked and will be set to
744 // true by the callback, allowing SaveNextCookie to detect whether the save
745 // occurred synchronously.
746 // See SaveNextCookie() for more information.
747 void URLRequestHttpJob::OnCookieSaved(
748 scoped_refptr
<SharedBoolean
> save_next_cookie_running
,
749 scoped_refptr
<SharedBoolean
> callback_pending
,
750 bool cookie_status
) {
751 callback_pending
->data
= false;
753 // If we were called synchronously, return.
754 if (save_next_cookie_running
->data
) {
758 // We were called asynchronously, so trigger the next save.
759 // We may have been canceled within OnSetCookie.
760 if (GetStatus().is_success()) {
767 void URLRequestHttpJob::FetchResponseCookies(
768 std::vector
<std::string
>* cookies
) {
769 const std::string name
= "Set-Cookie";
773 HttpResponseHeaders
* headers
= GetResponseHeaders();
774 while (headers
->EnumerateHeader(&iter
, name
, &value
)) {
776 cookies
->push_back(value
);
780 // NOTE: |ProcessStrictTransportSecurityHeader| and
781 // |ProcessPublicKeyPinsHeader| have very similar structures, by design.
782 void URLRequestHttpJob::ProcessStrictTransportSecurityHeader() {
783 DCHECK(response_info_
);
784 TransportSecurityState
* security_state
=
785 request_
->context()->transport_security_state();
786 const SSLInfo
& ssl_info
= response_info_
->ssl_info
;
788 // Only accept HSTS headers on HTTPS connections that have no
789 // certificate errors.
790 if (!ssl_info
.is_valid() || IsCertStatusError(ssl_info
.cert_status
) ||
794 // http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec:
796 // If a UA receives more than one STS header field in a HTTP response
797 // message over secure transport, then the UA MUST process only the
798 // first such header field.
799 HttpResponseHeaders
* headers
= GetResponseHeaders();
801 if (headers
->EnumerateHeader(NULL
, "Strict-Transport-Security", &value
))
802 security_state
->AddHSTSHeader(request_info_
.url
.host(), value
);
805 void URLRequestHttpJob::ProcessPublicKeyPinsHeader() {
806 DCHECK(response_info_
);
807 TransportSecurityState
* security_state
=
808 request_
->context()->transport_security_state();
809 const SSLInfo
& ssl_info
= response_info_
->ssl_info
;
811 // Only accept HPKP headers on HTTPS connections that have no
812 // certificate errors.
813 if (!ssl_info
.is_valid() || IsCertStatusError(ssl_info
.cert_status
) ||
817 // http://tools.ietf.org/html/draft-ietf-websec-key-pinning:
819 // If a UA receives more than one PKP header field in an HTTP
820 // response message over secure transport, then the UA MUST process
821 // only the first such header field.
822 HttpResponseHeaders
* headers
= GetResponseHeaders();
824 if (headers
->EnumerateHeader(NULL
, "Public-Key-Pins", &value
))
825 security_state
->AddHPKPHeader(request_info_
.url
.host(), value
, ssl_info
);
828 void URLRequestHttpJob::OnStartCompleted(int result
) {
829 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424359 is fixed.
830 tracked_objects::ScopedTracker
tracking_profile(
831 FROM_HERE_WITH_EXPLICIT_FUNCTION(
832 "424359 URLRequestHttpJob::OnStartCompleted"));
836 // If the request was destroyed, then there is no more work to do.
840 // If the job is done (due to cancellation), can just ignore this
845 receive_headers_end_
= base::TimeTicks::Now();
847 // Clear the IO_PENDING status
848 SetStatus(URLRequestStatus());
850 const URLRequestContext
* context
= request_
->context();
852 if (result
== ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
&&
853 transaction_
->GetResponseInfo() != NULL
) {
854 FraudulentCertificateReporter
* reporter
=
855 context
->fraudulent_certificate_reporter();
856 if (reporter
!= NULL
) {
857 const SSLInfo
& ssl_info
= transaction_
->GetResponseInfo()->ssl_info
;
858 const std::string
& host
= request_
->url().host();
860 reporter
->SendReport(host
, ssl_info
);
865 if (transaction_
&& transaction_
->GetResponseInfo()) {
866 SetProxyServer(transaction_
->GetResponseInfo()->proxy_server
);
868 scoped_refptr
<HttpResponseHeaders
> headers
= GetResponseHeaders();
869 if (network_delegate()) {
870 // Note that |this| may not be deleted until
871 // |on_headers_received_callback_| or
872 // |NetworkDelegate::URLRequestDestroyed()| has been called.
874 allowed_unsafe_redirect_url_
= GURL();
875 int error
= network_delegate()->NotifyHeadersReceived(
877 on_headers_received_callback_
,
879 &override_response_headers_
,
880 &allowed_unsafe_redirect_url_
);
881 if (error
!= net::OK
) {
882 if (error
== net::ERR_IO_PENDING
) {
883 awaiting_callback_
= true;
885 std::string
source("delegate");
886 request_
->net_log().AddEvent(NetLog::TYPE_CANCELLED
,
887 NetLog::StringCallback("source",
889 OnCallToDelegateComplete();
890 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED
, error
));
896 SaveCookiesAndNotifyHeadersComplete(net::OK
);
897 } else if (IsCertificateError(result
)) {
898 // We encountered an SSL certificate error.
899 if (result
== ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY
||
900 result
== ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
) {
901 // These are hard failures. They're handled separately and don't have
902 // the correct cert status, so set it here.
903 SSLInfo
info(transaction_
->GetResponseInfo()->ssl_info
);
904 info
.cert_status
= MapNetErrorToCertStatus(result
);
905 NotifySSLCertificateError(info
, true);
907 // Maybe overridable, maybe not. Ask the delegate to decide.
908 const URLRequestContext
* context
= request_
->context();
909 TransportSecurityState
* state
= context
->transport_security_state();
911 state
&& state
->ShouldSSLErrorsBeFatal(request_info_
.url
.host());
912 NotifySSLCertificateError(
913 transaction_
->GetResponseInfo()->ssl_info
, fatal
);
915 } else if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
) {
916 NotifyCertificateRequested(
917 transaction_
->GetResponseInfo()->cert_request_info
.get());
919 // Even on an error, there may be useful information in the response
920 // info (e.g. whether there's a cached copy).
921 if (transaction_
.get())
922 response_info_
= transaction_
->GetResponseInfo();
923 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED
, result
));
927 void URLRequestHttpJob::OnHeadersReceivedCallback(int result
) {
928 awaiting_callback_
= false;
930 // Check that there are no callbacks to already canceled requests.
931 DCHECK_NE(URLRequestStatus::CANCELED
, GetStatus().status());
933 SaveCookiesAndNotifyHeadersComplete(result
);
936 void URLRequestHttpJob::OnReadCompleted(int result
) {
937 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424359 is fixed.
938 tracked_objects::ScopedTracker
tracking_profile(
939 FROM_HERE_WITH_EXPLICIT_FUNCTION(
940 "424359 URLRequestHttpJob::OnReadCompleted"));
942 read_in_progress_
= false;
944 if (ShouldFixMismatchedContentLength(result
))
948 NotifyDone(URLRequestStatus());
949 } else if (result
< 0) {
950 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED
, result
));
952 // Clear the IO_PENDING status
953 SetStatus(URLRequestStatus());
956 NotifyReadComplete(result
);
959 void URLRequestHttpJob::RestartTransactionWithAuth(
960 const AuthCredentials
& credentials
) {
961 auth_credentials_
= credentials
;
963 // These will be reset in OnStartCompleted.
964 response_info_
= NULL
;
965 receive_headers_end_
= base::TimeTicks();
966 response_cookies_
.clear();
970 // Update the cookies, since the cookie store may have been updated from the
971 // headers in the 401/407. Since cookies were already appended to
972 // extra_headers, we need to strip them out before adding them again.
973 request_info_
.extra_headers
.RemoveHeader(HttpRequestHeaders::kCookie
);
975 AddCookieHeaderAndStart();
978 void URLRequestHttpJob::SetUpload(UploadDataStream
* upload
) {
979 DCHECK(!transaction_
.get()) << "cannot change once started";
980 request_info_
.upload_data_stream
= upload
;
983 void URLRequestHttpJob::SetExtraRequestHeaders(
984 const HttpRequestHeaders
& headers
) {
985 DCHECK(!transaction_
.get()) << "cannot change once started";
986 request_info_
.extra_headers
.CopyFrom(headers
);
989 LoadState
URLRequestHttpJob::GetLoadState() const {
990 return transaction_
.get() ?
991 transaction_
->GetLoadState() : LOAD_STATE_IDLE
;
994 UploadProgress
URLRequestHttpJob::GetUploadProgress() const {
995 return transaction_
.get() ?
996 transaction_
->GetUploadProgress() : UploadProgress();
999 bool URLRequestHttpJob::GetMimeType(std::string
* mime_type
) const {
1000 DCHECK(transaction_
.get());
1002 if (!response_info_
)
1005 return GetResponseHeaders()->GetMimeType(mime_type
);
1008 bool URLRequestHttpJob::GetCharset(std::string
* charset
) {
1009 DCHECK(transaction_
.get());
1011 if (!response_info_
)
1014 return GetResponseHeaders()->GetCharset(charset
);
1017 void URLRequestHttpJob::GetResponseInfo(HttpResponseInfo
* info
) {
1020 if (response_info_
) {
1021 DCHECK(transaction_
.get());
1023 *info
= *response_info_
;
1024 if (override_response_headers_
.get())
1025 info
->headers
= override_response_headers_
;
1029 void URLRequestHttpJob::GetLoadTimingInfo(
1030 LoadTimingInfo
* load_timing_info
) const {
1031 // If haven't made it far enough to receive any headers, don't return
1032 // anything. This makes for more consistent behavior in the case of errors.
1033 if (!transaction_
|| receive_headers_end_
.is_null())
1035 if (transaction_
->GetLoadTimingInfo(load_timing_info
))
1036 load_timing_info
->receive_headers_end
= receive_headers_end_
;
1039 bool URLRequestHttpJob::GetResponseCookies(std::vector
<std::string
>* cookies
) {
1040 DCHECK(transaction_
.get());
1042 if (!response_info_
)
1045 // TODO(darin): Why are we extracting response cookies again? Perhaps we
1046 // should just leverage response_cookies_.
1049 FetchResponseCookies(cookies
);
1053 int URLRequestHttpJob::GetResponseCode() const {
1054 DCHECK(transaction_
.get());
1056 if (!response_info_
)
1059 return GetResponseHeaders()->response_code();
1062 Filter
* URLRequestHttpJob::SetupFilter() const {
1063 DCHECK(transaction_
.get());
1064 if (!response_info_
)
1067 std::vector
<Filter::FilterType
> encoding_types
;
1068 std::string encoding_type
;
1069 HttpResponseHeaders
* headers
= GetResponseHeaders();
1071 while (headers
->EnumerateHeader(&iter
, "Content-Encoding", &encoding_type
)) {
1072 encoding_types
.push_back(Filter::ConvertEncodingToType(encoding_type
));
1075 if (filter_context_
->SdchResponseExpected()) {
1076 // We are wary of proxies that discard or damage SDCH encoding. If a server
1077 // explicitly states that this is not SDCH content, then we can correct our
1078 // assumption that this is an SDCH response, and avoid the need to recover
1079 // as though the content is corrupted (when we discover it is not SDCH
1081 std::string sdch_response_status
;
1083 while (headers
->EnumerateHeader(&iter
, "X-Sdch-Encode",
1084 &sdch_response_status
)) {
1085 if (sdch_response_status
== "0") {
1086 filter_context_
->ResetSdchResponseToFalse();
1092 // Even if encoding types are empty, there is a chance that we need to add
1093 // some decoding, as some proxies strip encoding completely. In such cases,
1094 // we may need to add (for example) SDCH filtering (when the context suggests
1095 // it is appropriate).
1096 Filter::FixupEncodingTypes(*filter_context_
, &encoding_types
);
1098 return !encoding_types
.empty()
1099 ? Filter::Factory(encoding_types
, *filter_context_
) : NULL
;
1102 bool URLRequestHttpJob::CopyFragmentOnRedirect(const GURL
& location
) const {
1103 // Allow modification of reference fragments by default, unless
1104 // |allowed_unsafe_redirect_url_| is set and equal to the redirect URL.
1105 // When this is the case, we assume that the network delegate has set the
1106 // desired redirect URL (with or without fragment), so it must not be changed
1108 return !allowed_unsafe_redirect_url_
.is_valid() ||
1109 allowed_unsafe_redirect_url_
!= location
;
1112 bool URLRequestHttpJob::IsSafeRedirect(const GURL
& location
) {
1113 // HTTP is always safe.
1114 // TODO(pauljensen): Remove once crbug.com/146591 is fixed.
1115 if (location
.is_valid() &&
1116 (location
.scheme() == "http" || location
.scheme() == "https")) {
1119 // Delegates may mark a URL as safe for redirection.
1120 if (allowed_unsafe_redirect_url_
.is_valid() &&
1121 allowed_unsafe_redirect_url_
== location
) {
1124 // Query URLRequestJobFactory as to whether |location| would be safe to
1126 return request_
->context()->job_factory() &&
1127 request_
->context()->job_factory()->IsSafeRedirectTarget(location
);
1130 bool URLRequestHttpJob::NeedsAuth() {
1131 int code
= GetResponseCode();
1135 // Check if we need either Proxy or WWW Authentication. This could happen
1136 // because we either provided no auth info, or provided incorrect info.
1139 if (proxy_auth_state_
== AUTH_STATE_CANCELED
)
1141 proxy_auth_state_
= AUTH_STATE_NEED_AUTH
;
1144 if (server_auth_state_
== AUTH_STATE_CANCELED
)
1146 server_auth_state_
= AUTH_STATE_NEED_AUTH
;
1152 void URLRequestHttpJob::GetAuthChallengeInfo(
1153 scoped_refptr
<AuthChallengeInfo
>* result
) {
1154 DCHECK(transaction_
.get());
1155 DCHECK(response_info_
);
1158 DCHECK(proxy_auth_state_
== AUTH_STATE_NEED_AUTH
||
1159 server_auth_state_
== AUTH_STATE_NEED_AUTH
);
1160 DCHECK((GetResponseHeaders()->response_code() == HTTP_UNAUTHORIZED
) ||
1161 (GetResponseHeaders()->response_code() ==
1162 HTTP_PROXY_AUTHENTICATION_REQUIRED
));
1164 *result
= response_info_
->auth_challenge
;
1167 void URLRequestHttpJob::SetAuth(const AuthCredentials
& credentials
) {
1168 DCHECK(transaction_
.get());
1170 // Proxy gets set first, then WWW.
1171 if (proxy_auth_state_
== AUTH_STATE_NEED_AUTH
) {
1172 proxy_auth_state_
= AUTH_STATE_HAVE_AUTH
;
1174 DCHECK_EQ(server_auth_state_
, AUTH_STATE_NEED_AUTH
);
1175 server_auth_state_
= AUTH_STATE_HAVE_AUTH
;
1178 RestartTransactionWithAuth(credentials
);
1181 void URLRequestHttpJob::CancelAuth() {
1182 // Proxy gets set first, then WWW.
1183 if (proxy_auth_state_
== AUTH_STATE_NEED_AUTH
) {
1184 proxy_auth_state_
= AUTH_STATE_CANCELED
;
1186 DCHECK_EQ(server_auth_state_
, AUTH_STATE_NEED_AUTH
);
1187 server_auth_state_
= AUTH_STATE_CANCELED
;
1190 // These will be reset in OnStartCompleted.
1191 response_info_
= NULL
;
1192 receive_headers_end_
= base::TimeTicks::Now();
1193 response_cookies_
.clear();
1197 // OK, let the consumer read the error page...
1199 // Because we set the AUTH_STATE_CANCELED flag, NeedsAuth will return false,
1200 // which will cause the consumer to receive OnResponseStarted instead of
1203 // We have to do this via InvokeLater to avoid "recursing" the consumer.
1205 base::MessageLoop::current()->PostTask(
1207 base::Bind(&URLRequestHttpJob::OnStartCompleted
,
1208 weak_factory_
.GetWeakPtr(), OK
));
1211 void URLRequestHttpJob::ContinueWithCertificate(
1212 X509Certificate
* client_cert
) {
1213 DCHECK(transaction_
.get());
1215 DCHECK(!response_info_
) << "should not have a response yet";
1216 receive_headers_end_
= base::TimeTicks();
1220 // No matter what, we want to report our status as IO pending since we will
1221 // be notifying our consumer asynchronously via OnStartCompleted.
1222 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING
, 0));
1224 int rv
= transaction_
->RestartWithCertificate(client_cert
, start_callback_
);
1225 if (rv
== ERR_IO_PENDING
)
1228 // The transaction started synchronously, but we need to notify the
1229 // URLRequest delegate via the message loop.
1230 base::MessageLoop::current()->PostTask(
1232 base::Bind(&URLRequestHttpJob::OnStartCompleted
,
1233 weak_factory_
.GetWeakPtr(), rv
));
1236 void URLRequestHttpJob::ContinueDespiteLastError() {
1237 // If the transaction was destroyed, then the job was cancelled.
1238 if (!transaction_
.get())
1241 DCHECK(!response_info_
) << "should not have a response yet";
1242 receive_headers_end_
= base::TimeTicks();
1246 // No matter what, we want to report our status as IO pending since we will
1247 // be notifying our consumer asynchronously via OnStartCompleted.
1248 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING
, 0));
1250 int rv
= transaction_
->RestartIgnoringLastError(start_callback_
);
1251 if (rv
== ERR_IO_PENDING
)
1254 // The transaction started synchronously, but we need to notify the
1255 // URLRequest delegate via the message loop.
1256 base::MessageLoop::current()->PostTask(
1258 base::Bind(&URLRequestHttpJob::OnStartCompleted
,
1259 weak_factory_
.GetWeakPtr(), rv
));
1262 void URLRequestHttpJob::ResumeNetworkStart() {
1263 DCHECK(transaction_
.get());
1264 transaction_
->ResumeNetworkStart();
1267 bool URLRequestHttpJob::ShouldFixMismatchedContentLength(int rv
) const {
1268 // Some servers send the body compressed, but specify the content length as
1269 // the uncompressed size. Although this violates the HTTP spec we want to
1270 // support it (as IE and FireFox do), but *only* for an exact match.
1271 // See http://crbug.com/79694.
1272 if (rv
== net::ERR_CONTENT_LENGTH_MISMATCH
||
1273 rv
== net::ERR_INCOMPLETE_CHUNKED_ENCODING
) {
1274 if (request_
&& request_
->response_headers()) {
1275 int64 expected_length
= request_
->response_headers()->GetContentLength();
1276 VLOG(1) << __FUNCTION__
<< "() "
1277 << "\"" << request_
->url().spec() << "\""
1278 << " content-length = " << expected_length
1279 << " pre total = " << prefilter_bytes_read()
1280 << " post total = " << postfilter_bytes_read();
1281 if (postfilter_bytes_read() == expected_length
) {
1290 bool URLRequestHttpJob::ReadRawData(IOBuffer
* buf
, int buf_size
,
1292 DCHECK_NE(buf_size
, 0);
1294 DCHECK(!read_in_progress_
);
1296 int rv
= transaction_
->Read(
1298 base::Bind(&URLRequestHttpJob::OnReadCompleted
, base::Unretained(this)));
1300 if (ShouldFixMismatchedContentLength(rv
))
1306 DoneWithRequest(FINISHED
);
1310 if (rv
== ERR_IO_PENDING
) {
1311 read_in_progress_
= true;
1312 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING
, 0));
1314 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED
, rv
));
1320 void URLRequestHttpJob::StopCaching() {
1321 if (transaction_
.get())
1322 transaction_
->StopCaching();
1325 bool URLRequestHttpJob::GetFullRequestHeaders(
1326 HttpRequestHeaders
* headers
) const {
1330 return transaction_
->GetFullRequestHeaders(headers
);
1333 int64
URLRequestHttpJob::GetTotalReceivedBytes() const {
1337 return transaction_
->GetTotalReceivedBytes();
1340 void URLRequestHttpJob::DoneReading() {
1342 transaction_
->DoneReading();
1344 DoneWithRequest(FINISHED
);
1347 void URLRequestHttpJob::DoneReadingRedirectResponse() {
1349 if (transaction_
->GetResponseInfo()->headers
->IsRedirect(NULL
)) {
1350 // If the original headers indicate a redirect, go ahead and cache the
1351 // response, even if the |override_response_headers_| are a redirect to
1352 // another location.
1353 transaction_
->DoneReading();
1355 // Otherwise, |override_response_headers_| must be non-NULL and contain
1356 // bogus headers indicating a redirect.
1357 DCHECK(override_response_headers_
.get());
1358 DCHECK(override_response_headers_
->IsRedirect(NULL
));
1359 transaction_
->StopCaching();
1362 DoneWithRequest(FINISHED
);
1365 HostPortPair
URLRequestHttpJob::GetSocketAddress() const {
1366 return response_info_
? response_info_
->socket_address
: HostPortPair();
1369 void URLRequestHttpJob::RecordTimer() {
1370 if (request_creation_time_
.is_null()) {
1372 << "The same transaction shouldn't start twice without new timing.";
1376 base::TimeDelta to_start
= base::Time::Now() - request_creation_time_
;
1377 request_creation_time_
= base::Time();
1379 UMA_HISTOGRAM_MEDIUM_TIMES("Net.HttpTimeToFirstByte", to_start
);
1382 void URLRequestHttpJob::ResetTimer() {
1383 if (!request_creation_time_
.is_null()) {
1385 << "The timer was reset before it was recorded.";
1388 request_creation_time_
= base::Time::Now();
1391 void URLRequestHttpJob::UpdatePacketReadTimes() {
1392 if (!packet_timing_enabled_
)
1395 if (filter_input_byte_count() <= bytes_observed_in_packets_
) {
1396 DCHECK_EQ(filter_input_byte_count(), bytes_observed_in_packets_
);
1397 return; // No new bytes have arrived.
1400 base::Time
now(base::Time::Now());
1401 if (!bytes_observed_in_packets_
)
1402 request_time_snapshot_
= now
;
1403 final_packet_time_
= now
;
1405 bytes_observed_in_packets_
= filter_input_byte_count();
1408 void URLRequestHttpJob::RecordPacketStats(
1409 FilterContext::StatisticSelector statistic
) const {
1410 if (!packet_timing_enabled_
|| (final_packet_time_
== base::Time()))
1413 base::TimeDelta duration
= final_packet_time_
- request_time_snapshot_
;
1414 switch (statistic
) {
1415 case FilterContext::SDCH_DECODE
: {
1416 UMA_HISTOGRAM_CUSTOM_COUNTS("Sdch3.Network_Decode_Bytes_Processed_b",
1417 static_cast<int>(bytes_observed_in_packets_
), 500, 100000, 100);
1420 case FilterContext::SDCH_PASSTHROUGH
: {
1421 // Despite advertising a dictionary, we handled non-sdch compressed
1426 case FilterContext::SDCH_EXPERIMENT_DECODE
: {
1427 UMA_HISTOGRAM_CUSTOM_TIMES("Sdch3.Experiment3_Decode",
1429 base::TimeDelta::FromMilliseconds(20),
1430 base::TimeDelta::FromMinutes(10), 100);
1433 case FilterContext::SDCH_EXPERIMENT_HOLDBACK
: {
1434 UMA_HISTOGRAM_CUSTOM_TIMES("Sdch3.Experiment3_Holdback",
1436 base::TimeDelta::FromMilliseconds(20),
1437 base::TimeDelta::FromMinutes(10), 100);
1446 // The common type of histogram we use for all compression-tracking histograms.
1447 #define COMPRESSION_HISTOGRAM(name, sample) \
1449 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.Compress." name, sample, \
1450 500, 1000000, 100); \
1453 void URLRequestHttpJob::RecordCompressionHistograms() {
1458 if (is_cached_content_
|| // Don't record cached content
1459 !GetStatus().is_success() || // Don't record failed content
1460 !IsCompressibleContent() || // Only record compressible content
1461 !prefilter_bytes_read()) // Zero-byte responses aren't useful.
1464 // Miniature requests aren't really compressible. Don't count them.
1465 const int kMinSize
= 16;
1466 if (prefilter_bytes_read() < kMinSize
)
1469 // Only record for http or https urls.
1470 bool is_http
= request_
->url().SchemeIs("http");
1471 bool is_https
= request_
->url().SchemeIs("https");
1472 if (!is_http
&& !is_https
)
1475 int compressed_B
= prefilter_bytes_read();
1476 int decompressed_B
= postfilter_bytes_read();
1477 bool was_filtered
= HasFilter();
1479 // We want to record how often downloaded resources are compressed.
1480 // But, we recognize that different protocols may have different
1481 // properties. So, for each request, we'll put it into one of 3
1484 // Proxies cannot tamper with compression headers with SSL.
1485 // b) Non-SSL, loaded-via-proxy resources
1486 // In this case, we know a proxy might have interfered.
1487 // c) Non-SSL, loaded-without-proxy resources
1488 // In this case, we know there was no explicit proxy. However,
1489 // it is possible that a transparent proxy was still interfering.
1491 // For each group, we record the same 3 histograms.
1495 COMPRESSION_HISTOGRAM("SSL.BytesBeforeCompression", compressed_B
);
1496 COMPRESSION_HISTOGRAM("SSL.BytesAfterCompression", decompressed_B
);
1498 COMPRESSION_HISTOGRAM("SSL.ShouldHaveBeenCompressed", decompressed_B
);
1503 if (request_
->was_fetched_via_proxy()) {
1505 COMPRESSION_HISTOGRAM("Proxy.BytesBeforeCompression", compressed_B
);
1506 COMPRESSION_HISTOGRAM("Proxy.BytesAfterCompression", decompressed_B
);
1508 COMPRESSION_HISTOGRAM("Proxy.ShouldHaveBeenCompressed", decompressed_B
);
1514 COMPRESSION_HISTOGRAM("NoProxy.BytesBeforeCompression", compressed_B
);
1515 COMPRESSION_HISTOGRAM("NoProxy.BytesAfterCompression", decompressed_B
);
1517 COMPRESSION_HISTOGRAM("NoProxy.ShouldHaveBeenCompressed", decompressed_B
);
1521 bool URLRequestHttpJob::IsCompressibleContent() const {
1522 std::string mime_type
;
1523 return GetMimeType(&mime_type
) &&
1524 (IsSupportedJavascriptMimeType(mime_type
.c_str()) ||
1525 IsSupportedNonImageMimeType(mime_type
.c_str()));
1528 void URLRequestHttpJob::RecordPerfHistograms(CompletionCause reason
) {
1529 if (start_time_
.is_null())
1532 base::TimeDelta total_time
= base::TimeTicks::Now() - start_time_
;
1533 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTime", total_time
);
1535 if (reason
== FINISHED
) {
1536 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeSuccess", total_time
);
1538 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeCancel", total_time
);
1541 if (response_info_
) {
1542 if (response_info_
->was_cached
) {
1543 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeCached", total_time
);
1545 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeNotCached", total_time
);
1549 if (request_info_
.load_flags
& LOAD_PREFETCH
&& !request_
->was_cached())
1550 UMA_HISTOGRAM_COUNTS("Net.Prefetch.PrefilterBytesReadFromNetwork",
1551 prefilter_bytes_read());
1553 start_time_
= base::TimeTicks();
1556 void URLRequestHttpJob::DoneWithRequest(CompletionCause reason
) {
1560 RecordPerfHistograms(reason
);
1561 if (reason
== FINISHED
) {
1562 request_
->set_received_response_content_length(prefilter_bytes_read());
1563 RecordCompressionHistograms();
1567 HttpResponseHeaders
* URLRequestHttpJob::GetResponseHeaders() const {
1568 DCHECK(transaction_
.get());
1569 DCHECK(transaction_
->GetResponseInfo());
1570 return override_response_headers_
.get() ?
1571 override_response_headers_
.get() :
1572 transaction_
->GetResponseInfo()->headers
.get();
1575 void URLRequestHttpJob::NotifyURLRequestDestroyed() {
1576 awaiting_callback_
= false;