Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / net / url_request / url_request_job.cc
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.
4
5 #include "net/url_request/url_request_job.h"
6
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 "net/base/auth.h"
15 #include "net/base/host_port_pair.h"
16 #include "net/base/io_buffer.h"
17 #include "net/base/load_states.h"
18 #include "net/base/net_errors.h"
19 #include "net/base/network_delegate.h"
20 #include "net/filter/filter.h"
21 #include "net/http/http_response_headers.h"
22 #include "net/url_request/url_request.h"
23
24 namespace net {
25
26 URLRequestJob::URLRequestJob(URLRequest* request,
27                              NetworkDelegate* network_delegate)
28     : request_(request),
29       done_(false),
30       prefilter_bytes_read_(0),
31       postfilter_bytes_read_(0),
32       filter_input_byte_count_(0),
33       filter_needs_more_output_space_(false),
34       filtered_read_buffer_len_(0),
35       has_handled_response_(false),
36       expected_content_size_(-1),
37       network_delegate_(network_delegate),
38       weak_factory_(this) {
39   base::PowerMonitor* power_monitor = base::PowerMonitor::Get();
40   if (power_monitor)
41     power_monitor->AddObserver(this);
42 }
43
44 void URLRequestJob::SetUpload(UploadDataStream* upload) {
45 }
46
47 void URLRequestJob::SetExtraRequestHeaders(const HttpRequestHeaders& headers) {
48 }
49
50 void URLRequestJob::SetPriority(RequestPriority priority) {
51 }
52
53 void URLRequestJob::Kill() {
54   weak_factory_.InvalidateWeakPtrs();
55   // Make sure the request is notified that we are done.  We assume that the
56   // request took care of setting its error status before calling Kill.
57   if (request_)
58     NotifyCanceled();
59 }
60
61 void URLRequestJob::DetachRequest() {
62   request_ = NULL;
63 }
64
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
67 // the caller.
68 bool URLRequestJob::Read(IOBuffer* buf, int buf_size, int *bytes_read) {
69   bool rv = false;
70
71   DCHECK_LT(buf_size, 1000000);  // Sanity check.
72   DCHECK(buf);
73   DCHECK(bytes_read);
74   DCHECK(filtered_read_buffer_.get() == NULL);
75   DCHECK_EQ(0, filtered_read_buffer_len_);
76
77   *bytes_read = 0;
78
79   // Skip Filter if not present.
80   if (!filter_.get()) {
81     rv = ReadRawDataHelper(buf, buf_size, bytes_read);
82   } else {
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;
87
88     if (ReadFilteredData(bytes_read)) {
89       rv = true;   // We have data to return.
90
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).
94       if (*bytes_read == 0)
95         DoneReading();
96     } else {
97       rv = false;  // Error, or a new IO is pending.
98     }
99   }
100   if (rv && *bytes_read == 0)
101     NotifyDone(URLRequestStatus());
102   return rv;
103 }
104
105 void URLRequestJob::StopCaching() {
106   // Nothing to do here.
107 }
108
109 bool URLRequestJob::GetFullRequestHeaders(HttpRequestHeaders* headers) const {
110   // Most job types don't send request headers.
111   return false;
112 }
113
114 int64 URLRequestJob::GetTotalReceivedBytes() const {
115   return 0;
116 }
117
118 LoadState URLRequestJob::GetLoadState() const {
119   return LOAD_STATE_IDLE;
120 }
121
122 UploadProgress URLRequestJob::GetUploadProgress() const {
123   return UploadProgress();
124 }
125
126 bool URLRequestJob::GetCharset(std::string* charset) {
127   return false;
128 }
129
130 void URLRequestJob::GetResponseInfo(HttpResponseInfo* info) {
131 }
132
133 void URLRequestJob::GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const {
134   // Only certain request types return more than just request start times.
135 }
136
137 bool URLRequestJob::GetResponseCookies(std::vector<std::string>* cookies) {
138   return false;
139 }
140
141 Filter* URLRequestJob::SetupFilter() const {
142   return NULL;
143 }
144
145 bool URLRequestJob::IsRedirectResponse(GURL* location,
146                                        int* http_status_code) {
147   // For non-HTTP jobs, headers will be null.
148   HttpResponseHeaders* headers = request_->response_headers();
149   if (!headers)
150     return false;
151
152   std::string value;
153   if (!headers->IsRedirect(&value))
154     return false;
155
156   *location = request_->url().Resolve(value);
157   *http_status_code = headers->response_code();
158   return true;
159 }
160
161 bool URLRequestJob::CopyFragmentOnRedirect(const GURL& location) const {
162   return true;
163 }
164
165 bool URLRequestJob::IsSafeRedirect(const GURL& location) {
166   return true;
167 }
168
169 bool URLRequestJob::NeedsAuth() {
170   return false;
171 }
172
173 void URLRequestJob::GetAuthChallengeInfo(
174     scoped_refptr<AuthChallengeInfo>* auth_info) {
175   // This will only be called if NeedsAuth() returns true, in which
176   // case the derived class should implement this!
177   NOTREACHED();
178 }
179
180 void URLRequestJob::SetAuth(const AuthCredentials& credentials) {
181   // This will only be called if NeedsAuth() returns true, in which
182   // case the derived class should implement this!
183   NOTREACHED();
184 }
185
186 void URLRequestJob::CancelAuth() {
187   // This will only be called if NeedsAuth() returns true, in which
188   // case the derived class should implement this!
189   NOTREACHED();
190 }
191
192 void URLRequestJob::ContinueWithCertificate(
193     X509Certificate* client_cert) {
194   // The derived class should implement this!
195   NOTREACHED();
196 }
197
198 void URLRequestJob::ContinueDespiteLastError() {
199   // Implementations should know how to recover from errors they generate.
200   // If this code was reached, we are trying to recover from an error that
201   // we don't know how to recover from.
202   NOTREACHED();
203 }
204
205 void URLRequestJob::FollowDeferredRedirect() {
206   DCHECK_NE(-1, deferred_redirect_info_.status_code);
207
208   // NOTE: deferred_redirect_info_ may be invalid, and attempting to follow it
209   // will fail inside FollowRedirect.  The DCHECK above asserts that we called
210   // OnReceivedRedirect.
211
212   // It is also possible that FollowRedirect will drop the last reference to
213   // this job, so we need to reset our members before calling it.
214
215   RedirectInfo redirect_info = deferred_redirect_info_;
216   deferred_redirect_info_ = RedirectInfo();
217   FollowRedirect(redirect_info);
218 }
219
220 void URLRequestJob::ResumeNetworkStart() {
221   // This should only be called for HTTP Jobs, and implemented in the derived
222   // class.
223   NOTREACHED();
224 }
225
226 bool URLRequestJob::GetMimeType(std::string* mime_type) const {
227   return false;
228 }
229
230 int URLRequestJob::GetResponseCode() const {
231   return -1;
232 }
233
234 HostPortPair URLRequestJob::GetSocketAddress() const {
235   return HostPortPair();
236 }
237
238 void URLRequestJob::OnSuspend() {
239   Kill();
240 }
241
242 void URLRequestJob::NotifyURLRequestDestroyed() {
243 }
244
245 URLRequestJob::~URLRequestJob() {
246   base::PowerMonitor* power_monitor = base::PowerMonitor::Get();
247   if (power_monitor)
248     power_monitor->RemoveObserver(this);
249 }
250
251 void URLRequestJob::NotifyCertificateRequested(
252     SSLCertRequestInfo* cert_request_info) {
253   if (!request_)
254     return;  // The request was destroyed, so there is no more work to do.
255
256   request_->NotifyCertificateRequested(cert_request_info);
257 }
258
259 void URLRequestJob::NotifySSLCertificateError(const SSLInfo& ssl_info,
260                                               bool fatal) {
261   if (!request_)
262     return;  // The request was destroyed, so there is no more work to do.
263
264   request_->NotifySSLCertificateError(ssl_info, fatal);
265 }
266
267 bool URLRequestJob::CanGetCookies(const CookieList& cookie_list) const {
268   if (!request_)
269     return false;  // The request was destroyed, so there is no more work to do.
270
271   return request_->CanGetCookies(cookie_list);
272 }
273
274 bool URLRequestJob::CanSetCookie(const std::string& cookie_line,
275                                  CookieOptions* options) const {
276   if (!request_)
277     return false;  // The request was destroyed, so there is no more work to do.
278
279   return request_->CanSetCookie(cookie_line, options);
280 }
281
282 bool URLRequestJob::CanEnablePrivacyMode() const {
283   if (!request_)
284     return false;  // The request was destroyed, so there is no more work to do.
285
286   return request_->CanEnablePrivacyMode();
287 }
288
289 CookieStore* URLRequestJob::GetCookieStore() const {
290   DCHECK(request_);
291
292   return request_->cookie_store();
293 }
294
295 void URLRequestJob::NotifyBeforeNetworkStart(bool* defer) {
296   if (!request_)
297     return;
298
299   request_->NotifyBeforeNetworkStart(defer);
300 }
301
302 void URLRequestJob::NotifyHeadersComplete() {
303   // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
304   tracked_objects::ScopedTracker tracking_profile(
305       FROM_HERE_WITH_EXPLICIT_FUNCTION(
306           "423948 URLRequestJob::NotifyHeadersComplete"));
307
308   if (!request_ || !request_->has_delegate())
309     return;  // The request was destroyed, so there is no more work to do.
310
311   if (has_handled_response_)
312     return;
313
314   DCHECK(!request_->status().is_io_pending());
315
316   // Initialize to the current time, and let the subclass optionally override
317   // the time stamps if it has that information.  The default request_time is
318   // set by URLRequest before it calls our Start method.
319   request_->response_info_.response_time = base::Time::Now();
320   GetResponseInfo(&request_->response_info_);
321
322   // When notifying the delegate, the delegate can release the request
323   // (and thus release 'this').  After calling to the delgate, we must
324   // check the request pointer to see if it still exists, and return
325   // immediately if it has been destroyed.  self_preservation ensures our
326   // survival until we can get out of this method.
327   scoped_refptr<URLRequestJob> self_preservation(this);
328
329   if (request_) {
330     // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
331     tracked_objects::ScopedTracker tracking_profile1(
332         FROM_HERE_WITH_EXPLICIT_FUNCTION(
333             "423948 URLRequestJob::NotifyHeadersComplete 1"));
334
335     request_->OnHeadersComplete();
336   }
337
338   // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
339   tracked_objects::ScopedTracker tracking_profile2(
340       FROM_HERE_WITH_EXPLICIT_FUNCTION(
341           "423948 URLRequestJob::NotifyHeadersComplete 2"));
342
343   GURL new_location;
344   int http_status_code;
345   if (IsRedirectResponse(&new_location, &http_status_code)) {
346     // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
347     tracked_objects::ScopedTracker tracking_profile3(
348         FROM_HERE_WITH_EXPLICIT_FUNCTION(
349             "423948 URLRequestJob::NotifyHeadersComplete 3"));
350
351     // Redirect response bodies are not read. Notify the transaction
352     // so it does not treat being stopped as an error.
353     DoneReadingRedirectResponse();
354
355     // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
356     tracked_objects::ScopedTracker tracking_profile4(
357         FROM_HERE_WITH_EXPLICIT_FUNCTION(
358             "423948 URLRequestJob::NotifyHeadersComplete 4"));
359
360     RedirectInfo redirect_info =
361         ComputeRedirectInfo(new_location, http_status_code);
362
363     // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
364     tracked_objects::ScopedTracker tracking_profile5(
365         FROM_HERE_WITH_EXPLICIT_FUNCTION(
366             "423948 URLRequestJob::NotifyHeadersComplete 5"));
367
368     bool defer_redirect = false;
369     request_->NotifyReceivedRedirect(redirect_info, &defer_redirect);
370
371     // Ensure that the request wasn't detached or destroyed in
372     // NotifyReceivedRedirect
373     if (!request_ || !request_->has_delegate())
374       return;
375
376     // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
377     tracked_objects::ScopedTracker tracking_profile6(
378         FROM_HERE_WITH_EXPLICIT_FUNCTION(
379             "423948 URLRequestJob::NotifyHeadersComplete 6"));
380
381     // If we were not cancelled, then maybe follow the redirect.
382     if (request_->status().is_success()) {
383       if (defer_redirect) {
384         deferred_redirect_info_ = redirect_info;
385       } else {
386         FollowRedirect(redirect_info);
387       }
388       return;
389     }
390   } else if (NeedsAuth()) {
391     // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
392     tracked_objects::ScopedTracker tracking_profile7(
393         FROM_HERE_WITH_EXPLICIT_FUNCTION(
394             "423948 URLRequestJob::NotifyHeadersComplete 7"));
395
396     scoped_refptr<AuthChallengeInfo> auth_info;
397     GetAuthChallengeInfo(&auth_info);
398
399     // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
400     tracked_objects::ScopedTracker tracking_profile8(
401         FROM_HERE_WITH_EXPLICIT_FUNCTION(
402             "423948 URLRequestJob::NotifyHeadersComplete 8"));
403
404     // Need to check for a NULL auth_info because the server may have failed
405     // to send a challenge with the 401 response.
406     if (auth_info.get()) {
407       request_->NotifyAuthRequired(auth_info.get());
408       // Wait for SetAuth or CancelAuth to be called.
409       return;
410     }
411   }
412
413   // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
414   tracked_objects::ScopedTracker tracking_profile9(
415       FROM_HERE_WITH_EXPLICIT_FUNCTION(
416           "423948 URLRequestJob::NotifyHeadersComplete 9"));
417
418   has_handled_response_ = true;
419   if (request_->status().is_success())
420     filter_.reset(SetupFilter());
421
422   if (!filter_.get()) {
423     std::string content_length;
424     request_->GetResponseHeaderByName("content-length", &content_length);
425     if (!content_length.empty())
426       base::StringToInt64(content_length, &expected_content_size_);
427   }
428
429   // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
430   tracked_objects::ScopedTracker tracking_profile10(
431       FROM_HERE_WITH_EXPLICIT_FUNCTION(
432           "423948 URLRequestJob::NotifyHeadersComplete 10"));
433
434   request_->NotifyResponseStarted();
435 }
436
437 void URLRequestJob::NotifyReadComplete(int bytes_read) {
438   if (!request_ || !request_->has_delegate())
439     return;  // The request was destroyed, so there is no more work to do.
440
441   // TODO(darin): Bug 1004233. Re-enable this test once all of the chrome
442   // unit_tests have been fixed to not trip this.
443 #if 0
444   DCHECK(!request_->status().is_io_pending());
445 #endif
446   // The headers should be complete before reads complete
447   DCHECK(has_handled_response_);
448
449   OnRawReadComplete(bytes_read);
450
451   // Don't notify if we had an error.
452   if (!request_->status().is_success())
453     return;
454
455   // When notifying the delegate, the delegate can release the request
456   // (and thus release 'this').  After calling to the delegate, we must
457   // check the request pointer to see if it still exists, and return
458   // immediately if it has been destroyed.  self_preservation ensures our
459   // survival until we can get out of this method.
460   scoped_refptr<URLRequestJob> self_preservation(this);
461
462   if (filter_.get()) {
463     // Tell the filter that it has more data
464     FilteredDataRead(bytes_read);
465
466     // Filter the data.
467     int filter_bytes_read = 0;
468     if (ReadFilteredData(&filter_bytes_read)) {
469       if (!filter_bytes_read)
470         DoneReading();
471       request_->NotifyReadCompleted(filter_bytes_read);
472     }
473   } else {
474     request_->NotifyReadCompleted(bytes_read);
475   }
476   DVLOG(1) << __FUNCTION__ << "() "
477            << "\"" << (request_ ? request_->url().spec() : "???") << "\""
478            << " pre bytes read = " << bytes_read
479            << " pre total = " << prefilter_bytes_read_
480            << " post total = " << postfilter_bytes_read_;
481 }
482
483 void URLRequestJob::NotifyStartError(const URLRequestStatus &status) {
484   DCHECK(!has_handled_response_);
485   has_handled_response_ = true;
486   if (request_) {
487     // There may be relevant information in the response info even in the
488     // error case.
489     GetResponseInfo(&request_->response_info_);
490
491     request_->set_status(status);
492     request_->NotifyResponseStarted();
493     // We may have been deleted.
494   }
495 }
496
497 void URLRequestJob::NotifyDone(const URLRequestStatus &status) {
498   DCHECK(!done_) << "Job sending done notification twice";
499   if (done_)
500     return;
501   done_ = true;
502
503   // Unless there was an error, we should have at least tried to handle
504   // the response before getting here.
505   DCHECK(has_handled_response_ || !status.is_success());
506
507   // As with NotifyReadComplete, we need to take care to notice if we were
508   // destroyed during a delegate callback.
509   if (request_) {
510     request_->set_is_pending(false);
511     // With async IO, it's quite possible to have a few outstanding
512     // requests.  We could receive a request to Cancel, followed shortly
513     // by a successful IO.  For tracking the status(), once there is
514     // an error, we do not change the status back to success.  To
515     // enforce this, only set the status if the job is so far
516     // successful.
517     if (request_->status().is_success()) {
518       if (status.status() == URLRequestStatus::FAILED) {
519         request_->net_log().AddEventWithNetErrorCode(NetLog::TYPE_FAILED,
520                                                      status.error());
521       }
522       request_->set_status(status);
523     }
524   }
525
526   // Complete this notification later.  This prevents us from re-entering the
527   // delegate if we're done because of a synchronous call.
528   base::MessageLoop::current()->PostTask(
529       FROM_HERE,
530       base::Bind(&URLRequestJob::CompleteNotifyDone,
531                  weak_factory_.GetWeakPtr()));
532 }
533
534 void URLRequestJob::CompleteNotifyDone() {
535   // Check if we should notify the delegate that we're done because of an error.
536   if (request_ &&
537       !request_->status().is_success() &&
538       request_->has_delegate()) {
539     // We report the error differently depending on whether we've called
540     // OnResponseStarted yet.
541     if (has_handled_response_) {
542       // We signal the error by calling OnReadComplete with a bytes_read of -1.
543       request_->NotifyReadCompleted(-1);
544     } else {
545       has_handled_response_ = true;
546       request_->NotifyResponseStarted();
547     }
548   }
549 }
550
551 void URLRequestJob::NotifyCanceled() {
552   if (!done_) {
553     NotifyDone(URLRequestStatus(URLRequestStatus::CANCELED, ERR_ABORTED));
554   }
555 }
556
557 void URLRequestJob::NotifyRestartRequired() {
558   DCHECK(!has_handled_response_);
559   if (GetStatus().status() != URLRequestStatus::CANCELED)
560     request_->Restart();
561 }
562
563 void URLRequestJob::OnCallToDelegate() {
564   request_->OnCallToDelegate();
565 }
566
567 void URLRequestJob::OnCallToDelegateComplete() {
568   request_->OnCallToDelegateComplete();
569 }
570
571 bool URLRequestJob::ReadRawData(IOBuffer* buf, int buf_size,
572                                 int *bytes_read) {
573   DCHECK(bytes_read);
574   *bytes_read = 0;
575   return true;
576 }
577
578 void URLRequestJob::DoneReading() {
579   // Do nothing.
580 }
581
582 void URLRequestJob::DoneReadingRedirectResponse() {
583 }
584
585 void URLRequestJob::FilteredDataRead(int bytes_read) {
586   DCHECK(filter_);
587   filter_->FlushStreamBuffer(bytes_read);
588 }
589
590 bool URLRequestJob::ReadFilteredData(int* bytes_read) {
591   DCHECK(filter_);
592   DCHECK(filtered_read_buffer_.get());
593   DCHECK_GT(filtered_read_buffer_len_, 0);
594   DCHECK_LT(filtered_read_buffer_len_, 1000000);  // Sanity check.
595   DCHECK(!raw_read_buffer_.get());
596
597   *bytes_read = 0;
598   bool rv = false;
599
600   for (;;) {
601     if (is_done())
602       return true;
603
604     if (!filter_needs_more_output_space_ && !filter_->stream_data_len()) {
605       // We don't have any raw data to work with, so read from the transaction.
606       int filtered_data_read;
607       if (ReadRawDataForFilter(&filtered_data_read)) {
608         if (filtered_data_read > 0) {
609           // Give data to filter.
610           filter_->FlushStreamBuffer(filtered_data_read);
611         } else {
612           return true;  // EOF.
613         }
614       } else {
615         return false;  // IO Pending (or error).
616       }
617     }
618
619     if ((filter_->stream_data_len() || filter_needs_more_output_space_) &&
620         !is_done()) {
621       // Get filtered data.
622       int filtered_data_len = filtered_read_buffer_len_;
623       int output_buffer_size = filtered_data_len;
624       Filter::FilterStatus status =
625           filter_->ReadData(filtered_read_buffer_->data(), &filtered_data_len);
626
627       if (filter_needs_more_output_space_ && !filtered_data_len) {
628         // filter_needs_more_output_space_ was mistaken... there are no more
629         // bytes and we should have at least tried to fill up the filter's input
630         // buffer. Correct the state, and try again.
631         filter_needs_more_output_space_ = false;
632         continue;
633       }
634       filter_needs_more_output_space_ =
635           (filtered_data_len == output_buffer_size);
636
637       switch (status) {
638         case Filter::FILTER_DONE: {
639           filter_needs_more_output_space_ = false;
640           *bytes_read = filtered_data_len;
641           postfilter_bytes_read_ += filtered_data_len;
642           rv = true;
643           break;
644         }
645         case Filter::FILTER_NEED_MORE_DATA: {
646           // We have finished filtering all data currently in the buffer.
647           // There might be some space left in the output buffer. One can
648           // consider reading more data from the stream to feed the filter
649           // and filling up the output buffer. This leads to more complicated
650           // buffer management and data notification mechanisms.
651           // We can revisit this issue if there is a real perf need.
652           if (filtered_data_len > 0) {
653             *bytes_read = filtered_data_len;
654             postfilter_bytes_read_ += filtered_data_len;
655             rv = true;
656           } else {
657             // Read again since we haven't received enough data yet (e.g., we
658             // may not have a complete gzip header yet).
659             continue;
660           }
661           break;
662         }
663         case Filter::FILTER_OK: {
664           *bytes_read = filtered_data_len;
665           postfilter_bytes_read_ += filtered_data_len;
666           rv = true;
667           break;
668         }
669         case Filter::FILTER_ERROR: {
670           DVLOG(1) << __FUNCTION__ << "() "
671                    << "\"" << (request_ ? request_->url().spec() : "???")
672                    << "\"" << " Filter Error";
673           filter_needs_more_output_space_ = false;
674           NotifyDone(URLRequestStatus(URLRequestStatus::FAILED,
675                      ERR_CONTENT_DECODING_FAILED));
676           rv = false;
677           break;
678         }
679         default: {
680           NOTREACHED();
681           filter_needs_more_output_space_ = false;
682           rv = false;
683           break;
684         }
685       }
686
687       // If logging all bytes is enabled, log the filtered bytes read.
688       if (rv && request() && request()->net_log().IsLoggingBytes() &&
689           filtered_data_len > 0) {
690         request()->net_log().AddByteTransferEvent(
691             NetLog::TYPE_URL_REQUEST_JOB_FILTERED_BYTES_READ,
692             filtered_data_len, filtered_read_buffer_->data());
693       }
694     } else {
695       // we are done, or there is no data left.
696       rv = true;
697     }
698     break;
699   }
700
701   if (rv) {
702     // When we successfully finished a read, we no longer need to save the
703     // caller's buffers. Release our reference.
704     filtered_read_buffer_ = NULL;
705     filtered_read_buffer_len_ = 0;
706   }
707   return rv;
708 }
709
710 void URLRequestJob::DestroyFilters() {
711   filter_.reset();
712 }
713
714 const URLRequestStatus URLRequestJob::GetStatus() {
715   if (request_)
716     return request_->status();
717   // If the request is gone, we must be cancelled.
718   return URLRequestStatus(URLRequestStatus::CANCELED,
719                           ERR_ABORTED);
720 }
721
722 void URLRequestJob::SetStatus(const URLRequestStatus &status) {
723   if (request_)
724     request_->set_status(status);
725 }
726
727 void URLRequestJob::SetProxyServer(const HostPortPair& proxy_server) {
728   request_->proxy_server_ = proxy_server;
729 }
730
731 bool URLRequestJob::ReadRawDataForFilter(int* bytes_read) {
732   bool rv = false;
733
734   DCHECK(bytes_read);
735   DCHECK(filter_.get());
736
737   *bytes_read = 0;
738
739   // Get more pre-filtered data if needed.
740   // TODO(mbelshe): is it possible that the filter needs *MORE* data
741   //    when there is some data already in the buffer?
742   if (!filter_->stream_data_len() && !is_done()) {
743     IOBuffer* stream_buffer = filter_->stream_buffer();
744     int stream_buffer_size = filter_->stream_buffer_size();
745     rv = ReadRawDataHelper(stream_buffer, stream_buffer_size, bytes_read);
746   }
747   return rv;
748 }
749
750 bool URLRequestJob::ReadRawDataHelper(IOBuffer* buf, int buf_size,
751                                       int* bytes_read) {
752   DCHECK(!request_->status().is_io_pending());
753   DCHECK(raw_read_buffer_.get() == NULL);
754
755   // Keep a pointer to the read buffer, so we have access to it in the
756   // OnRawReadComplete() callback in the event that the read completes
757   // asynchronously.
758   raw_read_buffer_ = buf;
759   bool rv = ReadRawData(buf, buf_size, bytes_read);
760
761   if (!request_->status().is_io_pending()) {
762     // If the read completes synchronously, either success or failure,
763     // invoke the OnRawReadComplete callback so we can account for the
764     // completed read.
765     OnRawReadComplete(*bytes_read);
766   }
767   return rv;
768 }
769
770 void URLRequestJob::FollowRedirect(const RedirectInfo& redirect_info) {
771   int rv = request_->Redirect(redirect_info);
772   if (rv != OK)
773     NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, rv));
774 }
775
776 void URLRequestJob::OnRawReadComplete(int bytes_read) {
777   DCHECK(raw_read_buffer_.get());
778   // If |filter_| is non-NULL, bytes will be logged after it is applied instead.
779   if (!filter_.get() && request() && request()->net_log().IsLoggingBytes() &&
780       bytes_read > 0) {
781     request()->net_log().AddByteTransferEvent(
782         NetLog::TYPE_URL_REQUEST_JOB_BYTES_READ,
783         bytes_read, raw_read_buffer_->data());
784   }
785
786   if (bytes_read > 0) {
787     RecordBytesRead(bytes_read);
788   }
789   raw_read_buffer_ = NULL;
790 }
791
792 void URLRequestJob::RecordBytesRead(int bytes_read) {
793   filter_input_byte_count_ += bytes_read;
794   prefilter_bytes_read_ += bytes_read;
795   if (!filter_.get())
796     postfilter_bytes_read_ += bytes_read;
797   DVLOG(2) << __FUNCTION__ << "() "
798            << "\"" << (request_ ? request_->url().spec() : "???") << "\""
799            << " pre bytes read = " << bytes_read
800            << " pre total = " << prefilter_bytes_read_
801            << " post total = " << postfilter_bytes_read_;
802   UpdatePacketReadTimes();  // Facilitate stats recording if it is active.
803   if (network_delegate_)
804     network_delegate_->NotifyRawBytesRead(*request_, bytes_read);
805 }
806
807 bool URLRequestJob::FilterHasData() {
808     return filter_.get() && filter_->stream_data_len();
809 }
810
811 void URLRequestJob::UpdatePacketReadTimes() {
812 }
813
814 RedirectInfo URLRequestJob::ComputeRedirectInfo(const GURL& location,
815                                                 int http_status_code) {
816   const GURL& url = request_->url();
817
818   RedirectInfo redirect_info;
819
820   redirect_info.status_code = http_status_code;
821
822   // The request method may change, depending on the status code.
823   redirect_info.new_method = URLRequest::ComputeMethodForRedirect(
824       request_->method(), http_status_code);
825
826   // Move the reference fragment of the old location to the new one if the
827   // new one has none. This duplicates mozilla's behavior.
828   if (url.is_valid() && url.has_ref() && !location.has_ref() &&
829       CopyFragmentOnRedirect(location)) {
830     GURL::Replacements replacements;
831     // Reference the |ref| directly out of the original URL to avoid a
832     // malloc.
833     replacements.SetRef(url.spec().data(),
834                         url.parsed_for_possibly_invalid_spec().ref);
835     redirect_info.new_url = location.ReplaceComponents(replacements);
836   } else {
837     redirect_info.new_url = location;
838   }
839
840   // Update the first-party URL if appropriate.
841   if (request_->first_party_url_policy() ==
842           URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT) {
843     redirect_info.new_first_party_for_cookies = redirect_info.new_url;
844   } else {
845     redirect_info.new_first_party_for_cookies =
846         request_->first_party_for_cookies();
847   }
848
849   // Suppress the referrer if we're redirecting out of https.
850   if (request_->referrer_policy() ==
851           URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE &&
852       GURL(request_->referrer()).SchemeIsSecure() &&
853       !redirect_info.new_url.SchemeIsSecure()) {
854     redirect_info.new_referrer.clear();
855   } else {
856     redirect_info.new_referrer = request_->referrer();
857   }
858
859   return redirect_info;
860 }
861
862 }  // namespace net