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 #ifndef CHROME_BROWSER_FILE_SELECT_HELPER_H_
6 #define CHROME_BROWSER_FILE_SELECT_HELPER_H_
12 #include "base/compiler_specific.h"
13 #include "base/gtest_prod_util.h"
14 #include "base/macros.h"
15 #include "base/scoped_observer.h"
16 #include "build/build_config.h"
17 #include "components/safe_browsing/buildflags.h"
18 #include "content/public/browser/browser_thread.h"
19 #include "content/public/browser/render_widget_host.h"
20 #include "content/public/browser/render_widget_host_observer.h"
21 #include "content/public/browser/web_contents_observer.h"
22 #include "net/base/directory_lister.h"
23 #include "third_party/blink/public/mojom/choosers/file_chooser.mojom.h"
24 #include "ui/shell_dialogs/select_file_dialog.h"
26 #if BUILDFLAG(FULL_SAFE_BROWSING)
27 #include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_dialog_delegate.h"
33 class FileSelectListener;
38 struct SelectedFileInfo;
41 // This class handles file-selection requests coming from renderer processes.
42 // It implements both the initialisation and listener functions for
43 // file-selection dialogs.
45 // Since FileSelectHelper listens to observations of a widget, it needs to live
46 // on and be destroyed on the UI thread. References to FileSelectHelper may be
47 // passed on to other threads.
48 class FileSelectHelper : public base::RefCountedThreadSafe<
50 content::BrowserThread::DeleteOnUIThread>,
51 public ui::SelectFileDialog::Listener,
52 public content::WebContentsObserver,
53 public content::RenderWidgetHostObserver,
54 private net::DirectoryLister::DirectoryListerDelegate {
56 // Show the file chooser dialog.
57 static void RunFileChooser(
58 content::RenderFrameHost* render_frame_host,
59 std::unique_ptr<content::FileSelectListener> listener,
60 const blink::mojom::FileChooserParams& params);
62 // Enumerates all the files in directory.
63 static void EnumerateDirectory(
64 content::WebContents* tab,
65 std::unique_ptr<content::FileSelectListener> listener,
66 const base::FilePath& path);
69 friend class base::RefCountedThreadSafe<FileSelectHelper>;
70 friend class base::DeleteHelper<FileSelectHelper>;
71 friend class FileSelectHelperContactsAndroid;
72 friend struct content::BrowserThread::DeleteOnThread<
73 content::BrowserThread::UI>;
75 FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest, IsAcceptTypeValid);
76 FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest, ZipPackage);
77 FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest, GetSanitizedFileName);
78 FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest, LastSelectedDirectory);
79 FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest,
80 DeepScanCompletionCallback_NoFiles);
81 FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest,
82 DeepScanCompletionCallback_OneOKFile);
83 FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest,
84 DeepScanCompletionCallback_TwoOKFiles);
85 FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest,
86 DeepScanCompletionCallback_TwoBadFiles);
87 FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest,
88 DeepScanCompletionCallback_OKBadFiles);
89 FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest, GetFileTypesFromAcceptType);
91 explicit FileSelectHelper(Profile* profile);
92 ~FileSelectHelper() override;
94 void RunFileChooser(content::RenderFrameHost* render_frame_host,
95 std::unique_ptr<content::FileSelectListener> listener,
96 blink::mojom::FileChooserParamsPtr params);
97 void GetFileTypesInThreadPool(blink::mojom::FileChooserParamsPtr params);
98 void GetSanitizedFilenameOnUIThread(
99 blink::mojom::FileChooserParamsPtr params);
100 #if BUILDFLAG(FULL_SAFE_BROWSING)
101 void CheckDownloadRequestWithSafeBrowsing(
102 const base::FilePath& default_path,
103 blink::mojom::FileChooserParamsPtr params);
104 void ProceedWithSafeBrowsingVerdict(const base::FilePath& default_path,
105 blink::mojom::FileChooserParamsPtr params,
106 bool allowed_by_safe_browsing);
108 void RunFileChooserOnUIThread(const base::FilePath& default_path,
109 blink::mojom::FileChooserParamsPtr params);
111 // Cleans up and releases this instance. This must be called after the last
112 // callback is received from the file chooser dialog.
113 void RunFileChooserEnd();
115 // SelectFileDialog::Listener overrides.
116 void FileSelected(const base::FilePath& path,
118 void* params) override;
119 void FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file,
121 void* params) override;
122 void MultiFilesSelected(const std::vector<base::FilePath>& files,
123 void* params) override;
124 void MultiFilesSelectedWithExtraInfo(
125 const std::vector<ui::SelectedFileInfo>& files,
126 void* params) override;
127 void FileSelectionCanceled(void* params) override;
129 // content::RenderWidgetHostObserver overrides.
130 void RenderWidgetHostDestroyed(
131 content::RenderWidgetHost* widget_host) override;
133 // content::WebContentsObserver overrides.
134 void RenderFrameHostChanged(content::RenderFrameHost* old_host,
135 content::RenderFrameHost* new_host) override;
136 void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override;
137 void WebContentsDestroyed() override;
139 void EnumerateDirectoryImpl(
140 content::WebContents* tab,
141 std::unique_ptr<content::FileSelectListener> listener,
142 const base::FilePath& path);
144 // Kicks off a new directory enumeration.
145 void StartNewEnumeration(const base::FilePath& path);
147 // net::DirectoryLister::DirectoryListerDelegate overrides.
149 const net::DirectoryLister::DirectoryListerData& data) override;
150 void OnListDone(int error) override;
152 void LaunchConfirmationDialog(
153 const base::FilePath& path,
154 std::vector<ui::SelectedFileInfo> selected_files);
156 // Cleans up and releases this instance. This must be called after the last
157 // callback is received from the enumeration code.
158 void EnumerateDirectoryEnd();
160 #if defined(OS_MACOSX)
161 // Must be called from a MayBlock() task. Each selected file that is a package
162 // will be zipped, and the zip will be passed to the render view host in place
164 void ProcessSelectedFilesMac(const std::vector<ui::SelectedFileInfo>& files);
166 // Saves the paths of |zipped_files| for later deletion. Passes |files| to the
168 void ProcessSelectedFilesMacOnUIThread(
169 const std::vector<ui::SelectedFileInfo>& files,
170 const std::vector<base::FilePath>& zipped_files);
172 // Zips the package at |path| into a temporary destination. Returns the
173 // temporary destination, if the zip was successful. Otherwise returns an
175 static base::FilePath ZipPackage(const base::FilePath& path);
176 #endif // defined(OS_MACOSX)
178 // This function is the start of a call chain that may or may not be async
179 // depending on the platform and features enabled. The call to this method
180 // is made after the user has chosen the file(s) in the UI in order to
181 // process and filter the list before returning the final result to the
182 // caller. The call chain is as follows:
184 // ConvertToFileChooserFileInfoList: converts a vector of SelectedFileInfo
185 // into a vector of FileChooserFileInfoPtr and then calls
186 // PerformSafeBrowsingDeepScanIfNeeded(). On chromeos, the conversion is
187 // performed asynchronously.
189 // PerformSafeBrowsingDeepScanIfNeeded: if the deep scanning feature is
190 // enabled and it is determined by enterprise policy that scans are required,
191 // starts the scans and sets DeepScanCompletionCallback() as the async
192 // callback. If deep scanning is not enabled or is not supported on the
193 // platform, this function calls NotifyListenerAndEnd() directly.
195 // DeepScanCompletionCallback: processes the results of the deep scan. Any
196 // files that did not pass the scan are removed from the list. Ends by
197 // calling NotifyListenerAndEnd().
199 // NotifyListenerAndEnd: Informs the listener of the final list of files to
200 // use and performs any required cleanup.
202 // Because the state of the web contents may change at each asynchronous
203 // step, calls are make to AbortIfWebContentsDestroyed() to check if, for
204 // example, the tab has been closed or the contents navigated. In these
205 // cases the file selection is aborted and the state cleaned up.
206 void ConvertToFileChooserFileInfoList(
207 const std::vector<ui::SelectedFileInfo>& files);
209 // Checks to see if scans are required for the specified files.
210 void PerformSafeBrowsingDeepScanIfNeeded(
211 std::vector<blink::mojom::FileChooserFileInfoPtr> list);
213 #if BUILDFLAG(FULL_SAFE_BROWSING)
214 // Callback used to receive the results of a deep scan.
215 void DeepScanCompletionCallback(
216 std::vector<blink::mojom::FileChooserFileInfoPtr> list,
217 const safe_browsing::DeepScanningDialogDelegate::Data& data,
218 const safe_browsing::DeepScanningDialogDelegate::Result& result);
221 // Finish the PerformSafeBrowsingDeepScanIfNeeded() handling after the
222 // deep scanning checks have been performed. Deep scanning may change the
223 // list of files chosen by the user, so the list of files passed here may be
224 // a subset of of the files passed to
225 // PerformSafeBrowsingDeepScanIfNeeded().
226 void NotifyListenerAndEnd(
227 std::vector<blink::mojom::FileChooserFileInfoPtr> list);
229 // Schedules the deletion of the files in |temporary_files_| and clears the
231 void DeleteTemporaryFiles();
233 // Cleans up when the initiator of the file chooser is no longer valid.
236 // Calls RunFileChooserEnd() if the webcontents was destroyed. Returns true
237 // if the file chooser operation shouldn't proceed.
238 bool AbortIfWebContentsDestroyed();
240 void SetFileSelectListenerForTesting(
241 std::unique_ptr<content::FileSelectListener> listener);
243 void DontAbortOnMissingWebContentsForTesting();
245 // Helper method to get allowed extensions for select file dialog from
246 // the specified accept types as defined in the spec:
247 // http://whatwg.org/html/number-state.html#attr-input-accept
248 // |accept_types| contains only valid lowercased MIME types or file extensions
249 // beginning with a period (.).
250 static std::unique_ptr<ui::SelectFileDialog::FileTypeInfo>
251 GetFileTypesFromAcceptType(const std::vector<base::string16>& accept_types);
253 // Check the accept type is valid. It is expected to be all lower case with
255 static bool IsAcceptTypeValid(const std::string& accept_type);
257 // Get a sanitized filename suitable for use as a default filename. The
258 // suggested filename coming over the IPC may contain invalid characters or
259 // may result in a filename that's reserved on the current platform.
261 // If |suggested_path| is empty, the return value is also empty.
263 // If |suggested_path| is non-empty, but can't be safely converted to UTF-8,
264 // or is entirely lost during the sanitization process (e.g. because it
265 // consists entirely of invalid characters), it's replaced with a default
268 // Otherwise, returns |suggested_path| with any invalid characters will be
269 // replaced with a suitable replacement character.
270 static base::FilePath GetSanitizedFileName(
271 const base::FilePath& suggested_path);
273 // Profile used to set/retrieve the last used directory.
276 // The RenderFrameHost and WebContents for the page showing a file dialog
277 // (may only be one such dialog).
278 content::RenderFrameHost* render_frame_host_;
279 content::WebContents* web_contents_;
281 // |listener_| receives the result of the FileSelectHelper.
282 std::unique_ptr<content::FileSelectListener> listener_;
284 // Dialog box used for choosing files to upload from file form fields.
285 scoped_refptr<ui::SelectFileDialog> select_file_dialog_;
286 std::unique_ptr<ui::SelectFileDialog::FileTypeInfo> select_file_types_;
288 // The type of file dialog last shown. This is SELECT_NONE if an
289 // instance is created through the public EnumerateDirectory().
290 ui::SelectFileDialog::Type dialog_type_;
292 // The mode of file dialog last shown.
293 blink::mojom::FileChooserParams::Mode dialog_mode_;
295 // The enumeration root directory for EnumerateDirectory() and
296 // RunFileChooser with kUploadFolder.
297 base::FilePath base_dir_;
299 // Maintain an active directory enumeration. These could come from the file
300 // select dialog or from drag-and-drop of directories. There could not be
301 // more than one going on at a time.
302 struct ActiveDirectoryEnumeration;
303 std::unique_ptr<ActiveDirectoryEnumeration> directory_enumeration_;
305 ScopedObserver<content::RenderWidgetHost, content::RenderWidgetHostObserver>
308 // Temporary files only used on OSX. This class is responsible for deleting
309 // these files when they are no longer needed.
310 std::vector<base::FilePath> temporary_files_;
312 // Set to false in unit tests since there is no WebContents.
313 bool abort_on_missing_web_contents_in_tests_ = true;
315 DISALLOW_COPY_AND_ASSIGN(FileSelectHelper);
318 #endif // CHROME_BROWSER_FILE_SELECT_HELPER_H_