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"
8 #include "base/compiler_specific.h"
9 #include "base/message_loop/message_loop.h"
10 #include "base/power_monitor/power_monitor.h"
11 #include "base/profiler/scoped_tracker.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_util.h"
14 #include "base/values.h"
15 #include "net/base/auth.h"
16 #include "net/base/host_port_pair.h"
17 #include "net/base/io_buffer.h"
18 #include "net/base/load_states.h"
19 #include "net/base/net_errors.h"
20 #include "net/base/network_delegate.h"
21 #include "net/filter/filter.h"
22 #include "net/http/http_response_headers.h"
26 // Callback for TYPE_URL_REQUEST_FILTERS_SET net-internals event.
27 base::Value
* FiltersSetCallback(net::Filter
* filter
,
28 enum net::NetLog::LogLevel
/* log_level */) {
29 base::DictionaryValue
* event_params
= new base::DictionaryValue();
30 event_params
->SetString("filters", filter
->OrderedFilterList());
38 URLRequestJob::URLRequestJob(URLRequest
* request
,
39 NetworkDelegate
* network_delegate
)
42 prefilter_bytes_read_(0),
43 postfilter_bytes_read_(0),
44 filter_input_byte_count_(0),
45 filter_needs_more_output_space_(false),
46 filtered_read_buffer_len_(0),
47 has_handled_response_(false),
48 expected_content_size_(-1),
49 network_delegate_(network_delegate
),
51 base::PowerMonitor
* power_monitor
= base::PowerMonitor::Get();
53 power_monitor
->AddObserver(this);
56 void URLRequestJob::SetUpload(UploadDataStream
* upload
) {
59 void URLRequestJob::SetExtraRequestHeaders(const HttpRequestHeaders
& headers
) {
62 void URLRequestJob::SetPriority(RequestPriority priority
) {
65 void URLRequestJob::Kill() {
66 weak_factory_
.InvalidateWeakPtrs();
67 // Make sure the request is notified that we are done. We assume that the
68 // request took care of setting its error status before calling Kill.
73 void URLRequestJob::DetachRequest() {
77 // This function calls ReadData to get stream data. If a filter exists, passes
78 // the data to the attached filter. Then returns the output from filter back to
80 bool URLRequestJob::Read(IOBuffer
* buf
, int buf_size
, int *bytes_read
) {
83 DCHECK_LT(buf_size
, 1000000); // Sanity check.
86 DCHECK(filtered_read_buffer_
.get() == NULL
);
87 DCHECK_EQ(0, filtered_read_buffer_len_
);
91 // Skip Filter if not present.
93 rv
= ReadRawDataHelper(buf
, buf_size
, bytes_read
);
95 // Save the caller's buffers while we do IO
96 // in the filter's buffers.
97 filtered_read_buffer_
= buf
;
98 filtered_read_buffer_len_
= buf_size
;
100 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
101 tracked_objects::ScopedTracker
tracking_profile2(
102 FROM_HERE_WITH_EXPLICIT_FUNCTION("423948 URLRequestJob::Read2"));
104 if (ReadFilteredData(bytes_read
)) {
105 rv
= true; // We have data to return.
107 // It is fine to call DoneReading even if ReadFilteredData receives 0
108 // bytes from the net, but we avoid making that call if we know for
109 // sure that's the case (ReadRawDataHelper path).
110 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is
112 tracked_objects::ScopedTracker
tracking_profile3(
113 FROM_HERE_WITH_EXPLICIT_FUNCTION("423948 URLRequestJob::Read3"));
115 if (*bytes_read
== 0)
118 rv
= false; // Error, or a new IO is pending.
122 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
123 tracked_objects::ScopedTracker
tracking_profile4(
124 FROM_HERE_WITH_EXPLICIT_FUNCTION("423948 URLRequestJob::Read4"));
126 if (rv
&& *bytes_read
== 0)
127 NotifyDone(URLRequestStatus());
131 void URLRequestJob::StopCaching() {
132 // Nothing to do here.
135 bool URLRequestJob::GetFullRequestHeaders(HttpRequestHeaders
* headers
) const {
136 // Most job types don't send request headers.
140 int64
URLRequestJob::GetTotalReceivedBytes() const {
144 LoadState
URLRequestJob::GetLoadState() const {
145 return LOAD_STATE_IDLE
;
148 UploadProgress
URLRequestJob::GetUploadProgress() const {
149 return UploadProgress();
152 bool URLRequestJob::GetCharset(std::string
* charset
) {
156 void URLRequestJob::GetResponseInfo(HttpResponseInfo
* info
) {
159 void URLRequestJob::GetLoadTimingInfo(LoadTimingInfo
* load_timing_info
) const {
160 // Only certain request types return more than just request start times.
163 bool URLRequestJob::GetResponseCookies(std::vector
<std::string
>* cookies
) {
167 Filter
* URLRequestJob::SetupFilter() const {
171 bool URLRequestJob::IsRedirectResponse(GURL
* location
,
172 int* http_status_code
) {
173 // For non-HTTP jobs, headers will be null.
174 HttpResponseHeaders
* headers
= request_
->response_headers();
179 if (!headers
->IsRedirect(&value
))
182 *location
= request_
->url().Resolve(value
);
183 *http_status_code
= headers
->response_code();
187 bool URLRequestJob::CopyFragmentOnRedirect(const GURL
& location
) const {
191 bool URLRequestJob::IsSafeRedirect(const GURL
& location
) {
195 bool URLRequestJob::NeedsAuth() {
199 void URLRequestJob::GetAuthChallengeInfo(
200 scoped_refptr
<AuthChallengeInfo
>* auth_info
) {
201 // This will only be called if NeedsAuth() returns true, in which
202 // case the derived class should implement this!
206 void URLRequestJob::SetAuth(const AuthCredentials
& credentials
) {
207 // This will only be called if NeedsAuth() returns true, in which
208 // case the derived class should implement this!
212 void URLRequestJob::CancelAuth() {
213 // This will only be called if NeedsAuth() returns true, in which
214 // case the derived class should implement this!
218 void URLRequestJob::ContinueWithCertificate(
219 X509Certificate
* client_cert
) {
220 // The derived class should implement this!
224 void URLRequestJob::ContinueDespiteLastError() {
225 // Implementations should know how to recover from errors they generate.
226 // If this code was reached, we are trying to recover from an error that
227 // we don't know how to recover from.
231 void URLRequestJob::FollowDeferredRedirect() {
232 DCHECK_NE(-1, deferred_redirect_info_
.status_code
);
234 // NOTE: deferred_redirect_info_ may be invalid, and attempting to follow it
235 // will fail inside FollowRedirect. The DCHECK above asserts that we called
236 // OnReceivedRedirect.
238 // It is also possible that FollowRedirect will drop the last reference to
239 // this job, so we need to reset our members before calling it.
241 RedirectInfo redirect_info
= deferred_redirect_info_
;
242 deferred_redirect_info_
= RedirectInfo();
243 FollowRedirect(redirect_info
);
246 void URLRequestJob::ResumeNetworkStart() {
247 // This should only be called for HTTP Jobs, and implemented in the derived
252 bool URLRequestJob::GetMimeType(std::string
* mime_type
) const {
256 int URLRequestJob::GetResponseCode() const {
260 HostPortPair
URLRequestJob::GetSocketAddress() const {
261 return HostPortPair();
264 void URLRequestJob::OnSuspend() {
268 void URLRequestJob::NotifyURLRequestDestroyed() {
272 GURL
URLRequestJob::ComputeReferrerForRedirect(
273 URLRequest::ReferrerPolicy policy
,
274 const std::string
& referrer
,
275 const GURL
& redirect_destination
) {
276 GURL
original_referrer(referrer
);
277 bool secure_referrer_but_insecure_destination
=
278 original_referrer
.SchemeIsSecure() &&
279 !redirect_destination
.SchemeIsSecure();
281 original_referrer
.GetOrigin() == redirect_destination
.GetOrigin();
283 case URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
:
284 return secure_referrer_but_insecure_destination
? GURL()
287 case URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN
:
289 return original_referrer
;
290 } else if (secure_referrer_but_insecure_destination
) {
293 return original_referrer
.GetOrigin();
296 case URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN
:
297 return same_origin
? original_referrer
: original_referrer
.GetOrigin();
299 case URLRequest::NEVER_CLEAR_REFERRER
:
300 return original_referrer
;
307 URLRequestJob::~URLRequestJob() {
308 base::PowerMonitor
* power_monitor
= base::PowerMonitor::Get();
310 power_monitor
->RemoveObserver(this);
313 void URLRequestJob::NotifyCertificateRequested(
314 SSLCertRequestInfo
* cert_request_info
) {
316 return; // The request was destroyed, so there is no more work to do.
318 request_
->NotifyCertificateRequested(cert_request_info
);
321 void URLRequestJob::NotifySSLCertificateError(const SSLInfo
& ssl_info
,
324 return; // The request was destroyed, so there is no more work to do.
326 request_
->NotifySSLCertificateError(ssl_info
, fatal
);
329 bool URLRequestJob::CanGetCookies(const CookieList
& cookie_list
) const {
331 return false; // The request was destroyed, so there is no more work to do.
333 return request_
->CanGetCookies(cookie_list
);
336 bool URLRequestJob::CanSetCookie(const std::string
& cookie_line
,
337 CookieOptions
* options
) const {
339 return false; // The request was destroyed, so there is no more work to do.
341 return request_
->CanSetCookie(cookie_line
, options
);
344 bool URLRequestJob::CanEnablePrivacyMode() const {
346 return false; // The request was destroyed, so there is no more work to do.
348 return request_
->CanEnablePrivacyMode();
351 CookieStore
* URLRequestJob::GetCookieStore() const {
354 return request_
->cookie_store();
357 void URLRequestJob::NotifyBeforeNetworkStart(bool* defer
) {
361 request_
->NotifyBeforeNetworkStart(defer
);
364 void URLRequestJob::NotifyHeadersComplete() {
365 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
366 tracked_objects::ScopedTracker
tracking_profile(
367 FROM_HERE_WITH_EXPLICIT_FUNCTION(
368 "423948 URLRequestJob::NotifyHeadersComplete"));
370 if (!request_
|| !request_
->has_delegate())
371 return; // The request was destroyed, so there is no more work to do.
373 if (has_handled_response_
)
376 DCHECK(!request_
->status().is_io_pending());
378 // Initialize to the current time, and let the subclass optionally override
379 // the time stamps if it has that information. The default request_time is
380 // set by URLRequest before it calls our Start method.
381 request_
->response_info_
.response_time
= base::Time::Now();
382 GetResponseInfo(&request_
->response_info_
);
384 // When notifying the delegate, the delegate can release the request
385 // (and thus release 'this'). After calling to the delgate, we must
386 // check the request pointer to see if it still exists, and return
387 // immediately if it has been destroyed. self_preservation ensures our
388 // survival until we can get out of this method.
389 scoped_refptr
<URLRequestJob
> self_preservation(this);
392 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
393 tracked_objects::ScopedTracker
tracking_profile1(
394 FROM_HERE_WITH_EXPLICIT_FUNCTION(
395 "423948 URLRequestJob::NotifyHeadersComplete 1"));
397 request_
->OnHeadersComplete();
400 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
401 tracked_objects::ScopedTracker
tracking_profile2(
402 FROM_HERE_WITH_EXPLICIT_FUNCTION(
403 "423948 URLRequestJob::NotifyHeadersComplete 2"));
406 int http_status_code
;
407 if (IsRedirectResponse(&new_location
, &http_status_code
)) {
408 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
409 tracked_objects::ScopedTracker
tracking_profile3(
410 FROM_HERE_WITH_EXPLICIT_FUNCTION(
411 "423948 URLRequestJob::NotifyHeadersComplete 3"));
413 // Redirect response bodies are not read. Notify the transaction
414 // so it does not treat being stopped as an error.
415 DoneReadingRedirectResponse();
417 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
418 tracked_objects::ScopedTracker
tracking_profile4(
419 FROM_HERE_WITH_EXPLICIT_FUNCTION(
420 "423948 URLRequestJob::NotifyHeadersComplete 4"));
422 RedirectInfo redirect_info
=
423 ComputeRedirectInfo(new_location
, http_status_code
);
425 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
426 tracked_objects::ScopedTracker
tracking_profile5(
427 FROM_HERE_WITH_EXPLICIT_FUNCTION(
428 "423948 URLRequestJob::NotifyHeadersComplete 5"));
430 bool defer_redirect
= false;
431 request_
->NotifyReceivedRedirect(redirect_info
, &defer_redirect
);
433 // Ensure that the request wasn't detached or destroyed in
434 // NotifyReceivedRedirect
435 if (!request_
|| !request_
->has_delegate())
438 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
439 tracked_objects::ScopedTracker
tracking_profile6(
440 FROM_HERE_WITH_EXPLICIT_FUNCTION(
441 "423948 URLRequestJob::NotifyHeadersComplete 6"));
443 // If we were not cancelled, then maybe follow the redirect.
444 if (request_
->status().is_success()) {
445 if (defer_redirect
) {
446 deferred_redirect_info_
= redirect_info
;
448 FollowRedirect(redirect_info
);
452 } else if (NeedsAuth()) {
453 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
454 tracked_objects::ScopedTracker
tracking_profile7(
455 FROM_HERE_WITH_EXPLICIT_FUNCTION(
456 "423948 URLRequestJob::NotifyHeadersComplete 7"));
458 scoped_refptr
<AuthChallengeInfo
> auth_info
;
459 GetAuthChallengeInfo(&auth_info
);
461 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
462 tracked_objects::ScopedTracker
tracking_profile8(
463 FROM_HERE_WITH_EXPLICIT_FUNCTION(
464 "423948 URLRequestJob::NotifyHeadersComplete 8"));
466 // Need to check for a NULL auth_info because the server may have failed
467 // to send a challenge with the 401 response.
468 if (auth_info
.get()) {
469 request_
->NotifyAuthRequired(auth_info
.get());
470 // Wait for SetAuth or CancelAuth to be called.
475 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
476 tracked_objects::ScopedTracker
tracking_profile9(
477 FROM_HERE_WITH_EXPLICIT_FUNCTION(
478 "423948 URLRequestJob::NotifyHeadersComplete 9"));
480 has_handled_response_
= true;
481 if (request_
->status().is_success())
482 filter_
.reset(SetupFilter());
484 if (!filter_
.get()) {
485 std::string content_length
;
486 request_
->GetResponseHeaderByName("content-length", &content_length
);
487 if (!content_length
.empty())
488 base::StringToInt64(content_length
, &expected_content_size_
);
490 request_
->net_log().AddEvent(
491 NetLog::TYPE_URL_REQUEST_FILTERS_SET
,
492 base::Bind(&FiltersSetCallback
, base::Unretained(filter_
.get())));
495 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
496 tracked_objects::ScopedTracker
tracking_profile10(
497 FROM_HERE_WITH_EXPLICIT_FUNCTION(
498 "423948 URLRequestJob::NotifyHeadersComplete 10"));
500 request_
->NotifyResponseStarted();
503 void URLRequestJob::NotifyReadComplete(int bytes_read
) {
504 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
505 tracked_objects::ScopedTracker
tracking_profile(
506 FROM_HERE_WITH_EXPLICIT_FUNCTION("URLRequestJob::NotifyReadComplete"));
508 if (!request_
|| !request_
->has_delegate())
509 return; // The request was destroyed, so there is no more work to do.
511 // TODO(darin): Bug 1004233. Re-enable this test once all of the chrome
512 // unit_tests have been fixed to not trip this.
514 DCHECK(!request_
->status().is_io_pending());
516 // The headers should be complete before reads complete
517 DCHECK(has_handled_response_
);
519 OnRawReadComplete(bytes_read
);
521 // Don't notify if we had an error.
522 if (!request_
->status().is_success())
525 // When notifying the delegate, the delegate can release the request
526 // (and thus release 'this'). After calling to the delegate, we must
527 // check the request pointer to see if it still exists, and return
528 // immediately if it has been destroyed. self_preservation ensures our
529 // survival until we can get out of this method.
530 scoped_refptr
<URLRequestJob
> self_preservation(this);
533 // Tell the filter that it has more data
534 FilteredDataRead(bytes_read
);
537 int filter_bytes_read
= 0;
538 if (ReadFilteredData(&filter_bytes_read
)) {
539 if (!filter_bytes_read
)
541 request_
->NotifyReadCompleted(filter_bytes_read
);
544 request_
->NotifyReadCompleted(bytes_read
);
546 DVLOG(1) << __FUNCTION__
<< "() "
547 << "\"" << (request_
? request_
->url().spec() : "???") << "\""
548 << " pre bytes read = " << bytes_read
549 << " pre total = " << prefilter_bytes_read_
550 << " post total = " << postfilter_bytes_read_
;
553 void URLRequestJob::NotifyStartError(const URLRequestStatus
&status
) {
554 DCHECK(!has_handled_response_
);
555 has_handled_response_
= true;
557 // There may be relevant information in the response info even in the
559 GetResponseInfo(&request_
->response_info_
);
561 request_
->set_status(status
);
562 request_
->NotifyResponseStarted();
563 // We may have been deleted.
567 void URLRequestJob::NotifyDone(const URLRequestStatus
&status
) {
568 DCHECK(!done_
) << "Job sending done notification twice";
573 // Unless there was an error, we should have at least tried to handle
574 // the response before getting here.
575 DCHECK(has_handled_response_
|| !status
.is_success());
577 // As with NotifyReadComplete, we need to take care to notice if we were
578 // destroyed during a delegate callback.
580 request_
->set_is_pending(false);
581 // With async IO, it's quite possible to have a few outstanding
582 // requests. We could receive a request to Cancel, followed shortly
583 // by a successful IO. For tracking the status(), once there is
584 // an error, we do not change the status back to success. To
585 // enforce this, only set the status if the job is so far
587 if (request_
->status().is_success()) {
588 if (status
.status() == URLRequestStatus::FAILED
) {
589 request_
->net_log().AddEventWithNetErrorCode(NetLog::TYPE_FAILED
,
592 request_
->set_status(status
);
596 // Complete this notification later. This prevents us from re-entering the
597 // delegate if we're done because of a synchronous call.
598 base::MessageLoop::current()->PostTask(
600 base::Bind(&URLRequestJob::CompleteNotifyDone
,
601 weak_factory_
.GetWeakPtr()));
604 void URLRequestJob::CompleteNotifyDone() {
605 // Check if we should notify the delegate that we're done because of an error.
607 !request_
->status().is_success() &&
608 request_
->has_delegate()) {
609 // We report the error differently depending on whether we've called
610 // OnResponseStarted yet.
611 if (has_handled_response_
) {
612 // We signal the error by calling OnReadComplete with a bytes_read of -1.
613 request_
->NotifyReadCompleted(-1);
615 has_handled_response_
= true;
616 request_
->NotifyResponseStarted();
621 void URLRequestJob::NotifyCanceled() {
623 NotifyDone(URLRequestStatus(URLRequestStatus::CANCELED
, ERR_ABORTED
));
627 void URLRequestJob::NotifyRestartRequired() {
628 DCHECK(!has_handled_response_
);
629 if (GetStatus().status() != URLRequestStatus::CANCELED
)
633 void URLRequestJob::OnCallToDelegate() {
634 request_
->OnCallToDelegate();
637 void URLRequestJob::OnCallToDelegateComplete() {
638 request_
->OnCallToDelegateComplete();
641 bool URLRequestJob::ReadRawData(IOBuffer
* buf
, int buf_size
,
648 void URLRequestJob::DoneReading() {
652 void URLRequestJob::DoneReadingRedirectResponse() {
655 void URLRequestJob::FilteredDataRead(int bytes_read
) {
657 filter_
->FlushStreamBuffer(bytes_read
);
660 bool URLRequestJob::ReadFilteredData(int* bytes_read
) {
662 DCHECK(filtered_read_buffer_
.get());
663 DCHECK_GT(filtered_read_buffer_len_
, 0);
664 DCHECK_LT(filtered_read_buffer_len_
, 1000000); // Sanity check.
665 DCHECK(!raw_read_buffer_
.get());
674 if (!filter_needs_more_output_space_
&& !filter_
->stream_data_len()) {
675 // We don't have any raw data to work with, so read from the transaction.
676 int filtered_data_read
;
677 if (ReadRawDataForFilter(&filtered_data_read
)) {
678 if (filtered_data_read
> 0) {
679 // Give data to filter.
680 filter_
->FlushStreamBuffer(filtered_data_read
);
685 return false; // IO Pending (or error).
689 if ((filter_
->stream_data_len() || filter_needs_more_output_space_
) &&
691 // Get filtered data.
692 int filtered_data_len
= filtered_read_buffer_len_
;
693 int output_buffer_size
= filtered_data_len
;
694 Filter::FilterStatus status
=
695 filter_
->ReadData(filtered_read_buffer_
->data(), &filtered_data_len
);
697 if (filter_needs_more_output_space_
&& !filtered_data_len
) {
698 // filter_needs_more_output_space_ was mistaken... there are no more
699 // bytes and we should have at least tried to fill up the filter's input
700 // buffer. Correct the state, and try again.
701 filter_needs_more_output_space_
= false;
704 filter_needs_more_output_space_
=
705 (filtered_data_len
== output_buffer_size
);
708 case Filter::FILTER_DONE
: {
709 filter_needs_more_output_space_
= false;
710 *bytes_read
= filtered_data_len
;
711 postfilter_bytes_read_
+= filtered_data_len
;
715 case Filter::FILTER_NEED_MORE_DATA
: {
716 // We have finished filtering all data currently in the buffer.
717 // There might be some space left in the output buffer. One can
718 // consider reading more data from the stream to feed the filter
719 // and filling up the output buffer. This leads to more complicated
720 // buffer management and data notification mechanisms.
721 // We can revisit this issue if there is a real perf need.
722 if (filtered_data_len
> 0) {
723 *bytes_read
= filtered_data_len
;
724 postfilter_bytes_read_
+= filtered_data_len
;
727 // Read again since we haven't received enough data yet (e.g., we
728 // may not have a complete gzip header yet).
733 case Filter::FILTER_OK
: {
734 *bytes_read
= filtered_data_len
;
735 postfilter_bytes_read_
+= filtered_data_len
;
739 case Filter::FILTER_ERROR
: {
740 DVLOG(1) << __FUNCTION__
<< "() "
741 << "\"" << (request_
? request_
->url().spec() : "???")
742 << "\"" << " Filter Error";
743 filter_needs_more_output_space_
= false;
744 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED
,
745 ERR_CONTENT_DECODING_FAILED
));
751 filter_needs_more_output_space_
= false;
757 // If logging all bytes is enabled, log the filtered bytes read.
758 if (rv
&& request() && request()->net_log().IsLoggingBytes() &&
759 filtered_data_len
> 0) {
760 request()->net_log().AddByteTransferEvent(
761 NetLog::TYPE_URL_REQUEST_JOB_FILTERED_BYTES_READ
,
762 filtered_data_len
, filtered_read_buffer_
->data());
765 // we are done, or there is no data left.
772 // When we successfully finished a read, we no longer need to save the
773 // caller's buffers. Release our reference.
774 filtered_read_buffer_
= NULL
;
775 filtered_read_buffer_len_
= 0;
780 void URLRequestJob::DestroyFilters() {
784 const URLRequestStatus
URLRequestJob::GetStatus() {
786 return request_
->status();
787 // If the request is gone, we must be cancelled.
788 return URLRequestStatus(URLRequestStatus::CANCELED
,
792 void URLRequestJob::SetStatus(const URLRequestStatus
&status
) {
794 request_
->set_status(status
);
797 void URLRequestJob::SetProxyServer(const HostPortPair
& proxy_server
) {
798 request_
->proxy_server_
= proxy_server
;
801 bool URLRequestJob::ReadRawDataForFilter(int* bytes_read
) {
805 DCHECK(filter_
.get());
809 // Get more pre-filtered data if needed.
810 // TODO(mbelshe): is it possible that the filter needs *MORE* data
811 // when there is some data already in the buffer?
812 if (!filter_
->stream_data_len() && !is_done()) {
813 IOBuffer
* stream_buffer
= filter_
->stream_buffer();
814 int stream_buffer_size
= filter_
->stream_buffer_size();
815 rv
= ReadRawDataHelper(stream_buffer
, stream_buffer_size
, bytes_read
);
820 bool URLRequestJob::ReadRawDataHelper(IOBuffer
* buf
, int buf_size
,
822 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
823 tracked_objects::ScopedTracker
tracking_profile(
824 FROM_HERE_WITH_EXPLICIT_FUNCTION(
825 "423948 URLRequestJob::ReadRawDataHelper"));
827 DCHECK(!request_
->status().is_io_pending());
828 DCHECK(raw_read_buffer_
.get() == NULL
);
830 // Keep a pointer to the read buffer, so we have access to it in the
831 // OnRawReadComplete() callback in the event that the read completes
833 raw_read_buffer_
= buf
;
834 bool rv
= ReadRawData(buf
, buf_size
, bytes_read
);
836 if (!request_
->status().is_io_pending()) {
837 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
838 tracked_objects::ScopedTracker
tracking_profile1(
839 FROM_HERE_WITH_EXPLICIT_FUNCTION(
840 "423948 URLRequestJob::ReadRawDataHelper1"));
842 // If the read completes synchronously, either success or failure,
843 // invoke the OnRawReadComplete callback so we can account for the
845 OnRawReadComplete(*bytes_read
);
850 void URLRequestJob::FollowRedirect(const RedirectInfo
& redirect_info
) {
851 int rv
= request_
->Redirect(redirect_info
);
853 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED
, rv
));
856 void URLRequestJob::OnRawReadComplete(int bytes_read
) {
857 DCHECK(raw_read_buffer_
.get());
858 // If |filter_| is non-NULL, bytes will be logged after it is applied instead.
859 if (!filter_
.get() && request() && request()->net_log().IsLoggingBytes() &&
861 request()->net_log().AddByteTransferEvent(
862 NetLog::TYPE_URL_REQUEST_JOB_BYTES_READ
,
863 bytes_read
, raw_read_buffer_
->data());
866 if (bytes_read
> 0) {
867 RecordBytesRead(bytes_read
);
869 raw_read_buffer_
= NULL
;
872 void URLRequestJob::RecordBytesRead(int bytes_read
) {
873 filter_input_byte_count_
+= bytes_read
;
874 prefilter_bytes_read_
+= bytes_read
;
876 postfilter_bytes_read_
+= bytes_read
;
877 DVLOG(2) << __FUNCTION__
<< "() "
878 << "\"" << (request_
? request_
->url().spec() : "???") << "\""
879 << " pre bytes read = " << bytes_read
880 << " pre total = " << prefilter_bytes_read_
881 << " post total = " << postfilter_bytes_read_
;
882 UpdatePacketReadTimes(); // Facilitate stats recording if it is active.
883 if (network_delegate_
) {
884 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
885 tracked_objects::ScopedTracker
tracking_profile(
886 FROM_HERE_WITH_EXPLICIT_FUNCTION(
887 "423948 URLRequestJob::RecordBytesRead NotifyRawBytesRead"));
889 network_delegate_
->NotifyRawBytesRead(*request_
, bytes_read
);
893 bool URLRequestJob::FilterHasData() {
894 return filter_
.get() && filter_
->stream_data_len();
897 void URLRequestJob::UpdatePacketReadTimes() {
900 RedirectInfo
URLRequestJob::ComputeRedirectInfo(const GURL
& location
,
901 int http_status_code
) {
902 const GURL
& url
= request_
->url();
904 RedirectInfo redirect_info
;
906 redirect_info
.status_code
= http_status_code
;
908 // The request method may change, depending on the status code.
909 redirect_info
.new_method
= URLRequest::ComputeMethodForRedirect(
910 request_
->method(), http_status_code
);
912 // Move the reference fragment of the old location to the new one if the
913 // new one has none. This duplicates mozilla's behavior.
914 if (url
.is_valid() && url
.has_ref() && !location
.has_ref() &&
915 CopyFragmentOnRedirect(location
)) {
916 GURL::Replacements replacements
;
917 // Reference the |ref| directly out of the original URL to avoid a
919 replacements
.SetRef(url
.spec().data(),
920 url
.parsed_for_possibly_invalid_spec().ref
);
921 redirect_info
.new_url
= location
.ReplaceComponents(replacements
);
923 redirect_info
.new_url
= location
;
926 // Update the first-party URL if appropriate.
927 if (request_
->first_party_url_policy() ==
928 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
) {
929 redirect_info
.new_first_party_for_cookies
= redirect_info
.new_url
;
931 redirect_info
.new_first_party_for_cookies
=
932 request_
->first_party_for_cookies();
935 // Alter the referrer if redirecting cross-origin (especially HTTP->HTTPS).
936 redirect_info
.new_referrer
=
937 ComputeReferrerForRedirect(request_
->referrer_policy(),
938 request_
->referrer(),
939 redirect_info
.new_url
).spec();
941 return redirect_info
;