Add wfh@ to chrome/browser/resources/plugin_metadata OWNERS.
[chromium-blink-merge.git] / net / url_request / url_request_http_job.cc
blob68858c147586fc902d58c50f946829c46bf543e1
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"
8 #include "base/bind.h"
9 #include "base/bind_helpers.h"
10 #include "base/command_line.h"
11 #include "base/compiler_specific.h"
12 #include "base/debug/alias.h"
13 #include "base/file_version_info.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/metrics/field_trial.h"
16 #include "base/metrics/histogram.h"
17 #include "base/profiler/scoped_tracker.h"
18 #include "base/rand_util.h"
19 #include "base/strings/string_util.h"
20 #include "base/time/time.h"
21 #include "net/base/host_port_pair.h"
22 #include "net/base/load_flags.h"
23 #include "net/base/mime_util.h"
24 #include "net/base/net_errors.h"
25 #include "net/base/net_util.h"
26 #include "net/base/network_delegate.h"
27 #include "net/base/sdch_manager.h"
28 #include "net/base/sdch_net_log_params.h"
29 #include "net/cert/cert_status_flags.h"
30 #include "net/cookies/cookie_store.h"
31 #include "net/http/http_content_disposition.h"
32 #include "net/http/http_network_session.h"
33 #include "net/http/http_request_headers.h"
34 #include "net/http/http_response_headers.h"
35 #include "net/http/http_response_info.h"
36 #include "net/http/http_status_code.h"
37 #include "net/http/http_transaction.h"
38 #include "net/http/http_transaction_factory.h"
39 #include "net/http/http_util.h"
40 #include "net/proxy/proxy_info.h"
41 #include "net/ssl/ssl_cert_request_info.h"
42 #include "net/ssl/ssl_config_service.h"
43 #include "net/url_request/fraudulent_certificate_reporter.h"
44 #include "net/url_request/http_user_agent_settings.h"
45 #include "net/url_request/url_request.h"
46 #include "net/url_request/url_request_context.h"
47 #include "net/url_request/url_request_error_job.h"
48 #include "net/url_request/url_request_job_factory.h"
49 #include "net/url_request/url_request_redirect_job.h"
50 #include "net/url_request/url_request_throttler_header_adapter.h"
51 #include "net/url_request/url_request_throttler_manager.h"
52 #include "net/websockets/websocket_handshake_stream_base.h"
54 static const char kAvailDictionaryHeader[] = "Avail-Dictionary";
56 namespace net {
58 class URLRequestHttpJob::HttpFilterContext : public FilterContext {
59 public:
60 explicit HttpFilterContext(URLRequestHttpJob* job);
61 ~HttpFilterContext() override;
63 // FilterContext implementation.
64 bool GetMimeType(std::string* mime_type) const override;
65 bool GetURL(GURL* gurl) const override;
66 bool GetContentDisposition(std::string* disposition) const override;
67 base::Time GetRequestTime() const override;
68 bool IsCachedContent() const override;
69 bool IsDownload() const override;
70 SdchManager::DictionarySet* SdchDictionariesAdvertised() const override;
71 int64 GetByteReadCount() const override;
72 int GetResponseCode() const override;
73 const URLRequestContext* GetURLRequestContext() const override;
74 void RecordPacketStats(StatisticSelector statistic) const override;
75 const BoundNetLog& GetNetLog() const override;
77 private:
78 URLRequestHttpJob* job_;
80 // URLRequestHttpJob may be detached from URLRequest, but we still need to
81 // return something.
82 BoundNetLog dummy_log_;
84 DISALLOW_COPY_AND_ASSIGN(HttpFilterContext);
87 URLRequestHttpJob::HttpFilterContext::HttpFilterContext(URLRequestHttpJob* job)
88 : job_(job) {
89 DCHECK(job_);
92 URLRequestHttpJob::HttpFilterContext::~HttpFilterContext() {
95 bool URLRequestHttpJob::HttpFilterContext::GetMimeType(
96 std::string* mime_type) const {
97 return job_->GetMimeType(mime_type);
100 bool URLRequestHttpJob::HttpFilterContext::GetURL(GURL* gurl) const {
101 if (!job_->request())
102 return false;
103 *gurl = job_->request()->url();
104 return true;
107 bool URLRequestHttpJob::HttpFilterContext::GetContentDisposition(
108 std::string* disposition) const {
109 HttpResponseHeaders* headers = job_->GetResponseHeaders();
110 void *iter = NULL;
111 return headers->EnumerateHeader(&iter, "Content-Disposition", disposition);
114 base::Time URLRequestHttpJob::HttpFilterContext::GetRequestTime() const {
115 return job_->request() ? job_->request()->request_time() : base::Time();
118 bool URLRequestHttpJob::HttpFilterContext::IsCachedContent() const {
119 return job_->is_cached_content_;
122 bool URLRequestHttpJob::HttpFilterContext::IsDownload() const {
123 return (job_->request_info_.load_flags & LOAD_IS_DOWNLOAD) != 0;
126 SdchManager::DictionarySet*
127 URLRequestHttpJob::HttpFilterContext::SdchDictionariesAdvertised() const {
128 return job_->dictionaries_advertised_.get();
131 int64 URLRequestHttpJob::HttpFilterContext::GetByteReadCount() const {
132 return job_->filter_input_byte_count();
135 int URLRequestHttpJob::HttpFilterContext::GetResponseCode() const {
136 return job_->GetResponseCode();
139 const URLRequestContext*
140 URLRequestHttpJob::HttpFilterContext::GetURLRequestContext() const {
141 return job_->request() ? job_->request()->context() : NULL;
144 void URLRequestHttpJob::HttpFilterContext::RecordPacketStats(
145 StatisticSelector statistic) const {
146 job_->RecordPacketStats(statistic);
149 const BoundNetLog& URLRequestHttpJob::HttpFilterContext::GetNetLog() const {
150 return job_->request() ? job_->request()->net_log() : dummy_log_;
153 // TODO(darin): make sure the port blocking code is not lost
154 // static
155 URLRequestJob* URLRequestHttpJob::Factory(URLRequest* request,
156 NetworkDelegate* network_delegate,
157 const std::string& scheme) {
158 DCHECK(scheme == "http" || scheme == "https" || scheme == "ws" ||
159 scheme == "wss");
161 if (!request->context()->http_transaction_factory()) {
162 NOTREACHED() << "requires a valid context";
163 return new URLRequestErrorJob(
164 request, network_delegate, ERR_INVALID_ARGUMENT);
167 GURL redirect_url;
168 if (request->GetHSTSRedirect(&redirect_url)) {
169 return new URLRequestRedirectJob(
170 request, network_delegate, redirect_url,
171 // Use status code 307 to preserve the method, so POST requests work.
172 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "HSTS");
174 return new URLRequestHttpJob(request,
175 network_delegate,
176 request->context()->http_user_agent_settings());
179 URLRequestHttpJob::URLRequestHttpJob(
180 URLRequest* request,
181 NetworkDelegate* network_delegate,
182 const HttpUserAgentSettings* http_user_agent_settings)
183 : URLRequestJob(request, network_delegate),
184 priority_(DEFAULT_PRIORITY),
185 response_info_(NULL),
186 response_cookies_save_index_(0),
187 proxy_auth_state_(AUTH_STATE_DONT_NEED_AUTH),
188 server_auth_state_(AUTH_STATE_DONT_NEED_AUTH),
189 start_callback_(base::Bind(&URLRequestHttpJob::OnStartCompleted,
190 base::Unretained(this))),
191 notify_before_headers_sent_callback_(
192 base::Bind(&URLRequestHttpJob::NotifyBeforeSendHeadersCallback,
193 base::Unretained(this))),
194 read_in_progress_(false),
195 throttling_entry_(NULL),
196 sdch_test_activated_(false),
197 sdch_test_control_(false),
198 is_cached_content_(false),
199 request_creation_time_(),
200 packet_timing_enabled_(false),
201 done_(false),
202 bytes_observed_in_packets_(0),
203 request_time_snapshot_(),
204 final_packet_time_(),
205 filter_context_(new HttpFilterContext(this)),
206 on_headers_received_callback_(
207 base::Bind(&URLRequestHttpJob::OnHeadersReceivedCallback,
208 base::Unretained(this))),
209 awaiting_callback_(false),
210 http_user_agent_settings_(http_user_agent_settings),
211 transaction_state_(TRANSACTION_WAS_NOT_INITIALIZED),
212 weak_factory_(this) {
213 URLRequestThrottlerManager* manager = request->context()->throttler_manager();
214 if (manager)
215 throttling_entry_ = manager->RegisterRequestUrl(request->url());
217 // TODO(battre) Remove this overriding once crbug.com/289715 has been
218 // resolved.
219 on_headers_received_callback_ =
220 base::Bind(&URLRequestHttpJob::OnHeadersReceivedCallbackForDebugging,
221 weak_factory_.GetWeakPtr());
223 ResetTimer();
226 URLRequestHttpJob::~URLRequestHttpJob() {
227 CHECK(!awaiting_callback_);
229 DCHECK(!sdch_test_control_ || !sdch_test_activated_);
230 if (!is_cached_content_) {
231 if (sdch_test_control_)
232 RecordPacketStats(FilterContext::SDCH_EXPERIMENT_HOLDBACK);
233 if (sdch_test_activated_)
234 RecordPacketStats(FilterContext::SDCH_EXPERIMENT_DECODE);
236 // Make sure SDCH filters are told to emit histogram data while
237 // filter_context_ is still alive.
238 DestroyFilters();
240 DoneWithRequest(ABORTED);
243 void URLRequestHttpJob::SetPriority(RequestPriority priority) {
244 priority_ = priority;
245 if (transaction_)
246 transaction_->SetPriority(priority_);
249 void URLRequestHttpJob::Start() {
250 DCHECK(!transaction_.get());
252 // URLRequest::SetReferrer ensures that we do not send username and password
253 // fields in the referrer.
254 GURL referrer(request_->referrer());
256 request_info_.url = request_->url();
257 request_info_.method = request_->method();
258 request_info_.load_flags = request_->load_flags();
259 // Enable privacy mode if cookie settings or flags tell us not send or
260 // save cookies.
261 bool enable_privacy_mode =
262 (request_info_.load_flags & LOAD_DO_NOT_SEND_COOKIES) ||
263 (request_info_.load_flags & LOAD_DO_NOT_SAVE_COOKIES) ||
264 CanEnablePrivacyMode();
265 // Privacy mode could still be disabled in OnCookiesLoaded if we are going
266 // to send previously saved cookies.
267 request_info_.privacy_mode = enable_privacy_mode ?
268 PRIVACY_MODE_ENABLED : PRIVACY_MODE_DISABLED;
270 // Strip Referer from request_info_.extra_headers to prevent, e.g., plugins
271 // from overriding headers that are controlled using other means. Otherwise a
272 // plugin could set a referrer although sending the referrer is inhibited.
273 request_info_.extra_headers.RemoveHeader(HttpRequestHeaders::kReferer);
275 // Our consumer should have made sure that this is a safe referrer. See for
276 // instance WebCore::FrameLoader::HideReferrer.
277 if (referrer.is_valid()) {
278 request_info_.extra_headers.SetHeader(HttpRequestHeaders::kReferer,
279 referrer.spec());
282 request_info_.extra_headers.SetHeaderIfMissing(
283 HttpRequestHeaders::kUserAgent,
284 http_user_agent_settings_ ?
285 http_user_agent_settings_->GetUserAgent() : std::string());
287 AddExtraHeaders();
288 AddCookieHeaderAndStart();
291 void URLRequestHttpJob::Kill() {
292 if (!transaction_.get())
293 return;
295 weak_factory_.InvalidateWeakPtrs();
296 DestroyTransaction();
297 URLRequestJob::Kill();
300 void URLRequestHttpJob::NotifyBeforeSendProxyHeadersCallback(
301 const ProxyInfo& proxy_info,
302 HttpRequestHeaders* request_headers) {
303 DCHECK(request_headers);
304 DCHECK_NE(URLRequestStatus::CANCELED, GetStatus().status());
305 if (network_delegate()) {
306 network_delegate()->NotifyBeforeSendProxyHeaders(
307 request_,
308 proxy_info,
309 request_headers);
313 void URLRequestHttpJob::NotifyHeadersComplete() {
314 DCHECK(!response_info_);
316 response_info_ = transaction_->GetResponseInfo();
318 // Save boolean, as we'll need this info at destruction time, and filters may
319 // also need this info.
320 is_cached_content_ = response_info_->was_cached;
322 if (!is_cached_content_ && throttling_entry_.get()) {
323 URLRequestThrottlerHeaderAdapter response_adapter(GetResponseHeaders());
324 throttling_entry_->UpdateWithResponse(request_info_.url.host(),
325 &response_adapter);
328 // The ordering of these calls is not important.
329 ProcessStrictTransportSecurityHeader();
330 ProcessPublicKeyPinsHeader();
332 // Handle the server notification of a new SDCH dictionary.
333 SdchManager* sdch_manager(request()->context()->sdch_manager());
334 if (sdch_manager) {
335 SdchProblemCode rv = sdch_manager->IsInSupportedDomain(request()->url());
336 if (rv != SDCH_OK) {
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));
344 } else {
345 const std::string name = "Get-Dictionary";
346 std::string url_text;
347 void* iter = NULL;
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
353 // several times
354 // before we even download it (so that we don't waste memory or
355 // bandwidth).
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);
362 if (rv != SDCH_OK) {
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 // Handle the server signalling no SDCH encoding.
375 if (dictionaries_advertised_) {
376 // We are wary of proxies that discard or damage SDCH encoding. If a server
377 // explicitly states that this is not SDCH content, then we can correct our
378 // assumption that this is an SDCH response, and avoid the need to recover
379 // as though the content is corrupted (when we discover it is not SDCH
380 // encoded).
381 std::string sdch_response_status;
382 void* iter = NULL;
383 while (GetResponseHeaders()->EnumerateHeader(&iter, "X-Sdch-Encode",
384 &sdch_response_status)) {
385 if (sdch_response_status == "0") {
386 dictionaries_advertised_.reset();
387 break;
392 // The HTTP transaction may be restarted several times for the purposes
393 // of sending authorization information. Each time it restarts, we get
394 // notified of the headers completion so that we can update the cookie store.
395 if (transaction_->IsReadyToRestartForAuth()) {
396 DCHECK(!response_info_->auth_challenge.get());
397 // TODO(battre): This breaks the webrequest API for
398 // URLRequestTestHTTP.BasicAuthWithCookies
399 // where OnBeforeSendHeaders -> OnSendHeaders -> OnBeforeSendHeaders
400 // occurs.
401 RestartTransactionWithAuth(AuthCredentials());
402 return;
405 URLRequestJob::NotifyHeadersComplete();
408 void URLRequestHttpJob::NotifyDone(const URLRequestStatus& status) {
409 DoneWithRequest(FINISHED);
410 URLRequestJob::NotifyDone(status);
413 void URLRequestHttpJob::DestroyTransaction() {
414 DCHECK(transaction_.get());
416 DoneWithRequest(ABORTED);
417 transaction_.reset();
418 transaction_state_ = TRANSACTION_WAS_DESTROYED;
419 response_info_ = NULL;
420 receive_headers_end_ = base::TimeTicks();
423 void URLRequestHttpJob::StartTransaction() {
424 if (network_delegate()) {
425 OnCallToDelegate();
426 int rv = network_delegate()->NotifyBeforeSendHeaders(
427 request_, notify_before_headers_sent_callback_,
428 &request_info_.extra_headers);
429 // If an extension blocks the request, we rely on the callback to
430 // MaybeStartTransactionInternal().
431 if (rv == ERR_IO_PENDING)
432 return;
433 MaybeStartTransactionInternal(rv);
434 return;
436 StartTransactionInternal();
439 void URLRequestHttpJob::NotifyBeforeSendHeadersCallback(int result) {
440 // Check that there are no callbacks to already canceled requests.
441 DCHECK_NE(URLRequestStatus::CANCELED, GetStatus().status());
443 MaybeStartTransactionInternal(result);
446 void URLRequestHttpJob::MaybeStartTransactionInternal(int result) {
447 OnCallToDelegateComplete();
448 if (result == OK) {
449 StartTransactionInternal();
450 } else {
451 std::string source("delegate");
452 request_->net_log().AddEvent(NetLog::TYPE_CANCELLED,
453 NetLog::StringCallback("source", &source));
454 NotifyCanceled();
455 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, result));
459 void URLRequestHttpJob::StartTransactionInternal() {
460 // NOTE: This method assumes that request_info_ is already setup properly.
462 // If we already have a transaction, then we should restart the transaction
463 // with auth provided by auth_credentials_.
465 int rv;
467 if (network_delegate()) {
468 network_delegate()->NotifySendHeaders(
469 request_, request_info_.extra_headers);
472 if (transaction_.get()) {
473 rv = transaction_->RestartWithAuth(auth_credentials_, start_callback_);
474 auth_credentials_ = AuthCredentials();
475 } else {
476 DCHECK(request_->context()->http_transaction_factory());
478 rv = request_->context()->http_transaction_factory()->CreateTransaction(
479 priority_, &transaction_);
480 if (rv == OK)
481 transaction_state_ = TRANSACTION_WAS_INITIALIZED;
483 if (rv == OK && request_info_.url.SchemeIsWSOrWSS()) {
484 base::SupportsUserData::Data* data = request_->GetUserData(
485 WebSocketHandshakeStreamBase::CreateHelper::DataKey());
486 if (data) {
487 transaction_->SetWebSocketHandshakeStreamCreateHelper(
488 static_cast<WebSocketHandshakeStreamBase::CreateHelper*>(data));
489 } else {
490 rv = ERR_DISALLOWED_URL_SCHEME;
494 if (rv == OK) {
495 transaction_->SetBeforeNetworkStartCallback(
496 base::Bind(&URLRequestHttpJob::NotifyBeforeNetworkStart,
497 base::Unretained(this)));
498 transaction_->SetBeforeProxyHeadersSentCallback(
499 base::Bind(&URLRequestHttpJob::NotifyBeforeSendProxyHeadersCallback,
500 base::Unretained(this)));
502 if (!throttling_entry_.get() ||
503 !throttling_entry_->ShouldRejectRequest(*request_,
504 network_delegate())) {
505 rv = transaction_->Start(
506 &request_info_, start_callback_, request_->net_log());
507 start_time_ = base::TimeTicks::Now();
508 } else {
509 // Special error code for the exponential back-off module.
510 rv = ERR_TEMPORARILY_THROTTLED;
515 if (rv == ERR_IO_PENDING)
516 return;
518 // The transaction started synchronously, but we need to notify the
519 // URLRequest delegate via the message loop.
520 base::MessageLoop::current()->PostTask(
521 FROM_HERE,
522 base::Bind(&URLRequestHttpJob::OnStartCompleted,
523 weak_factory_.GetWeakPtr(), rv));
526 void URLRequestHttpJob::AddExtraHeaders() {
527 SdchManager* sdch_manager = request()->context()->sdch_manager();
529 // Supply Accept-Encoding field only if it is not already provided.
530 // It should be provided IF the content is known to have restrictions on
531 // potential encoding, such as streaming multi-media.
532 // For details see bug 47381.
533 // TODO(jar, enal): jpeg files etc. should set up a request header if
534 // possible. Right now it is done only by buffered_resource_loader and
535 // simple_data_source.
536 if (!request_info_.extra_headers.HasHeader(
537 HttpRequestHeaders::kAcceptEncoding)) {
538 // We don't support SDCH responses to POST as there is a possibility
539 // of having SDCH encoded responses returned (e.g. by the cache)
540 // which we cannot decode, and in those situations, we will need
541 // to retransmit the request without SDCH, which is illegal for a POST.
542 bool advertise_sdch = sdch_manager != NULL && request()->method() != "POST";
543 if (advertise_sdch) {
544 SdchProblemCode rv = sdch_manager->IsInSupportedDomain(request()->url());
545 if (rv != SDCH_OK) {
546 advertise_sdch = false;
547 // If SDCH is just disabled, it is not a real error.
548 if (rv != SDCH_DISABLED && rv != SDCH_SECURE_SCHEME_NOT_SUPPORTED) {
549 SdchManager::SdchErrorRecovery(rv);
550 request()->net_log().AddEvent(
551 NetLog::TYPE_SDCH_DECODING_ERROR,
552 base::Bind(&NetLogSdchResourceProblemCallback, rv));
556 if (advertise_sdch) {
557 dictionaries_advertised_ =
558 sdch_manager->GetDictionarySet(request_->url());
561 // The AllowLatencyExperiment() is only true if we've successfully done a
562 // full SDCH compression recently in this browser session for this host.
563 // Note that for this path, there might be no applicable dictionaries,
564 // and hence we can't participate in the experiment.
565 if (dictionaries_advertised_ &&
566 sdch_manager->AllowLatencyExperiment(request_->url())) {
567 // We are participating in the test (or control), and hence we'll
568 // eventually record statistics via either SDCH_EXPERIMENT_DECODE or
569 // SDCH_EXPERIMENT_HOLDBACK, and we'll need some packet timing data.
570 packet_timing_enabled_ = true;
571 if (base::RandDouble() < .01) {
572 sdch_test_control_ = true; // 1% probability.
573 dictionaries_advertised_.reset();
574 advertise_sdch = false;
575 } else {
576 sdch_test_activated_ = true;
580 // Supply Accept-Encoding headers first so that it is more likely that they
581 // will be in the first transmitted packet. This can sometimes make it
582 // easier to filter and analyze the streams to assure that a proxy has not
583 // damaged these headers. Some proxies deliberately corrupt Accept-Encoding
584 // headers.
585 if (!advertise_sdch) {
586 // Tell the server what compression formats we support (other than SDCH).
587 request_info_.extra_headers.SetHeader(
588 HttpRequestHeaders::kAcceptEncoding, "gzip, deflate");
589 } else {
590 // Include SDCH in acceptable list.
591 request_info_.extra_headers.SetHeader(
592 HttpRequestHeaders::kAcceptEncoding, "gzip, deflate, sdch");
593 if (dictionaries_advertised_) {
594 request_info_.extra_headers.SetHeader(
595 kAvailDictionaryHeader,
596 dictionaries_advertised_->GetDictionaryClientHashList());
597 // Since we're tagging this transaction as advertising a dictionary,
598 // we'll definitely employ an SDCH filter (or tentative sdch filter)
599 // when we get a response. When done, we'll record histograms via
600 // SDCH_DECODE or SDCH_PASSTHROUGH. Hence we need to record packet
601 // arrival times.
602 packet_timing_enabled_ = true;
607 if (http_user_agent_settings_) {
608 // Only add default Accept-Language if the request didn't have it
609 // specified.
610 std::string accept_language =
611 http_user_agent_settings_->GetAcceptLanguage();
612 if (!accept_language.empty()) {
613 request_info_.extra_headers.SetHeaderIfMissing(
614 HttpRequestHeaders::kAcceptLanguage,
615 accept_language);
620 void URLRequestHttpJob::AddCookieHeaderAndStart() {
621 // No matter what, we want to report our status as IO pending since we will
622 // be notifying our consumer asynchronously via OnStartCompleted.
623 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
625 // If the request was destroyed, then there is no more work to do.
626 if (!request_)
627 return;
629 CookieStore* cookie_store = GetCookieStore();
630 if (cookie_store && !(request_info_.load_flags & LOAD_DO_NOT_SEND_COOKIES)) {
631 cookie_store->GetAllCookiesForURLAsync(
632 request_->url(),
633 base::Bind(&URLRequestHttpJob::CheckCookiePolicyAndLoad,
634 weak_factory_.GetWeakPtr()));
635 } else {
636 DoStartTransaction();
640 void URLRequestHttpJob::DoLoadCookies() {
641 CookieOptions options;
642 options.set_include_httponly();
643 GetCookieStore()->GetCookiesWithOptionsAsync(
644 request_->url(), options,
645 base::Bind(&URLRequestHttpJob::OnCookiesLoaded,
646 weak_factory_.GetWeakPtr()));
649 void URLRequestHttpJob::CheckCookiePolicyAndLoad(
650 const CookieList& cookie_list) {
651 if (CanGetCookies(cookie_list))
652 DoLoadCookies();
653 else
654 DoStartTransaction();
657 void URLRequestHttpJob::OnCookiesLoaded(const std::string& cookie_line) {
658 if (!cookie_line.empty()) {
659 request_info_.extra_headers.SetHeader(
660 HttpRequestHeaders::kCookie, cookie_line);
661 // Disable privacy mode as we are sending cookies anyway.
662 request_info_.privacy_mode = PRIVACY_MODE_DISABLED;
664 DoStartTransaction();
667 void URLRequestHttpJob::DoStartTransaction() {
668 // We may have been canceled while retrieving cookies.
669 if (GetStatus().is_success()) {
670 StartTransaction();
671 } else {
672 NotifyCanceled();
676 void URLRequestHttpJob::SaveCookiesAndNotifyHeadersComplete(int result) {
677 // End of the call started in OnStartCompleted.
678 OnCallToDelegateComplete();
680 if (result != net::OK) {
681 std::string source("delegate");
682 request_->net_log().AddEvent(NetLog::TYPE_CANCELLED,
683 NetLog::StringCallback("source", &source));
684 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, result));
685 return;
688 DCHECK(transaction_.get());
690 const HttpResponseInfo* response_info = transaction_->GetResponseInfo();
691 DCHECK(response_info);
693 response_cookies_.clear();
694 response_cookies_save_index_ = 0;
696 FetchResponseCookies(&response_cookies_);
698 if (!GetResponseHeaders()->GetDateValue(&response_date_))
699 response_date_ = base::Time();
701 // Now, loop over the response cookies, and attempt to persist each.
702 SaveNextCookie();
705 // If the save occurs synchronously, SaveNextCookie will loop and save the next
706 // cookie. If the save is deferred, the callback is responsible for continuing
707 // to iterate through the cookies.
708 // TODO(erikwright): Modify the CookieStore API to indicate via return value
709 // whether it completed synchronously or asynchronously.
710 // See http://crbug.com/131066.
711 void URLRequestHttpJob::SaveNextCookie() {
712 // No matter what, we want to report our status as IO pending since we will
713 // be notifying our consumer asynchronously via OnStartCompleted.
714 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
716 // Used to communicate with the callback. See the implementation of
717 // OnCookieSaved.
718 scoped_refptr<SharedBoolean> callback_pending = new SharedBoolean(false);
719 scoped_refptr<SharedBoolean> save_next_cookie_running =
720 new SharedBoolean(true);
722 if (!(request_info_.load_flags & LOAD_DO_NOT_SAVE_COOKIES) &&
723 GetCookieStore() && response_cookies_.size() > 0) {
724 CookieOptions options;
725 options.set_include_httponly();
726 options.set_server_time(response_date_);
728 net::CookieStore::SetCookiesCallback callback(
729 base::Bind(&URLRequestHttpJob::OnCookieSaved,
730 weak_factory_.GetWeakPtr(),
731 save_next_cookie_running,
732 callback_pending));
734 // Loop through the cookies as long as SetCookieWithOptionsAsync completes
735 // synchronously.
736 while (!callback_pending->data &&
737 response_cookies_save_index_ < response_cookies_.size()) {
738 if (CanSetCookie(
739 response_cookies_[response_cookies_save_index_], &options)) {
740 callback_pending->data = true;
741 GetCookieStore()->SetCookieWithOptionsAsync(
742 request_->url(), response_cookies_[response_cookies_save_index_],
743 options, callback);
745 ++response_cookies_save_index_;
749 save_next_cookie_running->data = false;
751 if (!callback_pending->data) {
752 response_cookies_.clear();
753 response_cookies_save_index_ = 0;
754 SetStatus(URLRequestStatus()); // Clear the IO_PENDING status
755 NotifyHeadersComplete();
756 return;
760 // |save_next_cookie_running| is true when the callback is bound and set to
761 // false when SaveNextCookie exits, allowing the callback to determine if the
762 // save occurred synchronously or asynchronously.
763 // |callback_pending| is false when the callback is invoked and will be set to
764 // true by the callback, allowing SaveNextCookie to detect whether the save
765 // occurred synchronously.
766 // See SaveNextCookie() for more information.
767 void URLRequestHttpJob::OnCookieSaved(
768 scoped_refptr<SharedBoolean> save_next_cookie_running,
769 scoped_refptr<SharedBoolean> callback_pending,
770 bool cookie_status) {
771 callback_pending->data = false;
773 // If we were called synchronously, return.
774 if (save_next_cookie_running->data) {
775 return;
778 // We were called asynchronously, so trigger the next save.
779 // We may have been canceled within OnSetCookie.
780 if (GetStatus().is_success()) {
781 SaveNextCookie();
782 } else {
783 NotifyCanceled();
787 void URLRequestHttpJob::FetchResponseCookies(
788 std::vector<std::string>* cookies) {
789 const std::string name = "Set-Cookie";
790 std::string value;
792 void* iter = NULL;
793 HttpResponseHeaders* headers = GetResponseHeaders();
794 while (headers->EnumerateHeader(&iter, name, &value)) {
795 if (!value.empty())
796 cookies->push_back(value);
800 // NOTE: |ProcessStrictTransportSecurityHeader| and
801 // |ProcessPublicKeyPinsHeader| have very similar structures, by design.
802 void URLRequestHttpJob::ProcessStrictTransportSecurityHeader() {
803 DCHECK(response_info_);
804 TransportSecurityState* security_state =
805 request_->context()->transport_security_state();
806 const SSLInfo& ssl_info = response_info_->ssl_info;
808 // Only accept HSTS headers on HTTPS connections that have no
809 // certificate errors.
810 if (!ssl_info.is_valid() || IsCertStatusError(ssl_info.cert_status) ||
811 !security_state)
812 return;
814 // http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec:
816 // If a UA receives more than one STS header field in a HTTP response
817 // message over secure transport, then the UA MUST process only the
818 // first such header field.
819 HttpResponseHeaders* headers = GetResponseHeaders();
820 std::string value;
821 if (headers->EnumerateHeader(NULL, "Strict-Transport-Security", &value))
822 security_state->AddHSTSHeader(request_info_.url.host(), value);
825 void URLRequestHttpJob::ProcessPublicKeyPinsHeader() {
826 DCHECK(response_info_);
827 TransportSecurityState* security_state =
828 request_->context()->transport_security_state();
829 const SSLInfo& ssl_info = response_info_->ssl_info;
831 // Only accept HPKP headers on HTTPS connections that have no
832 // certificate errors.
833 if (!ssl_info.is_valid() || IsCertStatusError(ssl_info.cert_status) ||
834 !security_state)
835 return;
837 // http://tools.ietf.org/html/draft-ietf-websec-key-pinning:
839 // If a UA receives more than one PKP header field in an HTTP
840 // response message over secure transport, then the UA MUST process
841 // only the first such header field.
842 HttpResponseHeaders* headers = GetResponseHeaders();
843 std::string value;
844 if (headers->EnumerateHeader(NULL, "Public-Key-Pins", &value))
845 security_state->AddHPKPHeader(request_info_.url.host(), value, ssl_info);
848 void URLRequestHttpJob::OnStartCompleted(int result) {
849 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424359 is fixed.
850 tracked_objects::ScopedTracker tracking_profile(
851 FROM_HERE_WITH_EXPLICIT_FUNCTION(
852 "424359 URLRequestHttpJob::OnStartCompleted"));
854 RecordTimer();
856 // If the request was destroyed, then there is no more work to do.
857 if (!request_)
858 return;
860 // If the job is done (due to cancellation), can just ignore this
861 // notification.
862 if (done_)
863 return;
865 receive_headers_end_ = base::TimeTicks::Now();
867 // Clear the IO_PENDING status
868 SetStatus(URLRequestStatus());
870 const URLRequestContext* context = request_->context();
872 if (result == ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN &&
873 transaction_->GetResponseInfo() != NULL) {
874 FraudulentCertificateReporter* reporter =
875 context->fraudulent_certificate_reporter();
876 if (reporter != NULL) {
877 const SSLInfo& ssl_info = transaction_->GetResponseInfo()->ssl_info;
878 const std::string& host = request_->url().host();
880 reporter->SendReport(host, ssl_info);
884 if (result == OK) {
885 if (transaction_ && transaction_->GetResponseInfo()) {
886 SetProxyServer(transaction_->GetResponseInfo()->proxy_server);
888 scoped_refptr<HttpResponseHeaders> headers = GetResponseHeaders();
889 if (network_delegate()) {
890 // Note that |this| may not be deleted until
891 // |on_headers_received_callback_| or
892 // |NetworkDelegate::URLRequestDestroyed()| has been called.
893 OnCallToDelegate();
894 allowed_unsafe_redirect_url_ = GURL();
895 int error = network_delegate()->NotifyHeadersReceived(
896 request_,
897 on_headers_received_callback_,
898 headers.get(),
899 &override_response_headers_,
900 &allowed_unsafe_redirect_url_);
901 if (error != net::OK) {
902 if (error == net::ERR_IO_PENDING) {
903 awaiting_callback_ = true;
904 } else {
905 std::string source("delegate");
906 request_->net_log().AddEvent(NetLog::TYPE_CANCELLED,
907 NetLog::StringCallback("source",
908 &source));
909 OnCallToDelegateComplete();
910 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, error));
912 return;
916 SaveCookiesAndNotifyHeadersComplete(net::OK);
917 } else if (IsCertificateError(result)) {
918 // We encountered an SSL certificate error.
919 if (result == ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY ||
920 result == ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN) {
921 // These are hard failures. They're handled separately and don't have
922 // the correct cert status, so set it here.
923 SSLInfo info(transaction_->GetResponseInfo()->ssl_info);
924 info.cert_status = MapNetErrorToCertStatus(result);
925 NotifySSLCertificateError(info, true);
926 } else {
927 // Maybe overridable, maybe not. Ask the delegate to decide.
928 const URLRequestContext* context = request_->context();
929 TransportSecurityState* state = context->transport_security_state();
930 const bool fatal =
931 state && state->ShouldSSLErrorsBeFatal(request_info_.url.host());
932 NotifySSLCertificateError(
933 transaction_->GetResponseInfo()->ssl_info, fatal);
935 } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
936 NotifyCertificateRequested(
937 transaction_->GetResponseInfo()->cert_request_info.get());
938 } else {
939 // Even on an error, there may be useful information in the response
940 // info (e.g. whether there's a cached copy).
941 if (transaction_.get())
942 response_info_ = transaction_->GetResponseInfo();
943 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, result));
947 // TODO(battre) Use URLRequestHttpJob::OnHeadersReceivedCallback again, once
948 // crbug.com/289715 has been resolved.
949 // static
950 void URLRequestHttpJob::OnHeadersReceivedCallbackForDebugging(
951 base::WeakPtr<net::URLRequestHttpJob> job,
952 int result) {
953 CHECK(job.get());
954 net::URLRequestHttpJob::TransactionState state = job->transaction_state_;
955 base::debug::Alias(&state);
956 CHECK(job->transaction_.get());
957 job->OnHeadersReceivedCallback(result);
960 void URLRequestHttpJob::OnHeadersReceivedCallback(int result) {
961 awaiting_callback_ = false;
963 // Check that there are no callbacks to already canceled requests.
964 DCHECK_NE(URLRequestStatus::CANCELED, GetStatus().status());
966 SaveCookiesAndNotifyHeadersComplete(result);
969 void URLRequestHttpJob::OnReadCompleted(int result) {
970 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424359 is fixed.
971 tracked_objects::ScopedTracker tracking_profile(
972 FROM_HERE_WITH_EXPLICIT_FUNCTION(
973 "424359 URLRequestHttpJob::OnReadCompleted"));
975 read_in_progress_ = false;
977 if (ShouldFixMismatchedContentLength(result))
978 result = OK;
980 if (result == OK) {
981 NotifyDone(URLRequestStatus());
982 } else if (result < 0) {
983 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, result));
984 } else {
985 // Clear the IO_PENDING status
986 SetStatus(URLRequestStatus());
989 NotifyReadComplete(result);
992 void URLRequestHttpJob::RestartTransactionWithAuth(
993 const AuthCredentials& credentials) {
994 auth_credentials_ = credentials;
996 // These will be reset in OnStartCompleted.
997 response_info_ = NULL;
998 receive_headers_end_ = base::TimeTicks();
999 response_cookies_.clear();
1001 ResetTimer();
1003 // Update the cookies, since the cookie store may have been updated from the
1004 // headers in the 401/407. Since cookies were already appended to
1005 // extra_headers, we need to strip them out before adding them again.
1006 request_info_.extra_headers.RemoveHeader(HttpRequestHeaders::kCookie);
1008 AddCookieHeaderAndStart();
1011 void URLRequestHttpJob::SetUpload(UploadDataStream* upload) {
1012 DCHECK(!transaction_.get()) << "cannot change once started";
1013 request_info_.upload_data_stream = upload;
1016 void URLRequestHttpJob::SetExtraRequestHeaders(
1017 const HttpRequestHeaders& headers) {
1018 DCHECK(!transaction_.get()) << "cannot change once started";
1019 request_info_.extra_headers.CopyFrom(headers);
1022 LoadState URLRequestHttpJob::GetLoadState() const {
1023 return transaction_.get() ?
1024 transaction_->GetLoadState() : LOAD_STATE_IDLE;
1027 UploadProgress URLRequestHttpJob::GetUploadProgress() const {
1028 return transaction_.get() ?
1029 transaction_->GetUploadProgress() : UploadProgress();
1032 bool URLRequestHttpJob::GetMimeType(std::string* mime_type) const {
1033 DCHECK(transaction_.get());
1035 if (!response_info_)
1036 return false;
1038 return GetResponseHeaders()->GetMimeType(mime_type);
1041 bool URLRequestHttpJob::GetCharset(std::string* charset) {
1042 DCHECK(transaction_.get());
1044 if (!response_info_)
1045 return false;
1047 return GetResponseHeaders()->GetCharset(charset);
1050 void URLRequestHttpJob::GetResponseInfo(HttpResponseInfo* info) {
1051 DCHECK(request_);
1053 if (response_info_) {
1054 DCHECK(transaction_.get());
1056 *info = *response_info_;
1057 if (override_response_headers_.get())
1058 info->headers = override_response_headers_;
1062 void URLRequestHttpJob::GetLoadTimingInfo(
1063 LoadTimingInfo* load_timing_info) const {
1064 // If haven't made it far enough to receive any headers, don't return
1065 // anything. This makes for more consistent behavior in the case of errors.
1066 if (!transaction_ || receive_headers_end_.is_null())
1067 return;
1068 if (transaction_->GetLoadTimingInfo(load_timing_info))
1069 load_timing_info->receive_headers_end = receive_headers_end_;
1072 bool URLRequestHttpJob::GetResponseCookies(std::vector<std::string>* cookies) {
1073 DCHECK(transaction_.get());
1075 if (!response_info_)
1076 return false;
1078 // TODO(darin): Why are we extracting response cookies again? Perhaps we
1079 // should just leverage response_cookies_.
1081 cookies->clear();
1082 FetchResponseCookies(cookies);
1083 return true;
1086 int URLRequestHttpJob::GetResponseCode() const {
1087 DCHECK(transaction_.get());
1089 if (!response_info_)
1090 return -1;
1092 return GetResponseHeaders()->response_code();
1095 Filter* URLRequestHttpJob::SetupFilter() const {
1096 DCHECK(transaction_.get());
1097 if (!response_info_)
1098 return NULL;
1100 std::vector<Filter::FilterType> encoding_types;
1101 std::string encoding_type;
1102 HttpResponseHeaders* headers = GetResponseHeaders();
1103 void* iter = NULL;
1104 while (headers->EnumerateHeader(&iter, "Content-Encoding", &encoding_type)) {
1105 encoding_types.push_back(Filter::ConvertEncodingToType(encoding_type));
1108 // Even if encoding types are empty, there is a chance that we need to add
1109 // some decoding, as some proxies strip encoding completely. In such cases,
1110 // we may need to add (for example) SDCH filtering (when the context suggests
1111 // it is appropriate).
1112 Filter::FixupEncodingTypes(*filter_context_, &encoding_types);
1114 return !encoding_types.empty()
1115 ? Filter::Factory(encoding_types, *filter_context_) : NULL;
1118 bool URLRequestHttpJob::CopyFragmentOnRedirect(const GURL& location) const {
1119 // Allow modification of reference fragments by default, unless
1120 // |allowed_unsafe_redirect_url_| is set and equal to the redirect URL.
1121 // When this is the case, we assume that the network delegate has set the
1122 // desired redirect URL (with or without fragment), so it must not be changed
1123 // any more.
1124 return !allowed_unsafe_redirect_url_.is_valid() ||
1125 allowed_unsafe_redirect_url_ != location;
1128 bool URLRequestHttpJob::IsSafeRedirect(const GURL& location) {
1129 // HTTP is always safe.
1130 // TODO(pauljensen): Remove once crbug.com/146591 is fixed.
1131 if (location.is_valid() &&
1132 (location.scheme() == "http" || location.scheme() == "https")) {
1133 return true;
1135 // Delegates may mark a URL as safe for redirection.
1136 if (allowed_unsafe_redirect_url_.is_valid() &&
1137 allowed_unsafe_redirect_url_ == location) {
1138 return true;
1140 // Query URLRequestJobFactory as to whether |location| would be safe to
1141 // redirect to.
1142 return request_->context()->job_factory() &&
1143 request_->context()->job_factory()->IsSafeRedirectTarget(location);
1146 bool URLRequestHttpJob::NeedsAuth() {
1147 int code = GetResponseCode();
1148 if (code == -1)
1149 return false;
1151 // Check if we need either Proxy or WWW Authentication. This could happen
1152 // because we either provided no auth info, or provided incorrect info.
1153 switch (code) {
1154 case 407:
1155 if (proxy_auth_state_ == AUTH_STATE_CANCELED)
1156 return false;
1157 proxy_auth_state_ = AUTH_STATE_NEED_AUTH;
1158 return true;
1159 case 401:
1160 if (server_auth_state_ == AUTH_STATE_CANCELED)
1161 return false;
1162 server_auth_state_ = AUTH_STATE_NEED_AUTH;
1163 return true;
1165 return false;
1168 void URLRequestHttpJob::GetAuthChallengeInfo(
1169 scoped_refptr<AuthChallengeInfo>* result) {
1170 DCHECK(transaction_.get());
1171 DCHECK(response_info_);
1173 // sanity checks:
1174 DCHECK(proxy_auth_state_ == AUTH_STATE_NEED_AUTH ||
1175 server_auth_state_ == AUTH_STATE_NEED_AUTH);
1176 DCHECK((GetResponseHeaders()->response_code() == HTTP_UNAUTHORIZED) ||
1177 (GetResponseHeaders()->response_code() ==
1178 HTTP_PROXY_AUTHENTICATION_REQUIRED));
1180 *result = response_info_->auth_challenge;
1183 void URLRequestHttpJob::SetAuth(const AuthCredentials& credentials) {
1184 DCHECK(transaction_.get());
1186 // Proxy gets set first, then WWW.
1187 if (proxy_auth_state_ == AUTH_STATE_NEED_AUTH) {
1188 proxy_auth_state_ = AUTH_STATE_HAVE_AUTH;
1189 } else {
1190 DCHECK_EQ(server_auth_state_, AUTH_STATE_NEED_AUTH);
1191 server_auth_state_ = AUTH_STATE_HAVE_AUTH;
1194 RestartTransactionWithAuth(credentials);
1197 void URLRequestHttpJob::CancelAuth() {
1198 // Proxy gets set first, then WWW.
1199 if (proxy_auth_state_ == AUTH_STATE_NEED_AUTH) {
1200 proxy_auth_state_ = AUTH_STATE_CANCELED;
1201 } else {
1202 DCHECK_EQ(server_auth_state_, AUTH_STATE_NEED_AUTH);
1203 server_auth_state_ = AUTH_STATE_CANCELED;
1206 // These will be reset in OnStartCompleted.
1207 response_info_ = NULL;
1208 receive_headers_end_ = base::TimeTicks::Now();
1209 response_cookies_.clear();
1211 ResetTimer();
1213 // OK, let the consumer read the error page...
1215 // Because we set the AUTH_STATE_CANCELED flag, NeedsAuth will return false,
1216 // which will cause the consumer to receive OnResponseStarted instead of
1217 // OnAuthRequired.
1219 // We have to do this via InvokeLater to avoid "recursing" the consumer.
1221 base::MessageLoop::current()->PostTask(
1222 FROM_HERE,
1223 base::Bind(&URLRequestHttpJob::OnStartCompleted,
1224 weak_factory_.GetWeakPtr(), OK));
1227 void URLRequestHttpJob::ContinueWithCertificate(
1228 X509Certificate* client_cert) {
1229 DCHECK(transaction_.get());
1231 DCHECK(!response_info_) << "should not have a response yet";
1232 receive_headers_end_ = base::TimeTicks();
1234 ResetTimer();
1236 // No matter what, we want to report our status as IO pending since we will
1237 // be notifying our consumer asynchronously via OnStartCompleted.
1238 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
1240 int rv = transaction_->RestartWithCertificate(client_cert, start_callback_);
1241 if (rv == ERR_IO_PENDING)
1242 return;
1244 // The transaction started synchronously, but we need to notify the
1245 // URLRequest delegate via the message loop.
1246 base::MessageLoop::current()->PostTask(
1247 FROM_HERE,
1248 base::Bind(&URLRequestHttpJob::OnStartCompleted,
1249 weak_factory_.GetWeakPtr(), rv));
1252 void URLRequestHttpJob::ContinueDespiteLastError() {
1253 // If the transaction was destroyed, then the job was cancelled.
1254 if (!transaction_.get())
1255 return;
1257 DCHECK(!response_info_) << "should not have a response yet";
1258 receive_headers_end_ = base::TimeTicks();
1260 ResetTimer();
1262 // No matter what, we want to report our status as IO pending since we will
1263 // be notifying our consumer asynchronously via OnStartCompleted.
1264 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
1266 int rv = transaction_->RestartIgnoringLastError(start_callback_);
1267 if (rv == ERR_IO_PENDING)
1268 return;
1270 // The transaction started synchronously, but we need to notify the
1271 // URLRequest delegate via the message loop.
1272 base::MessageLoop::current()->PostTask(
1273 FROM_HERE,
1274 base::Bind(&URLRequestHttpJob::OnStartCompleted,
1275 weak_factory_.GetWeakPtr(), rv));
1278 void URLRequestHttpJob::ResumeNetworkStart() {
1279 DCHECK(transaction_.get());
1280 transaction_->ResumeNetworkStart();
1283 bool URLRequestHttpJob::ShouldFixMismatchedContentLength(int rv) const {
1284 // Some servers send the body compressed, but specify the content length as
1285 // the uncompressed size. Although this violates the HTTP spec we want to
1286 // support it (as IE and FireFox do), but *only* for an exact match.
1287 // See http://crbug.com/79694.
1288 if (rv == net::ERR_CONTENT_LENGTH_MISMATCH ||
1289 rv == net::ERR_INCOMPLETE_CHUNKED_ENCODING) {
1290 if (request_ && request_->response_headers()) {
1291 int64 expected_length = request_->response_headers()->GetContentLength();
1292 VLOG(1) << __FUNCTION__ << "() "
1293 << "\"" << request_->url().spec() << "\""
1294 << " content-length = " << expected_length
1295 << " pre total = " << prefilter_bytes_read()
1296 << " post total = " << postfilter_bytes_read();
1297 if (postfilter_bytes_read() == expected_length) {
1298 // Clear the error.
1299 return true;
1303 return false;
1306 bool URLRequestHttpJob::ReadRawData(IOBuffer* buf, int buf_size,
1307 int* bytes_read) {
1308 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
1309 tracked_objects::ScopedTracker tracking_profile1(
1310 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1311 "423948 URLRequestHttpJob::ReadRawData1"));
1313 DCHECK_NE(buf_size, 0);
1314 DCHECK(bytes_read);
1315 DCHECK(!read_in_progress_);
1317 int rv = transaction_->Read(
1318 buf, buf_size,
1319 base::Bind(&URLRequestHttpJob::OnReadCompleted, base::Unretained(this)));
1321 if (ShouldFixMismatchedContentLength(rv))
1322 rv = 0;
1324 if (rv >= 0) {
1325 *bytes_read = rv;
1326 if (!rv) {
1327 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is
1328 // fixed.
1329 tracked_objects::ScopedTracker tracking_profile2(
1330 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1331 "423948 URLRequestHttpJob::ReadRawData2"));
1333 DoneWithRequest(FINISHED);
1335 return true;
1338 if (rv == ERR_IO_PENDING) {
1339 read_in_progress_ = true;
1340 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
1341 } else {
1342 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, rv));
1345 return false;
1348 void URLRequestHttpJob::StopCaching() {
1349 if (transaction_.get())
1350 transaction_->StopCaching();
1353 bool URLRequestHttpJob::GetFullRequestHeaders(
1354 HttpRequestHeaders* headers) const {
1355 if (!transaction_)
1356 return false;
1358 return transaction_->GetFullRequestHeaders(headers);
1361 int64 URLRequestHttpJob::GetTotalReceivedBytes() const {
1362 if (!transaction_)
1363 return 0;
1365 return transaction_->GetTotalReceivedBytes();
1368 void URLRequestHttpJob::DoneReading() {
1369 if (transaction_) {
1370 transaction_->DoneReading();
1372 DoneWithRequest(FINISHED);
1375 void URLRequestHttpJob::DoneReadingRedirectResponse() {
1376 if (transaction_) {
1377 if (transaction_->GetResponseInfo()->headers->IsRedirect(NULL)) {
1378 // If the original headers indicate a redirect, go ahead and cache the
1379 // response, even if the |override_response_headers_| are a redirect to
1380 // another location.
1381 transaction_->DoneReading();
1382 } else {
1383 // Otherwise, |override_response_headers_| must be non-NULL and contain
1384 // bogus headers indicating a redirect.
1385 DCHECK(override_response_headers_.get());
1386 DCHECK(override_response_headers_->IsRedirect(NULL));
1387 transaction_->StopCaching();
1390 DoneWithRequest(FINISHED);
1393 HostPortPair URLRequestHttpJob::GetSocketAddress() const {
1394 return response_info_ ? response_info_->socket_address : HostPortPair();
1397 void URLRequestHttpJob::RecordTimer() {
1398 if (request_creation_time_.is_null()) {
1399 NOTREACHED()
1400 << "The same transaction shouldn't start twice without new timing.";
1401 return;
1404 base::TimeDelta to_start = base::Time::Now() - request_creation_time_;
1405 request_creation_time_ = base::Time();
1407 UMA_HISTOGRAM_MEDIUM_TIMES("Net.HttpTimeToFirstByte", to_start);
1410 void URLRequestHttpJob::ResetTimer() {
1411 if (!request_creation_time_.is_null()) {
1412 NOTREACHED()
1413 << "The timer was reset before it was recorded.";
1414 return;
1416 request_creation_time_ = base::Time::Now();
1419 void URLRequestHttpJob::UpdatePacketReadTimes() {
1420 if (!packet_timing_enabled_)
1421 return;
1423 if (filter_input_byte_count() <= bytes_observed_in_packets_) {
1424 DCHECK_EQ(filter_input_byte_count(), bytes_observed_in_packets_);
1425 return; // No new bytes have arrived.
1428 base::Time now(base::Time::Now());
1429 if (!bytes_observed_in_packets_)
1430 request_time_snapshot_ = now;
1431 final_packet_time_ = now;
1433 bytes_observed_in_packets_ = filter_input_byte_count();
1436 void URLRequestHttpJob::RecordPacketStats(
1437 FilterContext::StatisticSelector statistic) const {
1438 if (!packet_timing_enabled_ || (final_packet_time_ == base::Time()))
1439 return;
1441 base::TimeDelta duration = final_packet_time_ - request_time_snapshot_;
1442 switch (statistic) {
1443 case FilterContext::SDCH_DECODE: {
1444 UMA_HISTOGRAM_CUSTOM_COUNTS("Sdch3.Network_Decode_Bytes_Processed_b",
1445 static_cast<int>(bytes_observed_in_packets_), 500, 100000, 100);
1446 return;
1448 case FilterContext::SDCH_PASSTHROUGH: {
1449 // Despite advertising a dictionary, we handled non-sdch compressed
1450 // content.
1451 return;
1454 case FilterContext::SDCH_EXPERIMENT_DECODE: {
1455 UMA_HISTOGRAM_CUSTOM_TIMES("Sdch3.Experiment3_Decode",
1456 duration,
1457 base::TimeDelta::FromMilliseconds(20),
1458 base::TimeDelta::FromMinutes(10), 100);
1459 return;
1461 case FilterContext::SDCH_EXPERIMENT_HOLDBACK: {
1462 UMA_HISTOGRAM_CUSTOM_TIMES("Sdch3.Experiment3_Holdback",
1463 duration,
1464 base::TimeDelta::FromMilliseconds(20),
1465 base::TimeDelta::FromMinutes(10), 100);
1466 return;
1468 default:
1469 NOTREACHED();
1470 return;
1474 // The common type of histogram we use for all compression-tracking histograms.
1475 #define COMPRESSION_HISTOGRAM(name, sample) \
1476 do { \
1477 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.Compress." name, sample, \
1478 500, 1000000, 100); \
1479 } while (0)
1481 void URLRequestHttpJob::RecordCompressionHistograms() {
1482 DCHECK(request_);
1483 if (!request_)
1484 return;
1486 if (is_cached_content_ || // Don't record cached content
1487 !GetStatus().is_success() || // Don't record failed content
1488 !IsCompressibleContent() || // Only record compressible content
1489 !prefilter_bytes_read()) // Zero-byte responses aren't useful.
1490 return;
1492 // Miniature requests aren't really compressible. Don't count them.
1493 const int kMinSize = 16;
1494 if (prefilter_bytes_read() < kMinSize)
1495 return;
1497 // Only record for http or https urls.
1498 bool is_http = request_->url().SchemeIs("http");
1499 bool is_https = request_->url().SchemeIs("https");
1500 if (!is_http && !is_https)
1501 return;
1503 int compressed_B = prefilter_bytes_read();
1504 int decompressed_B = postfilter_bytes_read();
1505 bool was_filtered = HasFilter();
1507 // We want to record how often downloaded resources are compressed.
1508 // But, we recognize that different protocols may have different
1509 // properties. So, for each request, we'll put it into one of 3
1510 // groups:
1511 // a) SSL resources
1512 // Proxies cannot tamper with compression headers with SSL.
1513 // b) Non-SSL, loaded-via-proxy resources
1514 // In this case, we know a proxy might have interfered.
1515 // c) Non-SSL, loaded-without-proxy resources
1516 // In this case, we know there was no explicit proxy. However,
1517 // it is possible that a transparent proxy was still interfering.
1519 // For each group, we record the same 3 histograms.
1521 if (is_https) {
1522 if (was_filtered) {
1523 COMPRESSION_HISTOGRAM("SSL.BytesBeforeCompression", compressed_B);
1524 COMPRESSION_HISTOGRAM("SSL.BytesAfterCompression", decompressed_B);
1525 } else {
1526 COMPRESSION_HISTOGRAM("SSL.ShouldHaveBeenCompressed", decompressed_B);
1528 return;
1531 if (request_->was_fetched_via_proxy()) {
1532 if (was_filtered) {
1533 COMPRESSION_HISTOGRAM("Proxy.BytesBeforeCompression", compressed_B);
1534 COMPRESSION_HISTOGRAM("Proxy.BytesAfterCompression", decompressed_B);
1535 } else {
1536 COMPRESSION_HISTOGRAM("Proxy.ShouldHaveBeenCompressed", decompressed_B);
1538 return;
1541 if (was_filtered) {
1542 COMPRESSION_HISTOGRAM("NoProxy.BytesBeforeCompression", compressed_B);
1543 COMPRESSION_HISTOGRAM("NoProxy.BytesAfterCompression", decompressed_B);
1544 } else {
1545 COMPRESSION_HISTOGRAM("NoProxy.ShouldHaveBeenCompressed", decompressed_B);
1549 bool URLRequestHttpJob::IsCompressibleContent() const {
1550 std::string mime_type;
1551 return GetMimeType(&mime_type) &&
1552 (IsSupportedJavascriptMimeType(mime_type.c_str()) ||
1553 IsSupportedNonImageMimeType(mime_type.c_str()));
1556 void URLRequestHttpJob::RecordPerfHistograms(CompletionCause reason) {
1557 if (start_time_.is_null())
1558 return;
1560 base::TimeDelta total_time = base::TimeTicks::Now() - start_time_;
1561 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTime", total_time);
1563 if (reason == FINISHED) {
1564 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeSuccess", total_time);
1565 } else {
1566 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeCancel", total_time);
1569 if (response_info_) {
1570 if (response_info_->was_cached) {
1571 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeCached", total_time);
1572 } else {
1573 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeNotCached", total_time);
1577 if (request_info_.load_flags & LOAD_PREFETCH && !request_->was_cached())
1578 UMA_HISTOGRAM_COUNTS("Net.Prefetch.PrefilterBytesReadFromNetwork",
1579 prefilter_bytes_read());
1581 start_time_ = base::TimeTicks();
1584 void URLRequestHttpJob::DoneWithRequest(CompletionCause reason) {
1585 if (done_)
1586 return;
1587 done_ = true;
1588 RecordPerfHistograms(reason);
1589 if (reason == FINISHED) {
1590 request_->set_received_response_content_length(prefilter_bytes_read());
1591 RecordCompressionHistograms();
1595 HttpResponseHeaders* URLRequestHttpJob::GetResponseHeaders() const {
1596 DCHECK(transaction_.get());
1597 DCHECK(transaction_->GetResponseInfo());
1598 return override_response_headers_.get() ?
1599 override_response_headers_.get() :
1600 transaction_->GetResponseInfo()->headers.get();
1603 void URLRequestHttpJob::NotifyURLRequestDestroyed() {
1604 awaiting_callback_ = false;
1607 } // namespace net