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 "chrome/browser/download/download_resource_throttle.h"
6
7#include "base/bind.h"
8#include "chrome/browser/download/download_stats.h"
9#include "content/public/browser/resource_controller.h"
10
11DownloadResourceThrottle::DownloadResourceThrottle(
12    DownloadRequestLimiter* limiter,
13    int render_process_id,
14    int render_view_id,
15    const GURL& url,
16    const std::string& request_method)
17    : querying_limiter_(true),
18      request_allowed_(false),
19      request_deferred_(false) {
20  limiter->CanDownloadOnIOThread(
21      render_process_id,
22      render_view_id,
23      url,
24      request_method,
25      base::Bind(&DownloadResourceThrottle::ContinueDownload,
26                 AsWeakPtr()));
27}
28
29DownloadResourceThrottle::~DownloadResourceThrottle() {
30}
31
32void DownloadResourceThrottle::WillStartRequest(bool* defer) {
33  WillDownload(defer);
34}
35
36void DownloadResourceThrottle::WillRedirectRequest(const GURL& new_url,
37                                                   bool* defer) {
38  WillDownload(defer);
39}
40
41void DownloadResourceThrottle::WillProcessResponse(bool* defer) {
42  WillDownload(defer);
43}
44
45const char* DownloadResourceThrottle::GetNameForLogging() const {
46  return "DownloadResourceThrottle";
47}
48
49void DownloadResourceThrottle::WillDownload(bool* defer) {
50  DCHECK(!request_deferred_);
51
52  // Defer the download until we have the DownloadRequestLimiter result.
53  if (querying_limiter_) {
54    request_deferred_ = true;
55    *defer = true;
56    return;
57  }
58
59  if (!request_allowed_)
60    controller()->Cancel();
61}
62
63void DownloadResourceThrottle::ContinueDownload(bool allow) {
64  querying_limiter_ = false;
65  request_allowed_ = allow;
66
67  if (allow) {
68    // Presumes all downloads initiated by navigation use this throttle and
69    // nothing else does.
70    RecordDownloadSource(DOWNLOAD_INITIATED_BY_NAVIGATION);
71  } else {
72    RecordDownloadCount(CHROME_DOWNLOAD_COUNT_BLOCKED_BY_THROTTLING);
73  }
74
75  if (request_deferred_) {
76    request_deferred_ = false;
77    if (allow) {
78      controller()->Resume();
79    } else {
80      controller()->Cancel();
81    }
82  }
83}
84