1// Copyright 2013 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#ifndef CHROME_BROWSER_DOWNLOAD_DOWNLOAD_TARGET_DETERMINER_H_
6#define CHROME_BROWSER_DOWNLOAD_DOWNLOAD_TARGET_DETERMINER_H_
7
8#include "base/files/file_path.h"
9#include "base/memory/ref_counted.h"
10#include "base/memory/scoped_ptr.h"
11#include "base/memory/weak_ptr.h"
12#include "base/task/cancelable_task_tracker.h"
13#include "chrome/browser/download/download_path_reservation_tracker.h"
14#include "chrome/browser/download/download_target_determiner_delegate.h"
15#include "chrome/browser/download/download_target_info.h"
16#include "content/public/browser/download_danger_type.h"
17#include "content/public/browser/download_item.h"
18#include "content/public/browser/download_manager_delegate.h"
19
20class ChromeDownloadManagerDelegate;
21class Profile;
22class DownloadPrefs;
23
24namespace content {
25enum DownloadDangerType;
26}
27
28// Determines the target of the download.
29//
30// Terminology:
31//   Virtual Path: A path representing the target of the download that may or
32//     may not be a physical file path. E.g. if the target of the download is in
33//     cloud storage, then the virtual path may be relative to a logical mount
34//     point.
35//
36//   Local Path: A local file system path where the downloads system should
37//     write the file to.
38//
39//   Intermediate Path: Where the data should be written to during the course of
40//     the download. Once the download completes, the file could be renamed to
41//     Local Path.
42//
43// DownloadTargetDeterminer is a self owned object that performs the work of
44// determining the download target. It observes the DownloadItem and aborts the
45// process if the download is removed. DownloadTargetDeterminerDelegate is
46// responsible for providing external dependencies and prompting the user if
47// necessary.
48//
49// The only public entrypoint is the static Start() method which creates an
50// instance of DownloadTargetDeterminer.
51class DownloadTargetDeterminer
52    : public content::DownloadItem::Observer {
53 public:
54  typedef base::Callback<void(scoped_ptr<DownloadTargetInfo>)>
55      CompletionCallback;
56
57  // Start the process of determing the target of |download|.
58  //
59  // |initial_virtual_path| if non-empty, defines the initial virtual path for
60  //   the target determination process. If one isn't specified, one will be
61  //   generated based on the response data specified in |download| and the
62  //   users' downloads directory.
63  //   Note: |initial_virtual_path| is only used if download has prompted the
64  //       user before and doesn't have a forced path.
65  // |download_prefs| is required and must outlive |download|. It is used for
66  //   determining the user's preferences regarding the default downloads
67  //   directory, prompting and auto-open behavior.
68  // |delegate| is required and must live until |callback| is invoked.
69  // |callback| will be scheduled asynchronously on the UI thread after download
70  //   determination is complete or after |download| is destroyed.
71  //
72  // Start() should be called on the UI thread.
73  static void Start(content::DownloadItem* download,
74                    const base::FilePath& initial_virtual_path,
75                    DownloadPrefs* download_prefs,
76                    DownloadTargetDeterminerDelegate* delegate,
77                    const CompletionCallback& callback);
78
79  // Returns a .crdownload intermediate path for the |suggested_path|.
80  static base::FilePath GetCrDownloadPath(const base::FilePath& suggested_path);
81
82#if defined(OS_WIN)
83  // Returns true if Adobe Reader is up to date. This information refreshed
84  // only when Start() gets called for a PDF and Adobe Reader is the default
85  // System PDF viewer.
86  static bool IsAdobeReaderUpToDate();
87#endif
88
89 private:
90  // The main workflow is controlled via a set of state transitions. Each state
91  // has an associated handler. The handler for STATE_FOO is DoFoo. Each handler
92  // performs work, determines the next state to transition to and returns a
93  // Result indicating how the workflow should proceed. The loop ends when a
94  // handler returns COMPLETE.
95  enum State {
96    STATE_GENERATE_TARGET_PATH,
97    STATE_NOTIFY_EXTENSIONS,
98    STATE_RESERVE_VIRTUAL_PATH,
99    STATE_PROMPT_USER_FOR_DOWNLOAD_PATH,
100    STATE_DETERMINE_LOCAL_PATH,
101    STATE_DETERMINE_MIME_TYPE,
102    STATE_DETERMINE_IF_HANDLED_SAFELY_BY_BROWSER,
103    STATE_DETERMINE_IF_ADOBE_READER_UP_TO_DATE,
104    STATE_CHECK_DOWNLOAD_URL,
105    STATE_CHECK_VISITED_REFERRER_BEFORE,
106    STATE_DETERMINE_INTERMEDIATE_PATH,
107    STATE_NONE,
108  };
109
110  // Result code returned by each step of the workflow below. Controls execution
111  // of DoLoop().
112  enum Result {
113    // Continue processing. next_state_ is required to not be STATE_NONE.
114    CONTINUE,
115
116    // The DoLoop() that invoked the handler should exit. This value is
117    // typically returned when the handler has invoked an asynchronous operation
118    // and is expecting a callback. If a handler returns this value, it has
119    // taken responsibility for ensuring that DoLoop() is invoked. It is
120    // possible that the handler has invoked another DoLoop() already.
121    QUIT_DOLOOP,
122
123    // Target determination is complete.
124    COMPLETE
125  };
126
127  // Used with IsDangerousFile to indicate whether the user has visited the
128  // referrer URL for the download prior to today.
129  enum PriorVisitsToReferrer {
130    NO_VISITS_TO_REFERRER,
131    VISITED_REFERRER,
132  };
133
134  // Construct a DownloadTargetDeterminer object. Constraints on the arguments
135  // are as per Start() above.
136  DownloadTargetDeterminer(content::DownloadItem* download,
137                           const base::FilePath& initial_virtual_path,
138                           DownloadPrefs* download_prefs,
139                           DownloadTargetDeterminerDelegate* delegate,
140                           const CompletionCallback& callback);
141
142  virtual ~DownloadTargetDeterminer();
143
144  // Invoke each successive handler until a handler returns QUIT_DOLOOP or
145  // COMPLETE. Note that as a result, this object might be deleted. So |this|
146  // should not be accessed after calling DoLoop().
147  void DoLoop();
148
149  // === Main workflow ===
150
151  // Generates an initial target path. This target is based only on the state of
152  // the download item.
153  // Next state:
154  // - STATE_NONE : If the download is not in progress, returns COMPLETE.
155  // - STATE_NOTIFY_EXTENSIONS : All other downloads.
156  Result DoGenerateTargetPath();
157
158  // Notifies downloads extensions. If any extension wishes to override the
159  // download filename, it will respond to the OnDeterminingFilename()
160  // notification.
161  // Next state:
162  // - STATE_RESERVE_VIRTUAL_PATH.
163  Result DoNotifyExtensions();
164
165  // Callback invoked after extensions are notified. Updates |virtual_path_| and
166  // |conflict_action_|.
167  void NotifyExtensionsDone(
168      const base::FilePath& new_path,
169      DownloadPathReservationTracker::FilenameConflictAction conflict_action);
170
171  // Invokes ReserveVirtualPath() on the delegate to acquire a reservation for
172  // the path. See DownloadPathReservationTracker.
173  // Next state:
174  // - STATE_PROMPT_USER_FOR_DOWNLOAD_PATH.
175  Result DoReserveVirtualPath();
176
177  // Callback invoked after the delegate aquires a path reservation.
178  void ReserveVirtualPathDone(const base::FilePath& path, bool verified);
179
180  // Presents a file picker to the user if necessary.
181  // Next state:
182  // - STATE_DETERMINE_LOCAL_PATH.
183  Result DoPromptUserForDownloadPath();
184
185  // Callback invoked after the file picker completes. Cancels the download if
186  // the user cancels the file picker.
187  void PromptUserForDownloadPathDone(const base::FilePath& virtual_path);
188
189  // Up until this point, the path that was used is considered to be a virtual
190  // path. This step determines the local file system path corresponding to this
191  // virtual path. The translation is done by invoking the DetermineLocalPath()
192  // method on the delegate.
193  // Next state:
194  // - STATE_DETERMINE_MIME_TYPE.
195  Result DoDetermineLocalPath();
196
197  // Callback invoked when the delegate has determined local path.
198  void DetermineLocalPathDone(const base::FilePath& local_path);
199
200  // Determine the MIME type corresponding to the local file path. This is only
201  // done if the local path and the virtual path was the same. I.e. The file is
202  // intended for the local file system. This restriction is there because the
203  // resulting MIME type is only valid for determining whether the browser can
204  // handle the download if it were opened via a file:// URL.
205  // Next state:
206  // - STATE_DETERMINE_IF_HANDLED_SAFELY_BY_BROWSER.
207  Result DoDetermineMimeType();
208
209  // Callback invoked when the MIME type is available. Since determination of
210  // the MIME type can involve disk access, it is done in the blocking pool.
211  void DetermineMimeTypeDone(const std::string& mime_type);
212
213  // Determine if the file type can be handled safely by the browser if it were
214  // to be opened via a file:// URL.
215  // Next state:
216  // - STATE_DETERMINE_IF_ADOBE_READER_UP_TO_DATE.
217  Result DoDetermineIfHandledSafely();
218
219#if defined(ENABLE_PLUGINS)
220  // Callback invoked when a decision is available about whether the file type
221  // can be handled safely by the browser.
222  void DetermineIfHandledSafelyDone(bool is_handled_safely);
223#endif
224
225  // Determine if Adobe Reader is up to date. Only do the check on Windows for
226  // .pdf file targets.
227  // Next state:
228  // - STATE_CHECK_DOWNLOAD_URL.
229  Result DoDetermineIfAdobeReaderUpToDate();
230
231#if defined(OS_WIN)
232  // Callback invoked when a decision is available about whether Adobe Reader
233  // is up to date.
234  void DetermineIfAdobeReaderUpToDateDone(bool adobe_reader_up_to_date);
235#endif
236
237  // Checks whether the downloaded URL is malicious. Invokes the
238  // DownloadProtectionService via the delegate.
239  // Next state:
240  // - STATE_CHECK_VISITED_REFERRER_BEFORE.
241  Result DoCheckDownloadUrl();
242
243  // Callback invoked after the delegate has checked the download URL. Sets the
244  // danger type of the download to |danger_type|.
245  void CheckDownloadUrlDone(content::DownloadDangerType danger_type);
246
247  // Checks if the user has visited the referrer URL of the download prior to
248  // today. The actual check is only performed if it would be needed to
249  // determine the danger type of the download.
250  // Next state:
251  // - STATE_DETERMINE_INTERMEDIATE_PATH.
252  Result DoCheckVisitedReferrerBefore();
253
254  // Callback invoked after completion of history check for prior visits to
255  // referrer URL.
256  void CheckVisitedReferrerBeforeDone(bool visited_referrer_before);
257
258  // Determines the intermediate path. Once this step completes, downloads
259  // target determination is complete. The determination assumes that the
260  // intermediate file will never be overwritten (always uniquified if needed).
261  // Next state:
262  // - STATE_NONE: Returns COMPLETE.
263  Result DoDetermineIntermediatePath();
264
265  // === End of main workflow ===
266
267  // Utilities:
268
269  void ScheduleCallbackAndDeleteSelf();
270
271  void CancelOnFailureAndDeleteSelf();
272
273  Profile* GetProfile();
274
275  // Determine whether to prompt the user for the download location. For regular
276  // downloads, this determination is based on the target disposition, auto-open
277  // behavior, among other factors. For an interrupted download, this
278  // determination will be based on the interrupt reason. It is assumed that
279  // download interruptions always occur after the first round of download
280  // target determination is complete.
281  bool ShouldPromptForDownload(const base::FilePath& filename) const;
282
283  // Returns true if the user has been prompted for this download at least once
284  // prior to this target determination operation. This method is only expected
285  // to return true for a resuming interrupted download that has prompted the
286  // user before interruption. The return value does not depend on whether the
287  // user will be or has been prompted during the current target determination
288  // operation.
289  bool HasPromptedForPath() const;
290
291  // Returns true if this download should show the "dangerous file" warning.
292  // Various factors are considered, such as the type of the file, whether a
293  // user action initiated the download, and whether the user has explicitly
294  // marked the file type as "auto open". Protected virtual for testing.
295  bool IsDangerousFile(PriorVisitsToReferrer visits);
296
297  // content::DownloadItem::Observer
298  virtual void OnDownloadDestroyed(content::DownloadItem* download) OVERRIDE;
299
300  // state
301  State next_state_;
302  bool should_prompt_;
303  bool should_notify_extensions_;
304  bool create_target_directory_;
305  DownloadPathReservationTracker::FilenameConflictAction conflict_action_;
306  content::DownloadDangerType danger_type_;
307  bool is_dangerous_file_;  // See DownloadTargetInfo::is_dangerous_file
308  base::FilePath virtual_path_;
309  base::FilePath local_path_;
310  base::FilePath intermediate_path_;
311  std::string mime_type_;
312  bool is_filetype_handled_safely_;
313
314  content::DownloadItem* download_;
315  const bool is_resumption_;
316  DownloadPrefs* download_prefs_;
317  DownloadTargetDeterminerDelegate* delegate_;
318  CompletionCallback completion_callback_;
319  base::CancelableTaskTracker history_tracker_;
320
321  base::WeakPtrFactory<DownloadTargetDeterminer> weak_ptr_factory_;
322
323  DISALLOW_COPY_AND_ASSIGN(DownloadTargetDeterminer);
324};
325
326#endif  // CHROME_BROWSER_DOWNLOAD_DOWNLOAD_TARGET_DETERMINER_H_
327