Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / net / url_request / url_request_job.cc
blobdd9bd5e15d656ebe54c8ed63815b4dbbca718303
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_job.h"
7 #include "base/bind.h"
8 #include "base/compiler_specific.h"
9 #include "base/location.h"
10 #include "base/metrics/histogram_macros.h"
11 #include "base/power_monitor/power_monitor.h"
12 #include "base/profiler/scoped_tracker.h"
13 #include "base/single_thread_task_runner.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_util.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "base/values.h"
18 #include "net/base/auth.h"
19 #include "net/base/host_port_pair.h"
20 #include "net/base/io_buffer.h"
21 #include "net/base/load_flags.h"
22 #include "net/base/load_states.h"
23 #include "net/base/net_errors.h"
24 #include "net/base/network_delegate.h"
25 #include "net/base/network_quality_estimator.h"
26 #include "net/filter/filter.h"
27 #include "net/http/http_response_headers.h"
28 #include "net/url_request/url_request_context.h"
30 namespace net {
32 namespace {
34 // Callback for TYPE_URL_REQUEST_FILTERS_SET net-internals event.
35 scoped_ptr<base::Value> FiltersSetCallback(
36 Filter* filter,
37 NetLogCaptureMode /* capture_mode */) {
38 scoped_ptr<base::DictionaryValue> event_params(new base::DictionaryValue());
39 event_params->SetString("filters", filter->OrderedFilterList());
40 return event_params.Pass();
43 std::string ComputeMethodForRedirect(const std::string& method,
44 int http_status_code) {
45 // For 303 redirects, all request methods except HEAD are converted to GET,
46 // as per the latest httpbis draft. The draft also allows POST requests to
47 // be converted to GETs when following 301/302 redirects, for historical
48 // reasons. Most major browsers do this and so shall we. Both RFC 2616 and
49 // the httpbis draft say to prompt the user to confirm the generation of new
50 // requests, other than GET and HEAD requests, but IE omits these prompts and
51 // so shall we.
52 // See:
53 // https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-17#section-7.3
54 if ((http_status_code == 303 && method != "HEAD") ||
55 ((http_status_code == 301 || http_status_code == 302) &&
56 method == "POST")) {
57 return "GET";
59 return method;
62 } // namespace
64 URLRequestJob::URLRequestJob(URLRequest* request,
65 NetworkDelegate* network_delegate)
66 : request_(request),
67 done_(false),
68 prefilter_bytes_read_(0),
69 postfilter_bytes_read_(0),
70 filter_needs_more_output_space_(false),
71 filtered_read_buffer_len_(0),
72 has_handled_response_(false),
73 expected_content_size_(-1),
74 network_delegate_(network_delegate),
75 last_notified_total_received_bytes_(0),
76 weak_factory_(this) {
77 base::PowerMonitor* power_monitor = base::PowerMonitor::Get();
78 if (power_monitor)
79 power_monitor->AddObserver(this);
82 void URLRequestJob::SetUpload(UploadDataStream* upload) {
85 void URLRequestJob::SetExtraRequestHeaders(const HttpRequestHeaders& headers) {
88 void URLRequestJob::SetPriority(RequestPriority priority) {
91 void URLRequestJob::Kill() {
92 weak_factory_.InvalidateWeakPtrs();
93 // Make sure the request is notified that we are done. We assume that the
94 // request took care of setting its error status before calling Kill.
95 if (request_)
96 NotifyCanceled();
99 void URLRequestJob::DetachRequest() {
100 request_ = NULL;
103 // This function calls ReadData to get stream data. If a filter exists, passes
104 // the data to the attached filter. Then returns the output from filter back to
105 // the caller.
106 bool URLRequestJob::Read(IOBuffer* buf, int buf_size, int *bytes_read) {
107 bool rv = false;
109 DCHECK_LT(buf_size, 1000000); // Sanity check.
110 DCHECK(buf);
111 DCHECK(bytes_read);
112 DCHECK(filtered_read_buffer_.get() == NULL);
113 DCHECK_EQ(0, filtered_read_buffer_len_);
115 *bytes_read = 0;
117 // Skip Filter if not present.
118 if (!filter_.get()) {
119 rv = ReadRawDataHelper(buf, buf_size, bytes_read);
120 } else {
121 // Save the caller's buffers while we do IO
122 // in the filter's buffers.
123 filtered_read_buffer_ = buf;
124 filtered_read_buffer_len_ = buf_size;
126 if (ReadFilteredData(bytes_read)) {
127 rv = true; // We have data to return.
129 // It is fine to call DoneReading even if ReadFilteredData receives 0
130 // bytes from the net, but we avoid making that call if we know for
131 // sure that's the case (ReadRawDataHelper path).
132 if (*bytes_read == 0)
133 DoneReading();
134 } else {
135 rv = false; // Error, or a new IO is pending.
139 if (rv && *bytes_read == 0)
140 NotifyDone(URLRequestStatus());
141 return rv;
144 void URLRequestJob::StopCaching() {
145 // Nothing to do here.
148 bool URLRequestJob::GetFullRequestHeaders(HttpRequestHeaders* headers) const {
149 // Most job types don't send request headers.
150 return false;
153 int64 URLRequestJob::GetTotalReceivedBytes() const {
154 return 0;
157 int64_t URLRequestJob::GetTotalSentBytes() const {
158 return 0;
161 LoadState URLRequestJob::GetLoadState() const {
162 return LOAD_STATE_IDLE;
165 UploadProgress URLRequestJob::GetUploadProgress() const {
166 return UploadProgress();
169 bool URLRequestJob::GetCharset(std::string* charset) {
170 return false;
173 void URLRequestJob::GetResponseInfo(HttpResponseInfo* info) {
176 void URLRequestJob::GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const {
177 // Only certain request types return more than just request start times.
180 bool URLRequestJob::GetResponseCookies(std::vector<std::string>* cookies) {
181 return false;
184 Filter* URLRequestJob::SetupFilter() const {
185 return NULL;
188 bool URLRequestJob::IsRedirectResponse(GURL* location,
189 int* http_status_code) {
190 // For non-HTTP jobs, headers will be null.
191 HttpResponseHeaders* headers = request_->response_headers();
192 if (!headers)
193 return false;
195 std::string value;
196 if (!headers->IsRedirect(&value))
197 return false;
199 *location = request_->url().Resolve(value);
200 *http_status_code = headers->response_code();
201 return true;
204 bool URLRequestJob::CopyFragmentOnRedirect(const GURL& location) const {
205 return true;
208 bool URLRequestJob::IsSafeRedirect(const GURL& location) {
209 return true;
212 bool URLRequestJob::NeedsAuth() {
213 return false;
216 void URLRequestJob::GetAuthChallengeInfo(
217 scoped_refptr<AuthChallengeInfo>* auth_info) {
218 // This will only be called if NeedsAuth() returns true, in which
219 // case the derived class should implement this!
220 NOTREACHED();
223 void URLRequestJob::SetAuth(const AuthCredentials& credentials) {
224 // This will only be called if NeedsAuth() returns true, in which
225 // case the derived class should implement this!
226 NOTREACHED();
229 void URLRequestJob::CancelAuth() {
230 // This will only be called if NeedsAuth() returns true, in which
231 // case the derived class should implement this!
232 NOTREACHED();
235 void URLRequestJob::ContinueWithCertificate(
236 X509Certificate* client_cert) {
237 // The derived class should implement this!
238 NOTREACHED();
241 void URLRequestJob::ContinueDespiteLastError() {
242 // Implementations should know how to recover from errors they generate.
243 // If this code was reached, we are trying to recover from an error that
244 // we don't know how to recover from.
245 NOTREACHED();
248 void URLRequestJob::FollowDeferredRedirect() {
249 DCHECK_NE(-1, deferred_redirect_info_.status_code);
251 // NOTE: deferred_redirect_info_ may be invalid, and attempting to follow it
252 // will fail inside FollowRedirect. The DCHECK above asserts that we called
253 // OnReceivedRedirect.
255 // It is also possible that FollowRedirect will drop the last reference to
256 // this job, so we need to reset our members before calling it.
258 RedirectInfo redirect_info = deferred_redirect_info_;
259 deferred_redirect_info_ = RedirectInfo();
260 FollowRedirect(redirect_info);
263 void URLRequestJob::ResumeNetworkStart() {
264 // This should only be called for HTTP Jobs, and implemented in the derived
265 // class.
266 NOTREACHED();
269 bool URLRequestJob::GetMimeType(std::string* mime_type) const {
270 return false;
273 int URLRequestJob::GetResponseCode() const {
274 return -1;
277 HostPortPair URLRequestJob::GetSocketAddress() const {
278 return HostPortPair();
281 void URLRequestJob::OnSuspend() {
282 Kill();
285 void URLRequestJob::NotifyURLRequestDestroyed() {
288 void URLRequestJob::GetConnectionAttempts(ConnectionAttempts* out) const {
289 out->clear();
292 // static
293 GURL URLRequestJob::ComputeReferrerForRedirect(
294 URLRequest::ReferrerPolicy policy,
295 const std::string& referrer,
296 const GURL& redirect_destination) {
297 GURL original_referrer(referrer);
298 bool secure_referrer_but_insecure_destination =
299 original_referrer.SchemeIsCryptographic() &&
300 !redirect_destination.SchemeIsCryptographic();
301 bool same_origin =
302 original_referrer.GetOrigin() == redirect_destination.GetOrigin();
303 switch (policy) {
304 case URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE:
305 return secure_referrer_but_insecure_destination ? GURL()
306 : original_referrer;
308 case URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN:
309 if (same_origin) {
310 return original_referrer;
311 } else if (secure_referrer_but_insecure_destination) {
312 return GURL();
313 } else {
314 return original_referrer.GetOrigin();
317 case URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN:
318 return same_origin ? original_referrer : original_referrer.GetOrigin();
320 case URLRequest::NEVER_CLEAR_REFERRER:
321 return original_referrer;
324 NOTREACHED();
325 return GURL();
328 URLRequestJob::~URLRequestJob() {
329 base::PowerMonitor* power_monitor = base::PowerMonitor::Get();
330 if (power_monitor)
331 power_monitor->RemoveObserver(this);
334 void URLRequestJob::NotifyCertificateRequested(
335 SSLCertRequestInfo* cert_request_info) {
336 if (!request_)
337 return; // The request was destroyed, so there is no more work to do.
339 request_->NotifyCertificateRequested(cert_request_info);
342 void URLRequestJob::NotifySSLCertificateError(const SSLInfo& ssl_info,
343 bool fatal) {
344 if (!request_)
345 return; // The request was destroyed, so there is no more work to do.
347 request_->NotifySSLCertificateError(ssl_info, fatal);
350 bool URLRequestJob::CanGetCookies(const CookieList& cookie_list) const {
351 if (!request_)
352 return false; // The request was destroyed, so there is no more work to do.
354 return request_->CanGetCookies(cookie_list);
357 bool URLRequestJob::CanSetCookie(const std::string& cookie_line,
358 CookieOptions* options) const {
359 if (!request_)
360 return false; // The request was destroyed, so there is no more work to do.
362 return request_->CanSetCookie(cookie_line, options);
365 bool URLRequestJob::CanEnablePrivacyMode() const {
366 if (!request_)
367 return false; // The request was destroyed, so there is no more work to do.
369 return request_->CanEnablePrivacyMode();
372 void URLRequestJob::NotifyBeforeNetworkStart(bool* defer) {
373 if (!request_)
374 return;
376 request_->NotifyBeforeNetworkStart(defer);
379 void URLRequestJob::NotifyHeadersComplete() {
380 if (!request_ || !request_->has_delegate())
381 return; // The request was destroyed, so there is no more work to do.
383 if (has_handled_response_)
384 return;
386 // This should not be called on error, and the job type should have cleared
387 // IO_PENDING state before calling this method.
388 DCHECK(request_->status().is_success());
390 // Initialize to the current time, and let the subclass optionally override
391 // the time stamps if it has that information. The default request_time is
392 // set by URLRequest before it calls our Start method.
393 request_->response_info_.response_time = base::Time::Now();
394 GetResponseInfo(&request_->response_info_);
396 // When notifying the delegate, the delegate can release the request
397 // (and thus release 'this'). After calling to the delgate, we must
398 // check the request pointer to see if it still exists, and return
399 // immediately if it has been destroyed. self_preservation ensures our
400 // survival until we can get out of this method.
401 scoped_refptr<URLRequestJob> self_preservation(this);
403 MaybeNotifyNetworkBytes();
405 if (request_)
406 request_->OnHeadersComplete();
408 GURL new_location;
409 int http_status_code;
410 if (IsRedirectResponse(&new_location, &http_status_code)) {
411 // Redirect response bodies are not read. Notify the transaction
412 // so it does not treat being stopped as an error.
413 DoneReadingRedirectResponse();
415 RedirectInfo redirect_info =
416 ComputeRedirectInfo(new_location, http_status_code);
417 bool defer_redirect = false;
418 request_->NotifyReceivedRedirect(redirect_info, &defer_redirect);
420 // Ensure that the request wasn't detached or destroyed in
421 // NotifyReceivedRedirect
422 if (!request_ || !request_->has_delegate())
423 return;
425 // If we were not cancelled, then maybe follow the redirect.
426 if (request_->status().is_success()) {
427 if (defer_redirect) {
428 deferred_redirect_info_ = redirect_info;
429 } else {
430 FollowRedirect(redirect_info);
432 return;
434 } else if (NeedsAuth()) {
435 scoped_refptr<AuthChallengeInfo> auth_info;
436 GetAuthChallengeInfo(&auth_info);
438 // Need to check for a NULL auth_info because the server may have failed
439 // to send a challenge with the 401 response.
440 if (auth_info.get()) {
441 request_->NotifyAuthRequired(auth_info.get());
442 // Wait for SetAuth or CancelAuth to be called.
443 return;
447 has_handled_response_ = true;
448 if (request_->status().is_success())
449 filter_.reset(SetupFilter());
451 if (!filter_.get()) {
452 std::string content_length;
453 request_->GetResponseHeaderByName("content-length", &content_length);
454 if (!content_length.empty())
455 base::StringToInt64(content_length, &expected_content_size_);
456 } else {
457 request_->net_log().AddEvent(
458 NetLog::TYPE_URL_REQUEST_FILTERS_SET,
459 base::Bind(&FiltersSetCallback, base::Unretained(filter_.get())));
462 request_->NotifyResponseStarted();
465 void URLRequestJob::NotifyReadComplete(int bytes_read) {
466 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/475755 is fixed.
467 tracked_objects::ScopedTracker tracking_profile(
468 FROM_HERE_WITH_EXPLICIT_FUNCTION(
469 "475755 URLRequestJob::NotifyReadComplete"));
471 if (!request_ || !request_->has_delegate())
472 return; // The request was destroyed, so there is no more work to do.
474 // TODO(darin): Bug 1004233. Re-enable this test once all of the chrome
475 // unit_tests have been fixed to not trip this.
476 #if 0
477 DCHECK(!request_->status().is_io_pending());
478 #endif
479 // The headers should be complete before reads complete
480 DCHECK(has_handled_response_);
482 OnRawReadComplete(bytes_read);
484 // Don't notify if we had an error.
485 if (!request_->status().is_success())
486 return;
488 // When notifying the delegate, the delegate can release the request
489 // (and thus release 'this'). After calling to the delegate, we must
490 // check the request pointer to see if it still exists, and return
491 // immediately if it has been destroyed. self_preservation ensures our
492 // survival until we can get out of this method.
493 scoped_refptr<URLRequestJob> self_preservation(this);
495 if (filter_.get()) {
496 // Tell the filter that it has more data
497 FilteredDataRead(bytes_read);
499 // Filter the data.
500 int filter_bytes_read = 0;
501 if (ReadFilteredData(&filter_bytes_read)) {
502 if (!filter_bytes_read)
503 DoneReading();
504 request_->NotifyReadCompleted(filter_bytes_read);
506 } else {
507 request_->NotifyReadCompleted(bytes_read);
509 DVLOG(1) << __FUNCTION__ << "() "
510 << "\"" << (request_ ? request_->url().spec() : "???") << "\""
511 << " pre bytes read = " << bytes_read
512 << " pre total = " << prefilter_bytes_read_
513 << " post total = " << postfilter_bytes_read_;
516 void URLRequestJob::NotifyStartError(const URLRequestStatus &status) {
517 DCHECK(!has_handled_response_);
518 has_handled_response_ = true;
519 if (request_) {
520 // There may be relevant information in the response info even in the
521 // error case.
522 GetResponseInfo(&request_->response_info_);
524 request_->set_status(status);
525 request_->NotifyResponseStarted();
526 // We may have been deleted.
530 void URLRequestJob::NotifyDone(const URLRequestStatus &status) {
531 DCHECK(!done_) << "Job sending done notification twice";
532 if (done_)
533 return;
534 done_ = true;
536 // Unless there was an error, we should have at least tried to handle
537 // the response before getting here.
538 DCHECK(has_handled_response_ || !status.is_success());
540 // As with NotifyReadComplete, we need to take care to notice if we were
541 // destroyed during a delegate callback.
542 if (request_) {
543 request_->set_is_pending(false);
544 // With async IO, it's quite possible to have a few outstanding
545 // requests. We could receive a request to Cancel, followed shortly
546 // by a successful IO. For tracking the status(), once there is
547 // an error, we do not change the status back to success. To
548 // enforce this, only set the status if the job is so far
549 // successful.
550 if (request_->status().is_success()) {
551 if (status.status() == URLRequestStatus::FAILED) {
552 request_->net_log().AddEventWithNetErrorCode(NetLog::TYPE_FAILED,
553 status.error());
555 request_->set_status(status);
558 // If the request succeeded (And wasn't cancelled) and the response code was
559 // 4xx or 5xx, record whether or not the main frame was blank. This is
560 // intended to be a short-lived histogram, used to figure out how important
561 // fixing http://crbug.com/331745 is.
562 if (request_->status().is_success()) {
563 int response_code = GetResponseCode();
564 if (400 <= response_code && response_code <= 599) {
565 bool page_has_content = (postfilter_bytes_read_ != 0);
566 if (request_->load_flags() & net::LOAD_MAIN_FRAME) {
567 UMA_HISTOGRAM_BOOLEAN("Net.ErrorResponseHasContentMainFrame",
568 page_has_content);
569 } else {
570 UMA_HISTOGRAM_BOOLEAN("Net.ErrorResponseHasContentNonMainFrame",
571 page_has_content);
577 MaybeNotifyNetworkBytes();
579 // Complete this notification later. This prevents us from re-entering the
580 // delegate if we're done because of a synchronous call.
581 base::ThreadTaskRunnerHandle::Get()->PostTask(
582 FROM_HERE, base::Bind(&URLRequestJob::CompleteNotifyDone,
583 weak_factory_.GetWeakPtr()));
586 void URLRequestJob::CompleteNotifyDone() {
587 // Check if we should notify the delegate that we're done because of an error.
588 if (request_ &&
589 !request_->status().is_success() &&
590 request_->has_delegate()) {
591 // We report the error differently depending on whether we've called
592 // OnResponseStarted yet.
593 if (has_handled_response_) {
594 // We signal the error by calling OnReadComplete with a bytes_read of -1.
595 request_->NotifyReadCompleted(-1);
596 } else {
597 has_handled_response_ = true;
598 request_->NotifyResponseStarted();
603 void URLRequestJob::NotifyCanceled() {
604 if (!done_) {
605 NotifyDone(URLRequestStatus(URLRequestStatus::CANCELED, ERR_ABORTED));
609 void URLRequestJob::NotifyRestartRequired() {
610 DCHECK(!has_handled_response_);
611 if (GetStatus().status() != URLRequestStatus::CANCELED)
612 request_->Restart();
615 void URLRequestJob::OnCallToDelegate() {
616 request_->OnCallToDelegate();
619 void URLRequestJob::OnCallToDelegateComplete() {
620 request_->OnCallToDelegateComplete();
623 bool URLRequestJob::ReadRawData(IOBuffer* buf, int buf_size,
624 int *bytes_read) {
625 DCHECK(bytes_read);
626 *bytes_read = 0;
627 return true;
630 void URLRequestJob::DoneReading() {
631 // Do nothing.
634 void URLRequestJob::DoneReadingRedirectResponse() {
637 void URLRequestJob::FilteredDataRead(int bytes_read) {
638 DCHECK(filter_);
639 filter_->FlushStreamBuffer(bytes_read);
642 bool URLRequestJob::ReadFilteredData(int* bytes_read) {
643 DCHECK(filter_);
644 DCHECK(filtered_read_buffer_.get());
645 DCHECK_GT(filtered_read_buffer_len_, 0);
646 DCHECK_LT(filtered_read_buffer_len_, 1000000); // Sanity check.
647 DCHECK(!raw_read_buffer_.get());
649 *bytes_read = 0;
650 bool rv = false;
652 for (;;) {
653 if (is_done())
654 return true;
656 if (!filter_needs_more_output_space_ && !filter_->stream_data_len()) {
657 // We don't have any raw data to work with, so read from the transaction.
658 int filtered_data_read;
659 if (ReadRawDataForFilter(&filtered_data_read)) {
660 if (filtered_data_read > 0) {
661 // Give data to filter.
662 filter_->FlushStreamBuffer(filtered_data_read);
663 } else {
664 return true; // EOF.
666 } else {
667 return false; // IO Pending (or error).
671 if ((filter_->stream_data_len() || filter_needs_more_output_space_) &&
672 !is_done()) {
673 // Get filtered data.
674 int filtered_data_len = filtered_read_buffer_len_;
675 int output_buffer_size = filtered_data_len;
676 Filter::FilterStatus status =
677 filter_->ReadData(filtered_read_buffer_->data(), &filtered_data_len);
679 if (filter_needs_more_output_space_ && !filtered_data_len) {
680 // filter_needs_more_output_space_ was mistaken... there are no more
681 // bytes and we should have at least tried to fill up the filter's input
682 // buffer. Correct the state, and try again.
683 filter_needs_more_output_space_ = false;
684 continue;
686 filter_needs_more_output_space_ =
687 (filtered_data_len == output_buffer_size);
689 switch (status) {
690 case Filter::FILTER_DONE: {
691 filter_needs_more_output_space_ = false;
692 *bytes_read = filtered_data_len;
693 postfilter_bytes_read_ += filtered_data_len;
694 rv = true;
695 break;
697 case Filter::FILTER_NEED_MORE_DATA: {
698 // We have finished filtering all data currently in the buffer.
699 // There might be some space left in the output buffer. One can
700 // consider reading more data from the stream to feed the filter
701 // and filling up the output buffer. This leads to more complicated
702 // buffer management and data notification mechanisms.
703 // We can revisit this issue if there is a real perf need.
704 if (filtered_data_len > 0) {
705 *bytes_read = filtered_data_len;
706 postfilter_bytes_read_ += filtered_data_len;
707 rv = true;
708 } else {
709 // Read again since we haven't received enough data yet (e.g., we
710 // may not have a complete gzip header yet).
711 continue;
713 break;
715 case Filter::FILTER_OK: {
716 *bytes_read = filtered_data_len;
717 postfilter_bytes_read_ += filtered_data_len;
718 rv = true;
719 break;
721 case Filter::FILTER_ERROR: {
722 DVLOG(1) << __FUNCTION__ << "() "
723 << "\"" << (request_ ? request_->url().spec() : "???")
724 << "\"" << " Filter Error";
725 filter_needs_more_output_space_ = false;
726 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED,
727 ERR_CONTENT_DECODING_FAILED));
728 rv = false;
729 break;
731 default: {
732 NOTREACHED();
733 filter_needs_more_output_space_ = false;
734 rv = false;
735 break;
739 // If logging all bytes is enabled, log the filtered bytes read.
740 if (rv && request() && filtered_data_len > 0 &&
741 request()->net_log().IsCapturing()) {
742 request()->net_log().AddByteTransferEvent(
743 NetLog::TYPE_URL_REQUEST_JOB_FILTERED_BYTES_READ, filtered_data_len,
744 filtered_read_buffer_->data());
746 } else {
747 // we are done, or there is no data left.
748 rv = true;
750 break;
753 if (rv) {
754 // When we successfully finished a read, we no longer need to save the
755 // caller's buffers. Release our reference.
756 filtered_read_buffer_ = NULL;
757 filtered_read_buffer_len_ = 0;
759 return rv;
762 void URLRequestJob::DestroyFilters() {
763 filter_.reset();
766 const URLRequestStatus URLRequestJob::GetStatus() {
767 if (request_)
768 return request_->status();
769 // If the request is gone, we must be cancelled.
770 return URLRequestStatus(URLRequestStatus::CANCELED,
771 ERR_ABORTED);
774 void URLRequestJob::SetStatus(const URLRequestStatus &status) {
775 if (request_) {
776 // An error status should never be replaced by a non-error status by a
777 // URLRequestJob. URLRequest has some retry paths, but it resets the status
778 // itself, if needed.
779 DCHECK(request_->status().is_io_pending() ||
780 request_->status().is_success() ||
781 (!status.is_success() && !status.is_io_pending()));
782 request_->set_status(status);
786 void URLRequestJob::SetProxyServer(const HostPortPair& proxy_server) {
787 request_->proxy_server_ = proxy_server;
790 bool URLRequestJob::ReadRawDataForFilter(int* bytes_read) {
791 bool rv = false;
793 DCHECK(bytes_read);
794 DCHECK(filter_.get());
796 *bytes_read = 0;
798 // Get more pre-filtered data if needed.
799 // TODO(mbelshe): is it possible that the filter needs *MORE* data
800 // when there is some data already in the buffer?
801 if (!filter_->stream_data_len() && !is_done()) {
802 IOBuffer* stream_buffer = filter_->stream_buffer();
803 int stream_buffer_size = filter_->stream_buffer_size();
804 rv = ReadRawDataHelper(stream_buffer, stream_buffer_size, bytes_read);
806 return rv;
809 bool URLRequestJob::ReadRawDataHelper(IOBuffer* buf, int buf_size,
810 int* bytes_read) {
811 DCHECK(!request_->status().is_io_pending());
812 DCHECK(raw_read_buffer_.get() == NULL);
814 // Keep a pointer to the read buffer, so we have access to it in the
815 // OnRawReadComplete() callback in the event that the read completes
816 // asynchronously.
817 raw_read_buffer_ = buf;
818 bool rv = ReadRawData(buf, buf_size, bytes_read);
820 if (!request_->status().is_io_pending()) {
821 // If the read completes synchronously, either success or failure,
822 // invoke the OnRawReadComplete callback so we can account for the
823 // completed read.
824 OnRawReadComplete(*bytes_read);
826 return rv;
829 void URLRequestJob::FollowRedirect(const RedirectInfo& redirect_info) {
830 int rv = request_->Redirect(redirect_info);
831 if (rv != OK)
832 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, rv));
835 void URLRequestJob::OnRawReadComplete(int bytes_read) {
836 DCHECK(raw_read_buffer_.get());
837 // If |filter_| is non-NULL, bytes will be logged after it is applied instead.
838 if (!filter_.get() && request() && bytes_read > 0 &&
839 request()->net_log().IsCapturing()) {
840 request()->net_log().AddByteTransferEvent(
841 NetLog::TYPE_URL_REQUEST_JOB_BYTES_READ,
842 bytes_read, raw_read_buffer_->data());
845 if (bytes_read > 0) {
846 RecordBytesRead(bytes_read);
848 raw_read_buffer_ = NULL;
851 void URLRequestJob::RecordBytesRead(int bytes_read) {
852 DCHECK_GT(bytes_read, 0);
853 prefilter_bytes_read_ += bytes_read;
855 // On first read, notify NetworkQualityEstimator that response headers have
856 // been received.
857 // TODO(tbansal): Move this to url_request_http_job.cc. This may catch
858 // Service Worker jobs twice.
859 // If prefilter_bytes_read_ is equal to bytes_read, it indicates this is the
860 // first raw read of the response body. This is used as the signal that
861 // response headers have been received.
862 if (request_ && request_->context()->network_quality_estimator() &&
863 prefilter_bytes_read_ == bytes_read) {
864 request_->context()->network_quality_estimator()->NotifyHeadersReceived(
865 *request_);
868 if (!filter_.get())
869 postfilter_bytes_read_ += bytes_read;
870 DVLOG(2) << __FUNCTION__ << "() "
871 << "\"" << (request_ ? request_->url().spec() : "???") << "\""
872 << " pre bytes read = " << bytes_read
873 << " pre total = " << prefilter_bytes_read_
874 << " post total = " << postfilter_bytes_read_;
875 UpdatePacketReadTimes(); // Facilitate stats recording if it is active.
877 // Notify observers if any additional network usage has occurred. Note that
878 // the number of received bytes over the network sent by this notification
879 // could be vastly different from |bytes_read|, such as when a large chunk of
880 // network bytes is received before multiple smaller raw reads are performed
881 // on it.
882 MaybeNotifyNetworkBytes();
885 bool URLRequestJob::FilterHasData() {
886 return filter_.get() && filter_->stream_data_len();
889 void URLRequestJob::UpdatePacketReadTimes() {
892 RedirectInfo URLRequestJob::ComputeRedirectInfo(const GURL& location,
893 int http_status_code) {
894 const GURL& url = request_->url();
896 RedirectInfo redirect_info;
898 redirect_info.status_code = http_status_code;
900 // The request method may change, depending on the status code.
901 redirect_info.new_method =
902 ComputeMethodForRedirect(request_->method(), http_status_code);
904 // Move the reference fragment of the old location to the new one if the
905 // new one has none. This duplicates mozilla's behavior.
906 if (url.is_valid() && url.has_ref() && !location.has_ref() &&
907 CopyFragmentOnRedirect(location)) {
908 GURL::Replacements replacements;
909 // Reference the |ref| directly out of the original URL to avoid a
910 // malloc.
911 replacements.SetRef(url.spec().data(),
912 url.parsed_for_possibly_invalid_spec().ref);
913 redirect_info.new_url = location.ReplaceComponents(replacements);
914 } else {
915 redirect_info.new_url = location;
918 // Update the first-party URL if appropriate.
919 if (request_->first_party_url_policy() ==
920 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT) {
921 redirect_info.new_first_party_for_cookies = redirect_info.new_url;
922 } else {
923 redirect_info.new_first_party_for_cookies =
924 request_->first_party_for_cookies();
927 // Alter the referrer if redirecting cross-origin (especially HTTP->HTTPS).
928 redirect_info.new_referrer =
929 ComputeReferrerForRedirect(request_->referrer_policy(),
930 request_->referrer(),
931 redirect_info.new_url).spec();
933 return redirect_info;
936 void URLRequestJob::MaybeNotifyNetworkBytes() {
937 if (!request_ || !network_delegate_)
938 return;
940 int64_t total_received_bytes = GetTotalReceivedBytes();
941 DCHECK_GE(total_received_bytes, last_notified_total_received_bytes_);
942 if (total_received_bytes > last_notified_total_received_bytes_) {
943 network_delegate_->NotifyNetworkBytesReceived(
944 *request_, total_received_bytes - last_notified_total_received_bytes_);
946 last_notified_total_received_bytes_ = total_received_bytes;
949 } // namespace net