Split bug 423948 into various sub-bugs and remove outdated instrumentation.
[chromium-blink-merge.git] / net / url_request / url_request_job.cc
blob9ba87b4dac8d2bee7df6e522979e59149c47a972
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/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"
24 namespace net {
26 namespace {
28 // Callback for TYPE_URL_REQUEST_FILTERS_SET net-internals event.
29 base::Value* FiltersSetCallback(Filter* filter,
30 NetLog::LogLevel /* log_level */) {
31 base::DictionaryValue* event_params = new base::DictionaryValue();
32 event_params->SetString("filters", filter->OrderedFilterList());
33 return event_params;
36 std::string ComputeMethodForRedirect(const std::string& method,
37 int http_status_code) {
38 // For 303 redirects, all request methods except HEAD are converted to GET,
39 // as per the latest httpbis draft. The draft also allows POST requests to
40 // be converted to GETs when following 301/302 redirects, for historical
41 // reasons. Most major browsers do this and so shall we. Both RFC 2616 and
42 // the httpbis draft say to prompt the user to confirm the generation of new
43 // requests, other than GET and HEAD requests, but IE omits these prompts and
44 // so shall we.
45 // See:
46 // https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-17#section-7.3
47 if ((http_status_code == 303 && method != "HEAD") ||
48 ((http_status_code == 301 || http_status_code == 302) &&
49 method == "POST")) {
50 return "GET";
52 return method;
55 } // namespace
57 URLRequestJob::URLRequestJob(URLRequest* request,
58 NetworkDelegate* network_delegate)
59 : request_(request),
60 done_(false),
61 prefilter_bytes_read_(0),
62 postfilter_bytes_read_(0),
63 filter_input_byte_count_(0),
64 filter_needs_more_output_space_(false),
65 filtered_read_buffer_len_(0),
66 has_handled_response_(false),
67 expected_content_size_(-1),
68 network_delegate_(network_delegate),
69 weak_factory_(this) {
70 base::PowerMonitor* power_monitor = base::PowerMonitor::Get();
71 if (power_monitor)
72 power_monitor->AddObserver(this);
75 void URLRequestJob::SetUpload(UploadDataStream* upload) {
78 void URLRequestJob::SetExtraRequestHeaders(const HttpRequestHeaders& headers) {
81 void URLRequestJob::SetPriority(RequestPriority priority) {
84 void URLRequestJob::Kill() {
85 weak_factory_.InvalidateWeakPtrs();
86 // Make sure the request is notified that we are done. We assume that the
87 // request took care of setting its error status before calling Kill.
88 if (request_)
89 NotifyCanceled();
92 void URLRequestJob::DetachRequest() {
93 request_ = NULL;
96 // This function calls ReadData to get stream data. If a filter exists, passes
97 // the data to the attached filter. Then returns the output from filter back to
98 // the caller.
99 bool URLRequestJob::Read(IOBuffer* buf, int buf_size, int *bytes_read) {
100 bool rv = false;
102 DCHECK_LT(buf_size, 1000000); // Sanity check.
103 DCHECK(buf);
104 DCHECK(bytes_read);
105 DCHECK(filtered_read_buffer_.get() == NULL);
106 DCHECK_EQ(0, filtered_read_buffer_len_);
108 *bytes_read = 0;
110 // Skip Filter if not present.
111 if (!filter_.get()) {
112 rv = ReadRawDataHelper(buf, buf_size, bytes_read);
113 } else {
114 // Save the caller's buffers while we do IO
115 // in the filter's buffers.
116 filtered_read_buffer_ = buf;
117 filtered_read_buffer_len_ = buf_size;
119 if (ReadFilteredData(bytes_read)) {
120 rv = true; // We have data to return.
122 // It is fine to call DoneReading even if ReadFilteredData receives 0
123 // bytes from the net, but we avoid making that call if we know for
124 // sure that's the case (ReadRawDataHelper path).
125 if (*bytes_read == 0)
126 DoneReading();
127 } else {
128 rv = false; // Error, or a new IO is pending.
132 if (rv && *bytes_read == 0)
133 NotifyDone(URLRequestStatus());
134 return rv;
137 void URLRequestJob::StopCaching() {
138 // Nothing to do here.
141 bool URLRequestJob::GetFullRequestHeaders(HttpRequestHeaders* headers) const {
142 // Most job types don't send request headers.
143 return false;
146 int64 URLRequestJob::GetTotalReceivedBytes() const {
147 return 0;
150 LoadState URLRequestJob::GetLoadState() const {
151 return LOAD_STATE_IDLE;
154 UploadProgress URLRequestJob::GetUploadProgress() const {
155 return UploadProgress();
158 bool URLRequestJob::GetCharset(std::string* charset) {
159 return false;
162 void URLRequestJob::GetResponseInfo(HttpResponseInfo* info) {
165 void URLRequestJob::GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const {
166 // Only certain request types return more than just request start times.
169 bool URLRequestJob::GetResponseCookies(std::vector<std::string>* cookies) {
170 return false;
173 Filter* URLRequestJob::SetupFilter() const {
174 return NULL;
177 bool URLRequestJob::IsRedirectResponse(GURL* location,
178 int* http_status_code) {
179 // For non-HTTP jobs, headers will be null.
180 HttpResponseHeaders* headers = request_->response_headers();
181 if (!headers)
182 return false;
184 std::string value;
185 if (!headers->IsRedirect(&value))
186 return false;
188 *location = request_->url().Resolve(value);
189 *http_status_code = headers->response_code();
190 return true;
193 bool URLRequestJob::CopyFragmentOnRedirect(const GURL& location) const {
194 return true;
197 bool URLRequestJob::IsSafeRedirect(const GURL& location) {
198 return true;
201 bool URLRequestJob::NeedsAuth() {
202 return false;
205 void URLRequestJob::GetAuthChallengeInfo(
206 scoped_refptr<AuthChallengeInfo>* auth_info) {
207 // This will only be called if NeedsAuth() returns true, in which
208 // case the derived class should implement this!
209 NOTREACHED();
212 void URLRequestJob::SetAuth(const AuthCredentials& credentials) {
213 // This will only be called if NeedsAuth() returns true, in which
214 // case the derived class should implement this!
215 NOTREACHED();
218 void URLRequestJob::CancelAuth() {
219 // This will only be called if NeedsAuth() returns true, in which
220 // case the derived class should implement this!
221 NOTREACHED();
224 void URLRequestJob::ContinueWithCertificate(
225 X509Certificate* client_cert) {
226 // The derived class should implement this!
227 NOTREACHED();
230 void URLRequestJob::ContinueDespiteLastError() {
231 // Implementations should know how to recover from errors they generate.
232 // If this code was reached, we are trying to recover from an error that
233 // we don't know how to recover from.
234 NOTREACHED();
237 void URLRequestJob::FollowDeferredRedirect() {
238 DCHECK_NE(-1, deferred_redirect_info_.status_code);
240 // NOTE: deferred_redirect_info_ may be invalid, and attempting to follow it
241 // will fail inside FollowRedirect. The DCHECK above asserts that we called
242 // OnReceivedRedirect.
244 // It is also possible that FollowRedirect will drop the last reference to
245 // this job, so we need to reset our members before calling it.
247 RedirectInfo redirect_info = deferred_redirect_info_;
248 deferred_redirect_info_ = RedirectInfo();
249 FollowRedirect(redirect_info);
252 void URLRequestJob::ResumeNetworkStart() {
253 // This should only be called for HTTP Jobs, and implemented in the derived
254 // class.
255 NOTREACHED();
258 bool URLRequestJob::GetMimeType(std::string* mime_type) const {
259 return false;
262 int URLRequestJob::GetResponseCode() const {
263 return -1;
266 HostPortPair URLRequestJob::GetSocketAddress() const {
267 return HostPortPair();
270 void URLRequestJob::OnSuspend() {
271 Kill();
274 void URLRequestJob::NotifyURLRequestDestroyed() {
277 // static
278 GURL URLRequestJob::ComputeReferrerForRedirect(
279 URLRequest::ReferrerPolicy policy,
280 const std::string& referrer,
281 const GURL& redirect_destination) {
282 GURL original_referrer(referrer);
283 bool secure_referrer_but_insecure_destination =
284 original_referrer.SchemeIsSecure() &&
285 !redirect_destination.SchemeIsSecure();
286 bool same_origin =
287 original_referrer.GetOrigin() == redirect_destination.GetOrigin();
288 switch (policy) {
289 case URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE:
290 return secure_referrer_but_insecure_destination ? GURL()
291 : original_referrer;
293 case URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN:
294 if (same_origin) {
295 return original_referrer;
296 } else if (secure_referrer_but_insecure_destination) {
297 return GURL();
298 } else {
299 return original_referrer.GetOrigin();
302 case URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN:
303 return same_origin ? original_referrer : original_referrer.GetOrigin();
305 case URLRequest::NEVER_CLEAR_REFERRER:
306 return original_referrer;
309 NOTREACHED();
310 return GURL();
313 URLRequestJob::~URLRequestJob() {
314 base::PowerMonitor* power_monitor = base::PowerMonitor::Get();
315 if (power_monitor)
316 power_monitor->RemoveObserver(this);
319 void URLRequestJob::NotifyCertificateRequested(
320 SSLCertRequestInfo* cert_request_info) {
321 if (!request_)
322 return; // The request was destroyed, so there is no more work to do.
324 request_->NotifyCertificateRequested(cert_request_info);
327 void URLRequestJob::NotifySSLCertificateError(const SSLInfo& ssl_info,
328 bool fatal) {
329 if (!request_)
330 return; // The request was destroyed, so there is no more work to do.
332 request_->NotifySSLCertificateError(ssl_info, fatal);
335 bool URLRequestJob::CanGetCookies(const CookieList& cookie_list) const {
336 if (!request_)
337 return false; // The request was destroyed, so there is no more work to do.
339 return request_->CanGetCookies(cookie_list);
342 bool URLRequestJob::CanSetCookie(const std::string& cookie_line,
343 CookieOptions* options) const {
344 if (!request_)
345 return false; // The request was destroyed, so there is no more work to do.
347 return request_->CanSetCookie(cookie_line, options);
350 bool URLRequestJob::CanEnablePrivacyMode() const {
351 if (!request_)
352 return false; // The request was destroyed, so there is no more work to do.
354 return request_->CanEnablePrivacyMode();
357 void URLRequestJob::NotifyBeforeNetworkStart(bool* defer) {
358 if (!request_)
359 return;
361 request_->NotifyBeforeNetworkStart(defer);
364 void URLRequestJob::NotifyHeadersComplete() {
365 if (!request_ || !request_->has_delegate())
366 return; // The request was destroyed, so there is no more work to do.
368 if (has_handled_response_)
369 return;
371 DCHECK(!request_->status().is_io_pending());
373 // Initialize to the current time, and let the subclass optionally override
374 // the time stamps if it has that information. The default request_time is
375 // set by URLRequest before it calls our Start method.
376 request_->response_info_.response_time = base::Time::Now();
377 GetResponseInfo(&request_->response_info_);
379 // When notifying the delegate, the delegate can release the request
380 // (and thus release 'this'). After calling to the delgate, we must
381 // check the request pointer to see if it still exists, and return
382 // immediately if it has been destroyed. self_preservation ensures our
383 // survival until we can get out of this method.
384 scoped_refptr<URLRequestJob> self_preservation(this);
386 if (request_)
387 request_->OnHeadersComplete();
389 GURL new_location;
390 int http_status_code;
391 if (IsRedirectResponse(&new_location, &http_status_code)) {
392 // Redirect response bodies are not read. Notify the transaction
393 // so it does not treat being stopped as an error.
394 DoneReadingRedirectResponse();
396 RedirectInfo redirect_info =
397 ComputeRedirectInfo(new_location, http_status_code);
398 bool defer_redirect = false;
399 request_->NotifyReceivedRedirect(redirect_info, &defer_redirect);
401 // Ensure that the request wasn't detached or destroyed in
402 // NotifyReceivedRedirect
403 if (!request_ || !request_->has_delegate())
404 return;
406 // If we were not cancelled, then maybe follow the redirect.
407 if (request_->status().is_success()) {
408 if (defer_redirect) {
409 deferred_redirect_info_ = redirect_info;
410 } else {
411 FollowRedirect(redirect_info);
413 return;
415 } else if (NeedsAuth()) {
416 scoped_refptr<AuthChallengeInfo> auth_info;
417 GetAuthChallengeInfo(&auth_info);
419 // Need to check for a NULL auth_info because the server may have failed
420 // to send a challenge with the 401 response.
421 if (auth_info.get()) {
422 request_->NotifyAuthRequired(auth_info.get());
423 // Wait for SetAuth or CancelAuth to be called.
424 return;
428 has_handled_response_ = true;
429 if (request_->status().is_success())
430 filter_.reset(SetupFilter());
432 if (!filter_.get()) {
433 std::string content_length;
434 request_->GetResponseHeaderByName("content-length", &content_length);
435 if (!content_length.empty())
436 base::StringToInt64(content_length, &expected_content_size_);
437 } else {
438 request_->net_log().AddEvent(
439 NetLog::TYPE_URL_REQUEST_FILTERS_SET,
440 base::Bind(&FiltersSetCallback, base::Unretained(filter_.get())));
443 request_->NotifyResponseStarted();
446 void URLRequestJob::NotifyReadComplete(int bytes_read) {
447 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/475755 is fixed.
448 tracked_objects::ScopedTracker tracking_profile(
449 FROM_HERE_WITH_EXPLICIT_FUNCTION(
450 "475755 URLRequestJob::NotifyReadComplete"));
452 if (!request_ || !request_->has_delegate())
453 return; // The request was destroyed, so there is no more work to do.
455 // TODO(darin): Bug 1004233. Re-enable this test once all of the chrome
456 // unit_tests have been fixed to not trip this.
457 #if 0
458 DCHECK(!request_->status().is_io_pending());
459 #endif
460 // The headers should be complete before reads complete
461 DCHECK(has_handled_response_);
463 OnRawReadComplete(bytes_read);
465 // Don't notify if we had an error.
466 if (!request_->status().is_success())
467 return;
469 // When notifying the delegate, the delegate can release the request
470 // (and thus release 'this'). After calling to the delegate, we must
471 // check the request pointer to see if it still exists, and return
472 // immediately if it has been destroyed. self_preservation ensures our
473 // survival until we can get out of this method.
474 scoped_refptr<URLRequestJob> self_preservation(this);
476 if (filter_.get()) {
477 // Tell the filter that it has more data
478 FilteredDataRead(bytes_read);
480 // Filter the data.
481 int filter_bytes_read = 0;
482 if (ReadFilteredData(&filter_bytes_read)) {
483 if (!filter_bytes_read)
484 DoneReading();
485 request_->NotifyReadCompleted(filter_bytes_read);
487 } else {
488 request_->NotifyReadCompleted(bytes_read);
490 DVLOG(1) << __FUNCTION__ << "() "
491 << "\"" << (request_ ? request_->url().spec() : "???") << "\""
492 << " pre bytes read = " << bytes_read
493 << " pre total = " << prefilter_bytes_read_
494 << " post total = " << postfilter_bytes_read_;
497 void URLRequestJob::NotifyStartError(const URLRequestStatus &status) {
498 DCHECK(!has_handled_response_);
499 has_handled_response_ = true;
500 if (request_) {
501 // There may be relevant information in the response info even in the
502 // error case.
503 GetResponseInfo(&request_->response_info_);
505 request_->set_status(status);
506 request_->NotifyResponseStarted();
507 // We may have been deleted.
511 void URLRequestJob::NotifyDone(const URLRequestStatus &status) {
512 DCHECK(!done_) << "Job sending done notification twice";
513 if (done_)
514 return;
515 done_ = true;
517 // Unless there was an error, we should have at least tried to handle
518 // the response before getting here.
519 DCHECK(has_handled_response_ || !status.is_success());
521 // As with NotifyReadComplete, we need to take care to notice if we were
522 // destroyed during a delegate callback.
523 if (request_) {
524 request_->set_is_pending(false);
525 // With async IO, it's quite possible to have a few outstanding
526 // requests. We could receive a request to Cancel, followed shortly
527 // by a successful IO. For tracking the status(), once there is
528 // an error, we do not change the status back to success. To
529 // enforce this, only set the status if the job is so far
530 // successful.
531 if (request_->status().is_success()) {
532 if (status.status() == URLRequestStatus::FAILED) {
533 request_->net_log().AddEventWithNetErrorCode(NetLog::TYPE_FAILED,
534 status.error());
536 request_->set_status(status);
540 // Complete this notification later. This prevents us from re-entering the
541 // delegate if we're done because of a synchronous call.
542 base::MessageLoop::current()->PostTask(
543 FROM_HERE,
544 base::Bind(&URLRequestJob::CompleteNotifyDone,
545 weak_factory_.GetWeakPtr()));
548 void URLRequestJob::CompleteNotifyDone() {
549 // Check if we should notify the delegate that we're done because of an error.
550 if (request_ &&
551 !request_->status().is_success() &&
552 request_->has_delegate()) {
553 // We report the error differently depending on whether we've called
554 // OnResponseStarted yet.
555 if (has_handled_response_) {
556 // We signal the error by calling OnReadComplete with a bytes_read of -1.
557 request_->NotifyReadCompleted(-1);
558 } else {
559 has_handled_response_ = true;
560 request_->NotifyResponseStarted();
565 void URLRequestJob::NotifyCanceled() {
566 if (!done_) {
567 NotifyDone(URLRequestStatus(URLRequestStatus::CANCELED, ERR_ABORTED));
571 void URLRequestJob::NotifyRestartRequired() {
572 DCHECK(!has_handled_response_);
573 if (GetStatus().status() != URLRequestStatus::CANCELED)
574 request_->Restart();
577 void URLRequestJob::OnCallToDelegate() {
578 request_->OnCallToDelegate();
581 void URLRequestJob::OnCallToDelegateComplete() {
582 request_->OnCallToDelegateComplete();
585 bool URLRequestJob::ReadRawData(IOBuffer* buf, int buf_size,
586 int *bytes_read) {
587 DCHECK(bytes_read);
588 *bytes_read = 0;
589 return true;
592 void URLRequestJob::DoneReading() {
593 // Do nothing.
596 void URLRequestJob::DoneReadingRedirectResponse() {
599 void URLRequestJob::FilteredDataRead(int bytes_read) {
600 DCHECK(filter_);
601 filter_->FlushStreamBuffer(bytes_read);
604 bool URLRequestJob::ReadFilteredData(int* bytes_read) {
605 DCHECK(filter_);
606 DCHECK(filtered_read_buffer_.get());
607 DCHECK_GT(filtered_read_buffer_len_, 0);
608 DCHECK_LT(filtered_read_buffer_len_, 1000000); // Sanity check.
609 DCHECK(!raw_read_buffer_.get());
611 *bytes_read = 0;
612 bool rv = false;
614 for (;;) {
615 if (is_done())
616 return true;
618 if (!filter_needs_more_output_space_ && !filter_->stream_data_len()) {
619 // We don't have any raw data to work with, so read from the transaction.
620 int filtered_data_read;
621 if (ReadRawDataForFilter(&filtered_data_read)) {
622 if (filtered_data_read > 0) {
623 // Give data to filter.
624 filter_->FlushStreamBuffer(filtered_data_read);
625 } else {
626 return true; // EOF.
628 } else {
629 return false; // IO Pending (or error).
633 if ((filter_->stream_data_len() || filter_needs_more_output_space_) &&
634 !is_done()) {
635 // Get filtered data.
636 int filtered_data_len = filtered_read_buffer_len_;
637 int output_buffer_size = filtered_data_len;
638 Filter::FilterStatus status =
639 filter_->ReadData(filtered_read_buffer_->data(), &filtered_data_len);
641 if (filter_needs_more_output_space_ && !filtered_data_len) {
642 // filter_needs_more_output_space_ was mistaken... there are no more
643 // bytes and we should have at least tried to fill up the filter's input
644 // buffer. Correct the state, and try again.
645 filter_needs_more_output_space_ = false;
646 continue;
648 filter_needs_more_output_space_ =
649 (filtered_data_len == output_buffer_size);
651 switch (status) {
652 case Filter::FILTER_DONE: {
653 filter_needs_more_output_space_ = false;
654 *bytes_read = filtered_data_len;
655 postfilter_bytes_read_ += filtered_data_len;
656 rv = true;
657 break;
659 case Filter::FILTER_NEED_MORE_DATA: {
660 // We have finished filtering all data currently in the buffer.
661 // There might be some space left in the output buffer. One can
662 // consider reading more data from the stream to feed the filter
663 // and filling up the output buffer. This leads to more complicated
664 // buffer management and data notification mechanisms.
665 // We can revisit this issue if there is a real perf need.
666 if (filtered_data_len > 0) {
667 *bytes_read = filtered_data_len;
668 postfilter_bytes_read_ += filtered_data_len;
669 rv = true;
670 } else {
671 // Read again since we haven't received enough data yet (e.g., we
672 // may not have a complete gzip header yet).
673 continue;
675 break;
677 case Filter::FILTER_OK: {
678 *bytes_read = filtered_data_len;
679 postfilter_bytes_read_ += filtered_data_len;
680 rv = true;
681 break;
683 case Filter::FILTER_ERROR: {
684 DVLOG(1) << __FUNCTION__ << "() "
685 << "\"" << (request_ ? request_->url().spec() : "???")
686 << "\"" << " Filter Error";
687 filter_needs_more_output_space_ = false;
688 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED,
689 ERR_CONTENT_DECODING_FAILED));
690 rv = false;
691 break;
693 default: {
694 NOTREACHED();
695 filter_needs_more_output_space_ = false;
696 rv = false;
697 break;
701 // If logging all bytes is enabled, log the filtered bytes read.
702 if (rv && request() && request()->net_log().IsLoggingBytes() &&
703 filtered_data_len > 0) {
704 request()->net_log().AddByteTransferEvent(
705 NetLog::TYPE_URL_REQUEST_JOB_FILTERED_BYTES_READ,
706 filtered_data_len, filtered_read_buffer_->data());
708 } else {
709 // we are done, or there is no data left.
710 rv = true;
712 break;
715 if (rv) {
716 // When we successfully finished a read, we no longer need to save the
717 // caller's buffers. Release our reference.
718 filtered_read_buffer_ = NULL;
719 filtered_read_buffer_len_ = 0;
721 return rv;
724 void URLRequestJob::DestroyFilters() {
725 filter_.reset();
728 const URLRequestStatus URLRequestJob::GetStatus() {
729 if (request_)
730 return request_->status();
731 // If the request is gone, we must be cancelled.
732 return URLRequestStatus(URLRequestStatus::CANCELED,
733 ERR_ABORTED);
736 void URLRequestJob::SetStatus(const URLRequestStatus &status) {
737 if (request_)
738 request_->set_status(status);
741 void URLRequestJob::SetProxyServer(const HostPortPair& proxy_server) {
742 request_->proxy_server_ = proxy_server;
745 bool URLRequestJob::ReadRawDataForFilter(int* bytes_read) {
746 bool rv = false;
748 DCHECK(bytes_read);
749 DCHECK(filter_.get());
751 *bytes_read = 0;
753 // Get more pre-filtered data if needed.
754 // TODO(mbelshe): is it possible that the filter needs *MORE* data
755 // when there is some data already in the buffer?
756 if (!filter_->stream_data_len() && !is_done()) {
757 IOBuffer* stream_buffer = filter_->stream_buffer();
758 int stream_buffer_size = filter_->stream_buffer_size();
759 rv = ReadRawDataHelper(stream_buffer, stream_buffer_size, bytes_read);
761 return rv;
764 bool URLRequestJob::ReadRawDataHelper(IOBuffer* buf, int buf_size,
765 int* bytes_read) {
766 DCHECK(!request_->status().is_io_pending());
767 DCHECK(raw_read_buffer_.get() == NULL);
769 // Keep a pointer to the read buffer, so we have access to it in the
770 // OnRawReadComplete() callback in the event that the read completes
771 // asynchronously.
772 raw_read_buffer_ = buf;
773 bool rv = ReadRawData(buf, buf_size, bytes_read);
775 if (!request_->status().is_io_pending()) {
776 // If the read completes synchronously, either success or failure,
777 // invoke the OnRawReadComplete callback so we can account for the
778 // completed read.
779 OnRawReadComplete(*bytes_read);
781 return rv;
784 void URLRequestJob::FollowRedirect(const RedirectInfo& redirect_info) {
785 int rv = request_->Redirect(redirect_info);
786 if (rv != OK)
787 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, rv));
790 void URLRequestJob::OnRawReadComplete(int bytes_read) {
791 DCHECK(raw_read_buffer_.get());
792 // If |filter_| is non-NULL, bytes will be logged after it is applied instead.
793 if (!filter_.get() && request() && request()->net_log().IsLoggingBytes() &&
794 bytes_read > 0) {
795 request()->net_log().AddByteTransferEvent(
796 NetLog::TYPE_URL_REQUEST_JOB_BYTES_READ,
797 bytes_read, raw_read_buffer_->data());
800 if (bytes_read > 0) {
801 RecordBytesRead(bytes_read);
803 raw_read_buffer_ = NULL;
806 void URLRequestJob::RecordBytesRead(int bytes_read) {
807 filter_input_byte_count_ += bytes_read;
808 prefilter_bytes_read_ += bytes_read;
809 if (!filter_.get())
810 postfilter_bytes_read_ += bytes_read;
811 DVLOG(2) << __FUNCTION__ << "() "
812 << "\"" << (request_ ? request_->url().spec() : "???") << "\""
813 << " pre bytes read = " << bytes_read
814 << " pre total = " << prefilter_bytes_read_
815 << " post total = " << postfilter_bytes_read_;
816 UpdatePacketReadTimes(); // Facilitate stats recording if it is active.
817 if (network_delegate_)
818 network_delegate_->NotifyRawBytesRead(*request_, bytes_read);
821 bool URLRequestJob::FilterHasData() {
822 return filter_.get() && filter_->stream_data_len();
825 void URLRequestJob::UpdatePacketReadTimes() {
828 RedirectInfo URLRequestJob::ComputeRedirectInfo(const GURL& location,
829 int http_status_code) {
830 const GURL& url = request_->url();
832 RedirectInfo redirect_info;
834 redirect_info.status_code = http_status_code;
836 // The request method may change, depending on the status code.
837 redirect_info.new_method =
838 ComputeMethodForRedirect(request_->method(), http_status_code);
840 // Move the reference fragment of the old location to the new one if the
841 // new one has none. This duplicates mozilla's behavior.
842 if (url.is_valid() && url.has_ref() && !location.has_ref() &&
843 CopyFragmentOnRedirect(location)) {
844 GURL::Replacements replacements;
845 // Reference the |ref| directly out of the original URL to avoid a
846 // malloc.
847 replacements.SetRef(url.spec().data(),
848 url.parsed_for_possibly_invalid_spec().ref);
849 redirect_info.new_url = location.ReplaceComponents(replacements);
850 } else {
851 redirect_info.new_url = location;
854 // Update the first-party URL if appropriate.
855 if (request_->first_party_url_policy() ==
856 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT) {
857 redirect_info.new_first_party_for_cookies = redirect_info.new_url;
858 } else {
859 redirect_info.new_first_party_for_cookies =
860 request_->first_party_for_cookies();
863 // Alter the referrer if redirecting cross-origin (especially HTTP->HTTPS).
864 redirect_info.new_referrer =
865 ComputeReferrerForRedirect(request_->referrer_policy(),
866 request_->referrer(),
867 redirect_info.new_url).spec();
869 return redirect_info;
872 } // namespace net