Rename InputLatency::ScrollUpdate to Latency::ScrollUpdate
[chromium-blink-merge.git] / net / url_request / url_request_job.cc
blob106cb8567f392999caba20625bfa83a254d3710c
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 NetLogCaptureMode /* capture_mode */) {
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_needs_more_output_space_(false),
64 filtered_read_buffer_len_(0),
65 has_handled_response_(false),
66 expected_content_size_(-1),
67 network_delegate_(network_delegate),
68 weak_factory_(this) {
69 base::PowerMonitor* power_monitor = base::PowerMonitor::Get();
70 if (power_monitor)
71 power_monitor->AddObserver(this);
74 void URLRequestJob::SetUpload(UploadDataStream* upload) {
77 void URLRequestJob::SetExtraRequestHeaders(const HttpRequestHeaders& headers) {
80 void URLRequestJob::SetPriority(RequestPriority priority) {
83 void URLRequestJob::Kill() {
84 weak_factory_.InvalidateWeakPtrs();
85 // Make sure the request is notified that we are done. We assume that the
86 // request took care of setting its error status before calling Kill.
87 if (request_)
88 NotifyCanceled();
91 void URLRequestJob::DetachRequest() {
92 request_ = NULL;
95 // This function calls ReadData to get stream data. If a filter exists, passes
96 // the data to the attached filter. Then returns the output from filter back to
97 // the caller.
98 bool URLRequestJob::Read(IOBuffer* buf, int buf_size, int *bytes_read) {
99 bool rv = false;
101 DCHECK_LT(buf_size, 1000000); // Sanity check.
102 DCHECK(buf);
103 DCHECK(bytes_read);
104 DCHECK(filtered_read_buffer_.get() == NULL);
105 DCHECK_EQ(0, filtered_read_buffer_len_);
107 *bytes_read = 0;
109 // Skip Filter if not present.
110 if (!filter_.get()) {
111 rv = ReadRawDataHelper(buf, buf_size, bytes_read);
112 } else {
113 // Save the caller's buffers while we do IO
114 // in the filter's buffers.
115 filtered_read_buffer_ = buf;
116 filtered_read_buffer_len_ = buf_size;
118 if (ReadFilteredData(bytes_read)) {
119 rv = true; // We have data to return.
121 // It is fine to call DoneReading even if ReadFilteredData receives 0
122 // bytes from the net, but we avoid making that call if we know for
123 // sure that's the case (ReadRawDataHelper path).
124 if (*bytes_read == 0)
125 DoneReading();
126 } else {
127 rv = false; // Error, or a new IO is pending.
131 if (rv && *bytes_read == 0)
132 NotifyDone(URLRequestStatus());
133 return rv;
136 void URLRequestJob::StopCaching() {
137 // Nothing to do here.
140 bool URLRequestJob::GetFullRequestHeaders(HttpRequestHeaders* headers) const {
141 // Most job types don't send request headers.
142 return false;
145 int64 URLRequestJob::GetTotalReceivedBytes() const {
146 return 0;
149 LoadState URLRequestJob::GetLoadState() const {
150 return LOAD_STATE_IDLE;
153 UploadProgress URLRequestJob::GetUploadProgress() const {
154 return UploadProgress();
157 bool URLRequestJob::GetCharset(std::string* charset) {
158 return false;
161 void URLRequestJob::GetResponseInfo(HttpResponseInfo* info) {
164 void URLRequestJob::GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const {
165 // Only certain request types return more than just request start times.
168 bool URLRequestJob::GetResponseCookies(std::vector<std::string>* cookies) {
169 return false;
172 Filter* URLRequestJob::SetupFilter() const {
173 return NULL;
176 bool URLRequestJob::IsRedirectResponse(GURL* location,
177 int* http_status_code) {
178 // For non-HTTP jobs, headers will be null.
179 HttpResponseHeaders* headers = request_->response_headers();
180 if (!headers)
181 return false;
183 std::string value;
184 if (!headers->IsRedirect(&value))
185 return false;
187 *location = request_->url().Resolve(value);
188 *http_status_code = headers->response_code();
189 return true;
192 bool URLRequestJob::CopyFragmentOnRedirect(const GURL& location) const {
193 return true;
196 bool URLRequestJob::IsSafeRedirect(const GURL& location) {
197 return true;
200 bool URLRequestJob::NeedsAuth() {
201 return false;
204 void URLRequestJob::GetAuthChallengeInfo(
205 scoped_refptr<AuthChallengeInfo>* auth_info) {
206 // This will only be called if NeedsAuth() returns true, in which
207 // case the derived class should implement this!
208 NOTREACHED();
211 void URLRequestJob::SetAuth(const AuthCredentials& credentials) {
212 // This will only be called if NeedsAuth() returns true, in which
213 // case the derived class should implement this!
214 NOTREACHED();
217 void URLRequestJob::CancelAuth() {
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::ContinueWithCertificate(
224 X509Certificate* client_cert) {
225 // The derived class should implement this!
226 NOTREACHED();
229 void URLRequestJob::ContinueDespiteLastError() {
230 // Implementations should know how to recover from errors they generate.
231 // If this code was reached, we are trying to recover from an error that
232 // we don't know how to recover from.
233 NOTREACHED();
236 void URLRequestJob::FollowDeferredRedirect() {
237 DCHECK_NE(-1, deferred_redirect_info_.status_code);
239 // NOTE: deferred_redirect_info_ may be invalid, and attempting to follow it
240 // will fail inside FollowRedirect. The DCHECK above asserts that we called
241 // OnReceivedRedirect.
243 // It is also possible that FollowRedirect will drop the last reference to
244 // this job, so we need to reset our members before calling it.
246 RedirectInfo redirect_info = deferred_redirect_info_;
247 deferred_redirect_info_ = RedirectInfo();
248 FollowRedirect(redirect_info);
251 void URLRequestJob::ResumeNetworkStart() {
252 // This should only be called for HTTP Jobs, and implemented in the derived
253 // class.
254 NOTREACHED();
257 bool URLRequestJob::GetMimeType(std::string* mime_type) const {
258 return false;
261 int URLRequestJob::GetResponseCode() const {
262 return -1;
265 HostPortPair URLRequestJob::GetSocketAddress() const {
266 return HostPortPair();
269 void URLRequestJob::OnSuspend() {
270 Kill();
273 void URLRequestJob::NotifyURLRequestDestroyed() {
276 // static
277 GURL URLRequestJob::ComputeReferrerForRedirect(
278 URLRequest::ReferrerPolicy policy,
279 const std::string& referrer,
280 const GURL& redirect_destination) {
281 GURL original_referrer(referrer);
282 bool secure_referrer_but_insecure_destination =
283 original_referrer.SchemeIsSecure() &&
284 !redirect_destination.SchemeIsSecure();
285 bool same_origin =
286 original_referrer.GetOrigin() == redirect_destination.GetOrigin();
287 switch (policy) {
288 case URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE:
289 return secure_referrer_but_insecure_destination ? GURL()
290 : original_referrer;
292 case URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN:
293 if (same_origin) {
294 return original_referrer;
295 } else if (secure_referrer_but_insecure_destination) {
296 return GURL();
297 } else {
298 return original_referrer.GetOrigin();
301 case URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN:
302 return same_origin ? original_referrer : original_referrer.GetOrigin();
304 case URLRequest::NEVER_CLEAR_REFERRER:
305 return original_referrer;
308 NOTREACHED();
309 return GURL();
312 URLRequestJob::~URLRequestJob() {
313 base::PowerMonitor* power_monitor = base::PowerMonitor::Get();
314 if (power_monitor)
315 power_monitor->RemoveObserver(this);
318 void URLRequestJob::NotifyCertificateRequested(
319 SSLCertRequestInfo* cert_request_info) {
320 if (!request_)
321 return; // The request was destroyed, so there is no more work to do.
323 request_->NotifyCertificateRequested(cert_request_info);
326 void URLRequestJob::NotifySSLCertificateError(const SSLInfo& ssl_info,
327 bool fatal) {
328 if (!request_)
329 return; // The request was destroyed, so there is no more work to do.
331 request_->NotifySSLCertificateError(ssl_info, fatal);
334 bool URLRequestJob::CanGetCookies(const CookieList& cookie_list) const {
335 if (!request_)
336 return false; // The request was destroyed, so there is no more work to do.
338 return request_->CanGetCookies(cookie_list);
341 bool URLRequestJob::CanSetCookie(const std::string& cookie_line,
342 CookieOptions* options) const {
343 if (!request_)
344 return false; // The request was destroyed, so there is no more work to do.
346 return request_->CanSetCookie(cookie_line, options);
349 bool URLRequestJob::CanEnablePrivacyMode() const {
350 if (!request_)
351 return false; // The request was destroyed, so there is no more work to do.
353 return request_->CanEnablePrivacyMode();
356 void URLRequestJob::NotifyBeforeNetworkStart(bool* defer) {
357 if (!request_)
358 return;
360 request_->NotifyBeforeNetworkStart(defer);
363 void URLRequestJob::NotifyHeadersComplete() {
364 if (!request_ || !request_->has_delegate())
365 return; // The request was destroyed, so there is no more work to do.
367 if (has_handled_response_)
368 return;
370 DCHECK(!request_->status().is_io_pending());
372 // Initialize to the current time, and let the subclass optionally override
373 // the time stamps if it has that information. The default request_time is
374 // set by URLRequest before it calls our Start method.
375 request_->response_info_.response_time = base::Time::Now();
376 GetResponseInfo(&request_->response_info_);
378 // When notifying the delegate, the delegate can release the request
379 // (and thus release 'this'). After calling to the delgate, we must
380 // check the request pointer to see if it still exists, and return
381 // immediately if it has been destroyed. self_preservation ensures our
382 // survival until we can get out of this method.
383 scoped_refptr<URLRequestJob> self_preservation(this);
385 if (request_)
386 request_->OnHeadersComplete();
388 GURL new_location;
389 int http_status_code;
390 if (IsRedirectResponse(&new_location, &http_status_code)) {
391 // Redirect response bodies are not read. Notify the transaction
392 // so it does not treat being stopped as an error.
393 DoneReadingRedirectResponse();
395 RedirectInfo redirect_info =
396 ComputeRedirectInfo(new_location, http_status_code);
397 bool defer_redirect = false;
398 request_->NotifyReceivedRedirect(redirect_info, &defer_redirect);
400 // Ensure that the request wasn't detached or destroyed in
401 // NotifyReceivedRedirect
402 if (!request_ || !request_->has_delegate())
403 return;
405 // If we were not cancelled, then maybe follow the redirect.
406 if (request_->status().is_success()) {
407 if (defer_redirect) {
408 deferred_redirect_info_ = redirect_info;
409 } else {
410 FollowRedirect(redirect_info);
412 return;
414 } else if (NeedsAuth()) {
415 scoped_refptr<AuthChallengeInfo> auth_info;
416 GetAuthChallengeInfo(&auth_info);
418 // Need to check for a NULL auth_info because the server may have failed
419 // to send a challenge with the 401 response.
420 if (auth_info.get()) {
421 request_->NotifyAuthRequired(auth_info.get());
422 // Wait for SetAuth or CancelAuth to be called.
423 return;
427 has_handled_response_ = true;
428 if (request_->status().is_success())
429 filter_.reset(SetupFilter());
431 if (!filter_.get()) {
432 std::string content_length;
433 request_->GetResponseHeaderByName("content-length", &content_length);
434 if (!content_length.empty())
435 base::StringToInt64(content_length, &expected_content_size_);
436 } else {
437 request_->net_log().AddEvent(
438 NetLog::TYPE_URL_REQUEST_FILTERS_SET,
439 base::Bind(&FiltersSetCallback, base::Unretained(filter_.get())));
442 request_->NotifyResponseStarted();
445 void URLRequestJob::NotifyReadComplete(int bytes_read) {
446 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/475755 is fixed.
447 tracked_objects::ScopedTracker tracking_profile(
448 FROM_HERE_WITH_EXPLICIT_FUNCTION(
449 "475755 URLRequestJob::NotifyReadComplete"));
451 if (!request_ || !request_->has_delegate())
452 return; // The request was destroyed, so there is no more work to do.
454 // TODO(darin): Bug 1004233. Re-enable this test once all of the chrome
455 // unit_tests have been fixed to not trip this.
456 #if 0
457 DCHECK(!request_->status().is_io_pending());
458 #endif
459 // The headers should be complete before reads complete
460 DCHECK(has_handled_response_);
462 OnRawReadComplete(bytes_read);
464 // Don't notify if we had an error.
465 if (!request_->status().is_success())
466 return;
468 // When notifying the delegate, the delegate can release the request
469 // (and thus release 'this'). After calling to the delegate, we must
470 // check the request pointer to see if it still exists, and return
471 // immediately if it has been destroyed. self_preservation ensures our
472 // survival until we can get out of this method.
473 scoped_refptr<URLRequestJob> self_preservation(this);
475 if (filter_.get()) {
476 // Tell the filter that it has more data
477 FilteredDataRead(bytes_read);
479 // Filter the data.
480 int filter_bytes_read = 0;
481 if (ReadFilteredData(&filter_bytes_read)) {
482 if (!filter_bytes_read)
483 DoneReading();
484 request_->NotifyReadCompleted(filter_bytes_read);
486 } else {
487 request_->NotifyReadCompleted(bytes_read);
489 DVLOG(1) << __FUNCTION__ << "() "
490 << "\"" << (request_ ? request_->url().spec() : "???") << "\""
491 << " pre bytes read = " << bytes_read
492 << " pre total = " << prefilter_bytes_read_
493 << " post total = " << postfilter_bytes_read_;
496 void URLRequestJob::NotifyStartError(const URLRequestStatus &status) {
497 DCHECK(!has_handled_response_);
498 has_handled_response_ = true;
499 if (request_) {
500 // There may be relevant information in the response info even in the
501 // error case.
502 GetResponseInfo(&request_->response_info_);
504 request_->set_status(status);
505 request_->NotifyResponseStarted();
506 // We may have been deleted.
510 void URLRequestJob::NotifyDone(const URLRequestStatus &status) {
511 DCHECK(!done_) << "Job sending done notification twice";
512 if (done_)
513 return;
514 done_ = true;
516 // Unless there was an error, we should have at least tried to handle
517 // the response before getting here.
518 DCHECK(has_handled_response_ || !status.is_success());
520 // As with NotifyReadComplete, we need to take care to notice if we were
521 // destroyed during a delegate callback.
522 if (request_) {
523 request_->set_is_pending(false);
524 // With async IO, it's quite possible to have a few outstanding
525 // requests. We could receive a request to Cancel, followed shortly
526 // by a successful IO. For tracking the status(), once there is
527 // an error, we do not change the status back to success. To
528 // enforce this, only set the status if the job is so far
529 // successful.
530 if (request_->status().is_success()) {
531 if (status.status() == URLRequestStatus::FAILED) {
532 request_->net_log().AddEventWithNetErrorCode(NetLog::TYPE_FAILED,
533 status.error());
535 request_->set_status(status);
539 // Complete this notification later. This prevents us from re-entering the
540 // delegate if we're done because of a synchronous call.
541 base::MessageLoop::current()->PostTask(
542 FROM_HERE,
543 base::Bind(&URLRequestJob::CompleteNotifyDone,
544 weak_factory_.GetWeakPtr()));
547 void URLRequestJob::CompleteNotifyDone() {
548 // Check if we should notify the delegate that we're done because of an error.
549 if (request_ &&
550 !request_->status().is_success() &&
551 request_->has_delegate()) {
552 // We report the error differently depending on whether we've called
553 // OnResponseStarted yet.
554 if (has_handled_response_) {
555 // We signal the error by calling OnReadComplete with a bytes_read of -1.
556 request_->NotifyReadCompleted(-1);
557 } else {
558 has_handled_response_ = true;
559 request_->NotifyResponseStarted();
564 void URLRequestJob::NotifyCanceled() {
565 if (!done_) {
566 NotifyDone(URLRequestStatus(URLRequestStatus::CANCELED, ERR_ABORTED));
570 void URLRequestJob::NotifyRestartRequired() {
571 DCHECK(!has_handled_response_);
572 if (GetStatus().status() != URLRequestStatus::CANCELED)
573 request_->Restart();
576 void URLRequestJob::OnCallToDelegate() {
577 request_->OnCallToDelegate();
580 void URLRequestJob::OnCallToDelegateComplete() {
581 request_->OnCallToDelegateComplete();
584 bool URLRequestJob::ReadRawData(IOBuffer* buf, int buf_size,
585 int *bytes_read) {
586 DCHECK(bytes_read);
587 *bytes_read = 0;
588 return true;
591 void URLRequestJob::DoneReading() {
592 // Do nothing.
595 void URLRequestJob::DoneReadingRedirectResponse() {
598 void URLRequestJob::FilteredDataRead(int bytes_read) {
599 DCHECK(filter_);
600 filter_->FlushStreamBuffer(bytes_read);
603 bool URLRequestJob::ReadFilteredData(int* bytes_read) {
604 DCHECK(filter_);
605 DCHECK(filtered_read_buffer_.get());
606 DCHECK_GT(filtered_read_buffer_len_, 0);
607 DCHECK_LT(filtered_read_buffer_len_, 1000000); // Sanity check.
608 DCHECK(!raw_read_buffer_.get());
610 *bytes_read = 0;
611 bool rv = false;
613 for (;;) {
614 if (is_done())
615 return true;
617 if (!filter_needs_more_output_space_ && !filter_->stream_data_len()) {
618 // We don't have any raw data to work with, so read from the transaction.
619 int filtered_data_read;
620 if (ReadRawDataForFilter(&filtered_data_read)) {
621 if (filtered_data_read > 0) {
622 // Give data to filter.
623 filter_->FlushStreamBuffer(filtered_data_read);
624 } else {
625 return true; // EOF.
627 } else {
628 return false; // IO Pending (or error).
632 if ((filter_->stream_data_len() || filter_needs_more_output_space_) &&
633 !is_done()) {
634 // Get filtered data.
635 int filtered_data_len = filtered_read_buffer_len_;
636 int output_buffer_size = filtered_data_len;
637 Filter::FilterStatus status =
638 filter_->ReadData(filtered_read_buffer_->data(), &filtered_data_len);
640 if (filter_needs_more_output_space_ && !filtered_data_len) {
641 // filter_needs_more_output_space_ was mistaken... there are no more
642 // bytes and we should have at least tried to fill up the filter's input
643 // buffer. Correct the state, and try again.
644 filter_needs_more_output_space_ = false;
645 continue;
647 filter_needs_more_output_space_ =
648 (filtered_data_len == output_buffer_size);
650 switch (status) {
651 case Filter::FILTER_DONE: {
652 filter_needs_more_output_space_ = false;
653 *bytes_read = filtered_data_len;
654 postfilter_bytes_read_ += filtered_data_len;
655 rv = true;
656 break;
658 case Filter::FILTER_NEED_MORE_DATA: {
659 // We have finished filtering all data currently in the buffer.
660 // There might be some space left in the output buffer. One can
661 // consider reading more data from the stream to feed the filter
662 // and filling up the output buffer. This leads to more complicated
663 // buffer management and data notification mechanisms.
664 // We can revisit this issue if there is a real perf need.
665 if (filtered_data_len > 0) {
666 *bytes_read = filtered_data_len;
667 postfilter_bytes_read_ += filtered_data_len;
668 rv = true;
669 } else {
670 // Read again since we haven't received enough data yet (e.g., we
671 // may not have a complete gzip header yet).
672 continue;
674 break;
676 case Filter::FILTER_OK: {
677 *bytes_read = filtered_data_len;
678 postfilter_bytes_read_ += filtered_data_len;
679 rv = true;
680 break;
682 case Filter::FILTER_ERROR: {
683 DVLOG(1) << __FUNCTION__ << "() "
684 << "\"" << (request_ ? request_->url().spec() : "???")
685 << "\"" << " Filter Error";
686 filter_needs_more_output_space_ = false;
687 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED,
688 ERR_CONTENT_DECODING_FAILED));
689 rv = false;
690 break;
692 default: {
693 NOTREACHED();
694 filter_needs_more_output_space_ = false;
695 rv = false;
696 break;
700 // If logging all bytes is enabled, log the filtered bytes read.
701 if (rv && request() &&
702 request()->net_log().GetCaptureMode().include_socket_bytes() &&
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() &&
794 request()->net_log().GetCaptureMode().include_socket_bytes() &&
795 bytes_read > 0) {
796 request()->net_log().AddByteTransferEvent(
797 NetLog::TYPE_URL_REQUEST_JOB_BYTES_READ,
798 bytes_read, raw_read_buffer_->data());
801 if (bytes_read > 0) {
802 RecordBytesRead(bytes_read);
804 raw_read_buffer_ = NULL;
807 void URLRequestJob::RecordBytesRead(int 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