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/strings/string_number_conversions.h"
12 #include "base/strings/string_util.h"
13 #include "net/base/auth.h"
14 #include "net/base/host_port_pair.h"
15 #include "net/base/io_buffer.h"
16 #include "net/base/load_states.h"
17 #include "net/base/net_errors.h"
18 #include "net/base/network_delegate.h"
19 #include "net/http/http_response_headers.h"
20 #include "net/url_request/url_request.h"
24 URLRequestJob::URLRequestJob(URLRequest* request,
25 NetworkDelegate* network_delegate)
28 prefilter_bytes_read_(0),
29 postfilter_bytes_read_(0),
30 filter_input_byte_count_(0),
31 filter_needs_more_output_space_(false),
32 filtered_read_buffer_len_(0),
33 has_handled_response_(false),
34 expected_content_size_(-1),
35 deferred_redirect_status_code_(-1),
36 network_delegate_(network_delegate),
38 base::PowerMonitor* power_monitor = base::PowerMonitor::Get();
40 power_monitor->AddObserver(this);
43 void URLRequestJob::SetUpload(UploadDataStream* upload) {
46 void URLRequestJob::SetExtraRequestHeaders(const HttpRequestHeaders& headers) {
49 void URLRequestJob::SetPriority(RequestPriority priority) {
52 void URLRequestJob::Kill() {
53 weak_factory_.InvalidateWeakPtrs();
54 // Make sure the request is notified that we are done. We assume that the
55 // request took care of setting its error status before calling Kill.
60 void URLRequestJob::DetachRequest() {
65 // This function calls ReadData to get stream data. If a filter exists, passes
66 // the data to the attached filter. Then returns the output from filter back to
68 bool URLRequestJob::Read(IOBuffer* buf, int buf_size, int *bytes_read) {
71 DCHECK_LT(buf_size, 1000000); // Sanity check.
74 DCHECK(filtered_read_buffer_.get() == NULL);
75 DCHECK_EQ(0, filtered_read_buffer_len_);
79 // Skip Filter if not present.
81 rv = ReadRawDataHelper(buf, buf_size, bytes_read);
83 // Save the caller's buffers while we do IO
84 // in the filter's buffers.
85 filtered_read_buffer_ = buf;
86 filtered_read_buffer_len_ = buf_size;
88 if (ReadFilteredData(bytes_read)) {
89 rv = true; // We have data to return.
91 // It is fine to call DoneReading even if ReadFilteredData receives 0
92 // bytes from the net, but we avoid making that call if we know for
93 // sure that's the case (ReadRawDataHelper path).
97 rv = false; // Error, or a new IO is pending.
100 if (rv && *bytes_read == 0)
101 NotifyDone(URLRequestStatus());
105 void URLRequestJob::StopCaching() {
106 // Nothing to do here.
109 bool URLRequestJob::GetFullRequestHeaders(HttpRequestHeaders* headers) const {
110 // Most job types don't send request headers.
114 LoadState URLRequestJob::GetLoadState() const {
115 return LOAD_STATE_IDLE;
118 UploadProgress URLRequestJob::GetUploadProgress() const {
119 return UploadProgress();
122 bool URLRequestJob::GetCharset(std::string* charset) {
126 void URLRequestJob::GetResponseInfo(HttpResponseInfo* info) {
129 void URLRequestJob::GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const {
130 // Only certain request types return more than just request start times.
133 bool URLRequestJob::GetResponseCookies(std::vector<std::string>* cookies) {
137 Filter* URLRequestJob::SetupFilter() const {
141 bool URLRequestJob::IsRedirectResponse(GURL* location,
142 int* http_status_code) {
143 // For non-HTTP jobs, headers will be null.
144 HttpResponseHeaders* headers = request_->response_headers();
149 if (!headers->IsRedirect(&value))
152 *location = request_->url().Resolve(value);
153 *http_status_code = headers->response_code();
157 bool URLRequestJob::IsSafeRedirect(const GURL& location) {
161 bool URLRequestJob::NeedsAuth() {
165 void URLRequestJob::GetAuthChallengeInfo(
166 scoped_refptr<AuthChallengeInfo>* auth_info) {
167 // This will only be called if NeedsAuth() returns true, in which
168 // case the derived class should implement this!
172 void URLRequestJob::SetAuth(const AuthCredentials& credentials) {
173 // This will only be called if NeedsAuth() returns true, in which
174 // case the derived class should implement this!
178 void URLRequestJob::CancelAuth() {
179 // This will only be called if NeedsAuth() returns true, in which
180 // case the derived class should implement this!
184 void URLRequestJob::ContinueWithCertificate(
185 X509Certificate* client_cert) {
186 // The derived class should implement this!
190 void URLRequestJob::ContinueDespiteLastError() {
191 // Implementations should know how to recover from errors they generate.
192 // If this code was reached, we are trying to recover from an error that
193 // we don't know how to recover from.
197 void URLRequestJob::FollowDeferredRedirect() {
198 DCHECK(deferred_redirect_status_code_ != -1);
200 // NOTE: deferred_redirect_url_ may be invalid, and attempting to redirect to
201 // such an URL will fail inside FollowRedirect. The DCHECK above asserts
202 // that we called OnReceivedRedirect.
204 // It is also possible that FollowRedirect will drop the last reference to
205 // this job, so we need to reset our members before calling it.
207 GURL redirect_url = deferred_redirect_url_;
208 int redirect_status_code = deferred_redirect_status_code_;
210 deferred_redirect_url_ = GURL();
211 deferred_redirect_status_code_ = -1;
213 FollowRedirect(redirect_url, redirect_status_code);
216 bool URLRequestJob::GetMimeType(std::string* mime_type) const {
220 int URLRequestJob::GetResponseCode() const {
224 HostPortPair URLRequestJob::GetSocketAddress() const {
225 return HostPortPair();
228 void URLRequestJob::OnSuspend() {
232 void URLRequestJob::NotifyURLRequestDestroyed() {
235 URLRequestJob::~URLRequestJob() {
236 base::PowerMonitor* power_monitor = base::PowerMonitor::Get();
238 power_monitor->RemoveObserver(this);
241 void URLRequestJob::NotifyCertificateRequested(
242 SSLCertRequestInfo* cert_request_info) {
244 return; // The request was destroyed, so there is no more work to do.
246 request_->NotifyCertificateRequested(cert_request_info);
249 void URLRequestJob::NotifySSLCertificateError(const SSLInfo& ssl_info,
252 return; // The request was destroyed, so there is no more work to do.
254 request_->NotifySSLCertificateError(ssl_info, fatal);
257 bool URLRequestJob::CanGetCookies(const CookieList& cookie_list) const {
259 return false; // The request was destroyed, so there is no more work to do.
261 return request_->CanGetCookies(cookie_list);
264 bool URLRequestJob::CanSetCookie(const std::string& cookie_line,
265 CookieOptions* options) const {
267 return false; // The request was destroyed, so there is no more work to do.
269 return request_->CanSetCookie(cookie_line, options);
272 bool URLRequestJob::CanEnablePrivacyMode() const {
274 return false; // The request was destroyed, so there is no more work to do.
276 return request_->CanEnablePrivacyMode();
279 void URLRequestJob::NotifyHeadersComplete() {
280 if (!request_ || !request_->has_delegate())
281 return; // The request was destroyed, so there is no more work to do.
283 if (has_handled_response_)
286 DCHECK(!request_->status().is_io_pending());
288 // Initialize to the current time, and let the subclass optionally override
289 // the time stamps if it has that information. The default request_time is
290 // set by URLRequest before it calls our Start method.
291 request_->response_info_.response_time = base::Time::Now();
292 GetResponseInfo(&request_->response_info_);
294 // When notifying the delegate, the delegate can release the request
295 // (and thus release 'this'). After calling to the delgate, we must
296 // check the request pointer to see if it still exists, and return
297 // immediately if it has been destroyed. self_preservation ensures our
298 // survival until we can get out of this method.
299 scoped_refptr<URLRequestJob> self_preservation(this);
302 request_->OnHeadersComplete();
305 int http_status_code;
306 if (IsRedirectResponse(&new_location, &http_status_code)) {
307 const GURL& url = request_->url();
309 // Move the reference fragment of the old location to the new one if the
310 // new one has none. This duplicates mozilla's behavior.
311 if (url.is_valid() && url.has_ref() && !new_location.has_ref()) {
312 GURL::Replacements replacements;
313 // Reference the |ref| directly out of the original URL to avoid a
315 replacements.SetRef(url.spec().data(),
316 url.parsed_for_possibly_invalid_spec().ref);
317 new_location = new_location.ReplaceComponents(replacements);
320 // Redirect response bodies are not read. Notify the transaction
321 // so it does not treat being stopped as an error.
324 bool defer_redirect = false;
325 request_->NotifyReceivedRedirect(new_location, &defer_redirect);
327 // Ensure that the request wasn't detached or destroyed in
328 // NotifyReceivedRedirect
329 if (!request_ || !request_->has_delegate())
332 // If we were not cancelled, then maybe follow the redirect.
333 if (request_->status().is_success()) {
334 if (defer_redirect) {
335 deferred_redirect_url_ = new_location;
336 deferred_redirect_status_code_ = http_status_code;
338 FollowRedirect(new_location, http_status_code);
342 } else if (NeedsAuth()) {
343 scoped_refptr<AuthChallengeInfo> auth_info;
344 GetAuthChallengeInfo(&auth_info);
345 // Need to check for a NULL auth_info because the server may have failed
346 // to send a challenge with the 401 response.
347 if (auth_info.get()) {
348 request_->NotifyAuthRequired(auth_info.get());
349 // Wait for SetAuth or CancelAuth to be called.
354 has_handled_response_ = true;
355 if (request_->status().is_success())
356 filter_.reset(SetupFilter());
358 if (!filter_.get()) {
359 std::string content_length;
360 request_->GetResponseHeaderByName("content-length", &content_length);
361 if (!content_length.empty())
362 base::StringToInt64(content_length, &expected_content_size_);
365 request_->NotifyResponseStarted();
368 void URLRequestJob::NotifyReadComplete(int bytes_read) {
369 if (!request_ || !request_->has_delegate())
370 return; // The request was destroyed, so there is no more work to do.
372 // TODO(darin): Bug 1004233. Re-enable this test once all of the chrome
373 // unit_tests have been fixed to not trip this.
374 //DCHECK(!request_->status().is_io_pending());
376 // The headers should be complete before reads complete
377 DCHECK(has_handled_response_);
379 OnRawReadComplete(bytes_read);
381 // Don't notify if we had an error.
382 if (!request_->status().is_success())
385 // When notifying the delegate, the delegate can release the request
386 // (and thus release 'this'). After calling to the delegate, we must
387 // check the request pointer to see if it still exists, and return
388 // immediately if it has been destroyed. self_preservation ensures our
389 // survival until we can get out of this method.
390 scoped_refptr<URLRequestJob> self_preservation(this);
393 // Tell the filter that it has more data
394 FilteredDataRead(bytes_read);
397 int filter_bytes_read = 0;
398 if (ReadFilteredData(&filter_bytes_read)) {
399 if (!filter_bytes_read)
401 request_->NotifyReadCompleted(filter_bytes_read);
404 request_->NotifyReadCompleted(bytes_read);
406 DVLOG(1) << __FUNCTION__ << "() "
407 << "\"" << (request_ ? request_->url().spec() : "???") << "\""
408 << " pre bytes read = " << bytes_read
409 << " pre total = " << prefilter_bytes_read_
410 << " post total = " << postfilter_bytes_read_;
413 void URLRequestJob::NotifyStartError(const URLRequestStatus &status) {
414 DCHECK(!has_handled_response_);
415 has_handled_response_ = true;
417 request_->set_status(status);
418 request_->NotifyResponseStarted();
422 void URLRequestJob::NotifyDone(const URLRequestStatus &status) {
423 DCHECK(!done_) << "Job sending done notification twice";
428 // Unless there was an error, we should have at least tried to handle
429 // the response before getting here.
430 DCHECK(has_handled_response_ || !status.is_success());
432 // As with NotifyReadComplete, we need to take care to notice if we were
433 // destroyed during a delegate callback.
435 request_->set_is_pending(false);
436 // With async IO, it's quite possible to have a few outstanding
437 // requests. We could receive a request to Cancel, followed shortly
438 // by a successful IO. For tracking the status(), once there is
439 // an error, we do not change the status back to success. To
440 // enforce this, only set the status if the job is so far
442 if (request_->status().is_success()) {
443 if (status.status() == URLRequestStatus::FAILED) {
444 request_->net_log().AddEventWithNetErrorCode(NetLog::TYPE_FAILED,
447 request_->set_status(status);
451 // Complete this notification later. This prevents us from re-entering the
452 // delegate if we're done because of a synchronous call.
453 base::MessageLoop::current()->PostTask(
455 base::Bind(&URLRequestJob::CompleteNotifyDone,
456 weak_factory_.GetWeakPtr()));
459 void URLRequestJob::CompleteNotifyDone() {
460 // Check if we should notify the delegate that we're done because of an error.
462 !request_->status().is_success() &&
463 request_->has_delegate()) {
464 // We report the error differently depending on whether we've called
465 // OnResponseStarted yet.
466 if (has_handled_response_) {
467 // We signal the error by calling OnReadComplete with a bytes_read of -1.
468 request_->NotifyReadCompleted(-1);
470 has_handled_response_ = true;
471 request_->NotifyResponseStarted();
476 void URLRequestJob::NotifyCanceled() {
478 NotifyDone(URLRequestStatus(URLRequestStatus::CANCELED, ERR_ABORTED));
482 void URLRequestJob::NotifyRestartRequired() {
483 DCHECK(!has_handled_response_);
484 if (GetStatus().status() != URLRequestStatus::CANCELED)
488 void URLRequestJob::OnCallToDelegate() {
489 request_->OnCallToDelegate();
492 void URLRequestJob::OnCallToDelegateComplete() {
493 request_->OnCallToDelegateComplete();
496 bool URLRequestJob::ReadRawData(IOBuffer* buf, int buf_size,
503 void URLRequestJob::DoneReading() {
507 void URLRequestJob::FilteredDataRead(int bytes_read) {
508 DCHECK(filter_.get()); // don't add data if there is no filter
509 filter_->FlushStreamBuffer(bytes_read);
512 bool URLRequestJob::ReadFilteredData(int* bytes_read) {
513 DCHECK(filter_.get()); // don't add data if there is no filter
514 DCHECK(filtered_read_buffer_.get() !=
515 NULL); // we need to have a buffer to fill
516 DCHECK_GT(filtered_read_buffer_len_, 0); // sanity check
517 DCHECK_LT(filtered_read_buffer_len_, 1000000); // sanity check
518 DCHECK(raw_read_buffer_.get() ==
519 NULL); // there should be no raw read buffer yet
527 if (!filter_needs_more_output_space_ && !filter_->stream_data_len()) {
528 // We don't have any raw data to work with, so
529 // read from the socket.
530 int filtered_data_read;
531 if (ReadRawDataForFilter(&filtered_data_read)) {
532 if (filtered_data_read > 0) {
533 filter_->FlushStreamBuffer(filtered_data_read); // Give data to filter.
538 return false; // IO Pending (or error)
542 if ((filter_->stream_data_len() || filter_needs_more_output_space_)
544 // Get filtered data.
545 int filtered_data_len = filtered_read_buffer_len_;
546 Filter::FilterStatus status;
547 int output_buffer_size = filtered_data_len;
548 status = filter_->ReadData(filtered_read_buffer_->data(),
551 if (filter_needs_more_output_space_ && 0 == filtered_data_len) {
552 // filter_needs_more_output_space_ was mistaken... there are no more bytes
553 // and we should have at least tried to fill up the filter's input buffer.
554 // Correct the state, and try again.
555 filter_needs_more_output_space_ = false;
556 return ReadFilteredData(bytes_read);
560 case Filter::FILTER_DONE: {
561 filter_needs_more_output_space_ = false;
562 *bytes_read = filtered_data_len;
563 postfilter_bytes_read_ += filtered_data_len;
567 case Filter::FILTER_NEED_MORE_DATA: {
568 filter_needs_more_output_space_ =
569 (filtered_data_len == output_buffer_size);
570 // We have finished filtering all data currently in the buffer.
571 // There might be some space left in the output buffer. One can
572 // consider reading more data from the stream to feed the filter
573 // and filling up the output buffer. This leads to more complicated
574 // buffer management and data notification mechanisms.
575 // We can revisit this issue if there is a real perf need.
576 if (filtered_data_len > 0) {
577 *bytes_read = filtered_data_len;
578 postfilter_bytes_read_ += filtered_data_len;
581 // Read again since we haven't received enough data yet (e.g., we may
582 // not have a complete gzip header yet)
583 rv = ReadFilteredData(bytes_read);
587 case Filter::FILTER_OK: {
588 filter_needs_more_output_space_ =
589 (filtered_data_len == output_buffer_size);
590 *bytes_read = filtered_data_len;
591 postfilter_bytes_read_ += filtered_data_len;
595 case Filter::FILTER_ERROR: {
596 DVLOG(1) << __FUNCTION__ << "() "
597 << "\"" << (request_ ? request_->url().spec() : "???") << "\""
599 filter_needs_more_output_space_ = false;
600 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED,
601 ERR_CONTENT_DECODING_FAILED));
607 filter_needs_more_output_space_ = false;
612 DVLOG(2) << __FUNCTION__ << "() "
613 << "\"" << (request_ ? request_->url().spec() : "???") << "\""
615 << " post bytes read = " << filtered_data_len
616 << " pre total = " << prefilter_bytes_read_
618 << postfilter_bytes_read_;
619 // If logging all bytes is enabled, log the filtered bytes read.
620 if (rv && request() && request()->net_log().IsLoggingBytes() &&
621 filtered_data_len > 0) {
622 request()->net_log().AddByteTransferEvent(
623 NetLog::TYPE_URL_REQUEST_JOB_FILTERED_BYTES_READ,
624 filtered_data_len, filtered_read_buffer_->data());
627 // we are done, or there is no data left.
632 // When we successfully finished a read, we no longer need to
633 // save the caller's buffers. Release our reference.
634 filtered_read_buffer_ = NULL;
635 filtered_read_buffer_len_ = 0;
640 const URLRequestStatus URLRequestJob::GetStatus() {
642 return request_->status();
643 // If the request is gone, we must be cancelled.
644 return URLRequestStatus(URLRequestStatus::CANCELED,
648 void URLRequestJob::SetStatus(const URLRequestStatus &status) {
650 request_->set_status(status);
653 bool URLRequestJob::ReadRawDataForFilter(int* bytes_read) {
657 DCHECK(filter_.get());
661 // Get more pre-filtered data if needed.
662 // TODO(mbelshe): is it possible that the filter needs *MORE* data
663 // when there is some data already in the buffer?
664 if (!filter_->stream_data_len() && !is_done()) {
665 IOBuffer* stream_buffer = filter_->stream_buffer();
666 int stream_buffer_size = filter_->stream_buffer_size();
667 rv = ReadRawDataHelper(stream_buffer, stream_buffer_size, bytes_read);
672 bool URLRequestJob::ReadRawDataHelper(IOBuffer* buf, int buf_size,
674 DCHECK(!request_->status().is_io_pending());
675 DCHECK(raw_read_buffer_.get() == NULL);
677 // Keep a pointer to the read buffer, so we have access to it in the
678 // OnRawReadComplete() callback in the event that the read completes
680 raw_read_buffer_ = buf;
681 bool rv = ReadRawData(buf, buf_size, bytes_read);
683 if (!request_->status().is_io_pending()) {
684 // If |filter_| is NULL, and logging all bytes is enabled, log the raw
686 if (!filter_.get() && request() && request()->net_log().IsLoggingBytes() &&
688 request()->net_log().AddByteTransferEvent(
689 NetLog::TYPE_URL_REQUEST_JOB_BYTES_READ,
690 *bytes_read, raw_read_buffer_->data());
693 // If the read completes synchronously, either success or failure,
694 // invoke the OnRawReadComplete callback so we can account for the
696 OnRawReadComplete(*bytes_read);
701 void URLRequestJob::FollowRedirect(const GURL& location, int http_status_code) {
702 int rv = request_->Redirect(location, http_status_code);
704 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, rv));
707 void URLRequestJob::OnRawReadComplete(int bytes_read) {
708 DCHECK(raw_read_buffer_.get());
709 if (bytes_read > 0) {
710 RecordBytesRead(bytes_read);
712 raw_read_buffer_ = NULL;
715 void URLRequestJob::RecordBytesRead(int bytes_read) {
716 filter_input_byte_count_ += bytes_read;
717 prefilter_bytes_read_ += bytes_read;
719 postfilter_bytes_read_ += bytes_read;
720 DVLOG(2) << __FUNCTION__ << "() "
721 << "\"" << (request_ ? request_->url().spec() : "???") << "\""
722 << " pre bytes read = " << bytes_read
723 << " pre total = " << prefilter_bytes_read_
724 << " post total = " << postfilter_bytes_read_;
725 UpdatePacketReadTimes(); // Facilitate stats recording if it is active.
726 if (network_delegate_)
727 network_delegate_->NotifyRawBytesRead(*request_, bytes_read);
730 bool URLRequestJob::FilterHasData() {
731 return filter_.get() && filter_->stream_data_len();
734 void URLRequestJob::UpdatePacketReadTimes() {