Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(523)

Side by Side Diff: chrome/browser/extensions/api/file_system/chrome_file_system_delegate.cc

Issue 2937753002: test
Patch Set: Created 3 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright 2017 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/extensions/api/file_system/file_system_api.h" 5 #include "chrome/browser/extensions/api/file_system/chrome_file_system_delegate. h"
6 6
7 #include <stddef.h>
8
9 #include <memory>
10 #include <set>
11 #include <utility> 7 #include <utility>
12 #include <vector> 8 #include <vector>
13 9
14 #include "apps/saved_files_service.h" 10 #include "apps/saved_files_service_delegate_impl.h"
15 #include "base/bind.h" 11 #include "base/bind.h"
12 #include "base/callback.h"
16 #include "base/files/file_path.h" 13 #include "base/files/file_path.h"
17 #include "base/files/file_util.h" 14 #include "base/logging.h"
18 #include "base/macros.h"
19 #include "base/memory/ptr_util.h" 15 #include "base/memory/ptr_util.h"
20 #include "base/path_service.h" 16 #include "base/path_service.h"
21 #include "base/strings/string_util.h" 17 #include "base/strings/string16.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/strings/sys_string_conversions.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/task_scheduler/post_task.h"
26 #include "base/value_conversions.h"
27 #include "base/values.h"
28 #include "build/build_config.h"
29 #include "chrome/browser/platform_util.h" 18 #include "chrome/browser/platform_util.h"
30 #include "chrome/browser/profiles/profile.h" 19 #include "chrome/browser/profiles/profile.h"
31 #include "chrome/browser/ui/apps/directory_access_confirmation_dialog.h" 20 #include "chrome/browser/ui/apps/directory_access_confirmation_dialog.h"
32 #include "chrome/browser/ui/chrome_select_file_policy.h" 21 #include "chrome/browser/ui/chrome_select_file_policy.h"
33 #include "chrome/common/chrome_paths.h" 22 #include "chrome/common/chrome_paths.h"
34 #include "chrome/common/extensions/api/file_system.h"
35 #include "chrome/grit/generated_resources.h" 23 #include "chrome/grit/generated_resources.h"
36 #include "content/public/browser/browser_thread.h" 24 #include "content/public/browser/browser_context.h"
37 #include "content/public/browser/child_process_security_policy.h" 25 #include "content/public/browser/child_process_security_policy.h"
38 #include "content/public/browser/render_frame_host.h" 26 #include "content/public/browser/render_frame_host.h"
39 #include "content/public/browser/render_process_host.h" 27 #include "content/public/browser/render_process_host.h"
40 #include "content/public/browser/storage_partition.h" 28 #include "content/public/browser/storage_partition.h"
41 #include "content/public/browser/web_contents.h" 29 #include "content/public/browser/web_contents.h"
42 #include "extensions/browser/api/file_handlers/app_file_handler_util.h" 30 #include "extensions/browser/api/file_handlers/app_file_handler_util.h"
43 #include "extensions/browser/app_window/app_window.h" 31 #include "extensions/browser/api/file_system/saved_files_service_delegate.h"
44 #include "extensions/browser/app_window/app_window_registry.h" 32 #include "extensions/browser/extension_function.h"
45 #include "extensions/browser/extension_prefs.h" 33 #include "extensions/browser/extension_prefs.h"
46 #include "extensions/browser/extension_system.h" 34 #include "extensions/browser/extension_system.h"
47 #include "extensions/browser/extension_util.h" 35 #include "extensions/browser/extension_util.h"
48 #include "extensions/browser/granted_file_entry.h" 36 #include "extensions/common/api/file_system.h"
49 #include "extensions/browser/path_util.h" 37 #include "extensions/common/extension.h"
50 #include "extensions/common/permissions/api_permission.h"
51 #include "extensions/common/permissions/permissions_data.h"
52 #include "net/base/mime_util.h"
53 #include "storage/browser/fileapi/external_mount_points.h" 38 #include "storage/browser/fileapi/external_mount_points.h"
54 #include "storage/browser/fileapi/file_system_operation_runner.h"
55 #include "storage/browser/fileapi/isolated_context.h" 39 #include "storage/browser/fileapi/isolated_context.h"
56 #include "storage/common/fileapi/file_system_types.h" 40 #include "storage/common/fileapi/file_system_types.h"
57 #include "storage/common/fileapi/file_system_util.h" 41 #include "storage/common/fileapi/file_system_util.h"
58 #include "ui/base/l10n/l10n_util.h"
59 #include "ui/base/ui_base_types.h"
60 #include "ui/shell_dialogs/select_file_dialog.h" 42 #include "ui/shell_dialogs/select_file_dialog.h"
61 #include "ui/shell_dialogs/selected_file_info.h" 43 #include "ui/shell_dialogs/select_file_policy.h"
62 44
63 #if defined(OS_MACOSX) 45 #if defined(OS_MACOSX)
64 #include <CoreFoundation/CoreFoundation.h> 46 #include <CoreFoundation/CoreFoundation.h>
65 #include "base/mac/foundation_util.h" 47 #include "base/mac/foundation_util.h"
66 #endif 48 #endif
67 49
68 #if defined(OS_CHROMEOS) 50 #if defined(OS_CHROMEOS)
69 #include "base/strings/string16.h"
70 #include "chrome/browser/chromeos/file_manager/filesystem_api_util.h"
71 #include "chrome/browser/chromeos/file_manager/volume_manager.h" 51 #include "chrome/browser/chromeos/file_manager/volume_manager.h"
72 #include "extensions/browser/event_router.h" 52 #include "extensions/browser/event_router.h"
73 #include "extensions/browser/extension_registry.h" 53 #include "extensions/browser/extension_registry.h"
74 #include "extensions/common/constants.h" 54 #include "extensions/common/constants.h"
75 #include "url/url_constants.h" 55 #include "url/url_constants.h"
76 #endif 56 #endif
77 57
78 using apps::SavedFileEntry;
79 using apps::SavedFilesService;
80 using storage::IsolatedContext;
81
82 const char kInvalidCallingPage[] = "Invalid calling page. This function can't "
83 "be called from a background page.";
84 const char kUserCancelled[] = "User cancelled";
85 const char kWritableFileErrorFormat[] = "Error opening %s";
86 const char kRequiresFileSystemWriteError[] =
87 "Operation requires fileSystem.write permission";
88 const char kRequiresFileSystemDirectoryError[] =
89 "Operation requires fileSystem.directory permission";
90 const char kMultipleUnsupportedError[] =
91 "acceptsMultiple: true is only supported for 'openFile'";
92 const char kUnknownIdError[] = "Unknown id";
93
94 #if !defined(OS_CHROMEOS)
95 const char kNotSupportedOnCurrentPlatformError[] =
96 "Operation not supported on the current platform.";
97 #else
98 const char kNotSupportedOnNonKioskSessionError[] =
99 "Operation only supported for kiosk apps running in a kiosk session.";
100 const char kVolumeNotFoundError[] = "Volume not found.";
101 const char kSecurityError[] = "Security error.";
102 const char kConsentImpossible[] =
103 "Impossible to ask for user consent as there is no app window visible.";
104 #endif
105
106 namespace extensions { 58 namespace extensions {
107 59
108 namespace file_system = api::file_system; 60 namespace file_system = api::file_system;
109 namespace ChooseEntry = file_system::ChooseEntry; 61
62 #if defined(OS_CHROMEOS)
63 using file_system_api::ConsentProvider;
64 using file_system_api::ConsentProviderDelegate;
110 65
111 namespace { 66 namespace {
112 67
113 bool g_skip_picker_for_test = false; 68 const char kConsentImpossible[] =
114 bool g_use_suggested_path_for_test = false; 69 "Impossible to ask for user consent as there is no app window visible.";
115 base::FilePath* g_path_to_be_picked_for_test; 70 const char kNotSupportedOnNonKioskSessionError[] =
116 std::vector<base::FilePath>* g_paths_to_be_picked_for_test; 71 "Operation only supported for kiosk apps running in a kiosk session.";
117 bool g_skip_directory_confirmation_for_test = false; 72 const char kRequiresFileSystemWriteError[] =
118 bool g_allow_directory_access_for_test = false; 73 "Operation requires fileSystem.write permission";
74 const char kSecurityError[] = "Security error.";
75 const char kVolumeNotFoundError[] = "Volume not found.";
119 76
120 // Expand the mime-types and extensions provided in an AcceptOption, returning
121 // them within the passed extension vector. Returns false if no valid types
122 // were found.
123 bool GetFileTypesFromAcceptOption(
124 const file_system::AcceptOption& accept_option,
125 std::vector<base::FilePath::StringType>* extensions,
126 base::string16* description) {
127 std::set<base::FilePath::StringType> extension_set;
128 int description_id = 0;
129
130 if (accept_option.mime_types.get()) {
131 std::vector<std::string>* list = accept_option.mime_types.get();
132 bool valid_type = false;
133 for (std::vector<std::string>::const_iterator iter = list->begin();
134 iter != list->end(); ++iter) {
135 std::vector<base::FilePath::StringType> inner;
136 std::string accept_type = base::ToLowerASCII(*iter);
137 net::GetExtensionsForMimeType(accept_type, &inner);
138 if (inner.empty())
139 continue;
140
141 if (valid_type)
142 description_id = 0; // We already have an accept type with label; if
143 // we find another, give up and use the default.
144 else if (accept_type == "image/*")
145 description_id = IDS_IMAGE_FILES;
146 else if (accept_type == "audio/*")
147 description_id = IDS_AUDIO_FILES;
148 else if (accept_type == "video/*")
149 description_id = IDS_VIDEO_FILES;
150
151 extension_set.insert(inner.begin(), inner.end());
152 valid_type = true;
153 }
154 }
155
156 if (accept_option.extensions.get()) {
157 std::vector<std::string>* list = accept_option.extensions.get();
158 for (std::vector<std::string>::const_iterator iter = list->begin();
159 iter != list->end(); ++iter) {
160 std::string extension = base::ToLowerASCII(*iter);
161 #if defined(OS_WIN)
162 extension_set.insert(base::UTF8ToWide(*iter));
163 #else
164 extension_set.insert(*iter);
165 #endif
166 }
167 }
168
169 extensions->assign(extension_set.begin(), extension_set.end());
170 if (extensions->empty())
171 return false;
172
173 if (accept_option.description.get())
174 *description = base::UTF8ToUTF16(*accept_option.description);
175 else if (description_id)
176 *description = l10n_util::GetStringUTF16(description_id);
177
178 return true;
179 }
180
181 // Key for the path of the directory of the file last chosen by the user in
182 // response to a chrome.fileSystem.chooseEntry() call.
183 const char kLastChooseEntryDirectory[] = "last_choose_file_directory";
184
185 const int kGraylistedPaths[] = {
186 base::DIR_HOME,
187 #if defined(OS_WIN)
188 base::DIR_PROGRAM_FILES,
189 base::DIR_PROGRAM_FILESX86,
190 base::DIR_WINDOWS,
191 #endif
192 };
193
194 typedef base::Callback<void(std::unique_ptr<base::File::Info>)>
195 FileInfoOptCallback;
196
197 // Passes optional file info to the UI thread depending on |result| and |info|.
198 void PassFileInfoToUIThread(const FileInfoOptCallback& callback,
199 base::File::Error result,
200 const base::File::Info& info) {
201 DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
202 std::unique_ptr<base::File::Info> file_info(
203 result == base::File::FILE_OK ? new base::File::Info(info) : NULL);
204 content::BrowserThread::PostTask(
205 content::BrowserThread::UI, FROM_HERE,
206 base::BindOnce(callback, base::Passed(&file_info)));
207 }
208
209 // Gets a WebContents instance handle for a platform app hosted in
210 // |render_frame_host|. If not found, then returns NULL.
211 content::WebContents* GetWebContentsForRenderFrameHost(
212 Profile* profile,
213 content::RenderFrameHost* render_frame_host) {
214 content::WebContents* web_contents =
215 content::WebContents::FromRenderFrameHost(render_frame_host);
216 // Check if there is an app window associated with the web contents; if not,
217 // return null.
218 return AppWindowRegistry::Get(profile)
219 ->GetAppWindowForWebContents(web_contents)
220 ? web_contents
221 : nullptr;
222 }
223
224 #if defined(OS_CHROMEOS)
225 // Fills a list of volumes mounted in the system. 77 // Fills a list of volumes mounted in the system.
226 void FillVolumeList(Profile* profile, 78 void FillVolumeList(content::BrowserContext* browser_context,
227 std::vector<api::file_system::Volume>* result) { 79 std::vector<file_system::Volume>* result) {
228 file_manager::VolumeManager* const volume_manager = 80 file_manager::VolumeManager* const volume_manager =
229 file_manager::VolumeManager::Get(profile); 81 file_manager::VolumeManager::Get(browser_context);
230 DCHECK(volume_manager); 82 DCHECK(volume_manager);
231 83
232 const auto& volume_list = volume_manager->GetVolumeList(); 84 const auto& volume_list = volume_manager->GetVolumeList();
233 // Convert volume_list to result_volume_list. 85 // Convert volume_list to result_volume_list.
234 for (const auto& volume : volume_list) { 86 for (const auto& volume : volume_list) {
235 api::file_system::Volume result_volume; 87 file_system::Volume result_volume;
236 result_volume.volume_id = volume->volume_id(); 88 result_volume.volume_id = volume->volume_id();
237 result_volume.writable = !volume->is_read_only(); 89 result_volume.writable = !volume->is_read_only();
238 result->push_back(std::move(result_volume)); 90 result->push_back(std::move(result_volume));
239 } 91 }
240 } 92 }
241 #endif
242 93
243 } // namespace 94 } // namespace
244 95
245 namespace file_system_api { 96 namespace file_system_api {
246 97
247 base::FilePath GetLastChooseEntryDirectory(const ExtensionPrefs* prefs, 98 void DispatchVolumeListChangeEvent(content::BrowserContext* browser_context) {
248 const std::string& extension_id) { 99 DCHECK(browser_context);
249 base::FilePath path; 100 EventRouter* const event_router = EventRouter::Get(browser_context);
250 std::string string_path;
251 if (prefs->ReadPrefAsString(extension_id,
252 kLastChooseEntryDirectory,
253 &string_path)) {
254 path = base::FilePath::FromUTF8Unsafe(string_path);
255 }
256 return path;
257 }
258
259 void SetLastChooseEntryDirectory(ExtensionPrefs* prefs,
260 const std::string& extension_id,
261 const base::FilePath& path) {
262 prefs->UpdateExtensionPref(extension_id, kLastChooseEntryDirectory,
263 base::CreateFilePathValue(path));
264 }
265
266 #if defined(OS_CHROMEOS)
267 void DispatchVolumeListChangeEvent(Profile* profile) {
268 DCHECK(profile);
269 EventRouter* const event_router = EventRouter::Get(profile);
270 if (!event_router) // Possible on shutdown. 101 if (!event_router) // Possible on shutdown.
271 return; 102 return;
272 103
273 ExtensionRegistry* const registry = ExtensionRegistry::Get(profile); 104 ExtensionRegistry* const registry = ExtensionRegistry::Get(browser_context);
274 if (!registry) // Possible on shutdown. 105 if (!registry) // Possible on shutdown.
275 return; 106 return;
276 107
277 ConsentProviderDelegate consent_provider_delegate(profile, nullptr); 108 ConsentProviderDelegate consent_provider_delegate(
109 Profile::FromBrowserContext(browser_context));
278 ConsentProvider consent_provider(&consent_provider_delegate); 110 ConsentProvider consent_provider(&consent_provider_delegate);
279 api::file_system::VolumeListChangedEvent event_args; 111 file_system::VolumeListChangedEvent event_args;
280 FillVolumeList(profile, &event_args.volumes); 112 FillVolumeList(browser_context, &event_args.volumes);
281 for (const auto& extension : registry->enabled_extensions()) { 113 for (const auto& extension : registry->enabled_extensions()) {
282 if (!consent_provider.IsGrantable(*extension.get())) 114 if (!consent_provider.IsGrantable(*extension.get()))
283 continue; 115 continue;
284 event_router->DispatchEventToExtension( 116 event_router->DispatchEventToExtension(
285 extension->id(), 117 extension->id(),
286 base::MakeUnique<Event>( 118 base::MakeUnique<Event>(
287 events::FILE_SYSTEM_ON_VOLUME_LIST_CHANGED, 119 events::FILE_SYSTEM_ON_VOLUME_LIST_CHANGED,
288 api::file_system::OnVolumeListChanged::kEventName, 120 file_system::OnVolumeListChanged::kEventName,
289 api::file_system::OnVolumeListChanged::Create(event_args))); 121 file_system::OnVolumeListChanged::Create(event_args)));
290 } 122 }
291 } 123 }
292 #endif
293 124
294 } // namespace file_system_api 125 } // namespace file_system_api
126 #endif // defined(OS_CHROMEOS)
295 127
296 #if defined(OS_CHROMEOS) 128 ChromeFileSystemDelegate::ChromeFileSystemDelegate() {}
297 using file_system_api::ConsentProvider;
298 #endif
299 129
300 ExtensionFunction::ResponseAction FileSystemGetDisplayPathFunction::Run() { 130 ChromeFileSystemDelegate::~ChromeFileSystemDelegate() {}
301 std::string filesystem_name;
302 std::string filesystem_path;
303 EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &filesystem_name));
304 EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &filesystem_path));
305 131
306 base::FilePath file_path; 132 base::FilePath ChromeFileSystemDelegate::GetDefaultDirectory() {
307 std::string error; 133 base::FilePath documents_dir;
308 if (!app_file_handler_util::ValidateFileEntryAndGetPath( 134 PathService::Get(chrome::DIR_USER_DOCUMENTS, &documents_dir);
309 filesystem_name, filesystem_path, 135 return documents_dir;
310 render_frame_host()->GetProcess()->GetID(), &file_path, &error)) {
311 return RespondNow(Error(error));
312 }
313
314 file_path = path_util::PrettifyPath(file_path);
315 return RespondNow(
316 OneArgument(base::MakeUnique<base::Value>(file_path.value())));
317 } 136 }
318 137
319 FileSystemEntryFunction::FileSystemEntryFunction() 138 std::unique_ptr<ui::SelectFilePolicy>
320 : multiple_(false), is_directory_(false) {} 139 ChromeFileSystemDelegate::CreateSelectFilePolicy(
321 140 content::WebContents* web_contents) {
322 void FileSystemEntryFunction::PrepareFilesForWritableApp( 141 return base::MakeUnique<ChromeSelectFilePolicy>(web_contents);
323 const std::vector<base::FilePath>& paths) {
324 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
325 // TODO(cmihail): Path directory set should be initialized only with the
326 // paths that are actually directories, but for now we will consider
327 // all paths directories in case is_directory_ is true, otherwise
328 // all paths files, as this was the previous logic.
329 std::set<base::FilePath> path_directory_set_ =
330 is_directory_ ? std::set<base::FilePath>(paths.begin(), paths.end())
331 : std::set<base::FilePath>{};
332 app_file_handler_util::PrepareFilesForWritableApp(
333 paths, GetProfile(), path_directory_set_,
334 base::Bind(&FileSystemEntryFunction::RegisterFileSystemsAndSendResponse,
335 this, paths),
336 base::Bind(&FileSystemEntryFunction::HandleWritableFileError, this));
337 } 142 }
338 143
339 void FileSystemEntryFunction::RegisterFileSystemsAndSendResponse( 144 scoped_refptr<ui::SelectFileDialog>
340 const std::vector<base::FilePath>& paths) { 145 ChromeFileSystemDelegate::CreateSelectFileDialog(
341 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); 146 ui::SelectFileDialog::Listener* listener,
342 if (!render_frame_host()) 147 std::unique_ptr<ui::SelectFilePolicy> policy) {
343 return; 148 // SelectFileDialog will take ownership of |policy|.
344 149 return ui::SelectFileDialog::Create(listener, policy.release());
345 std::unique_ptr<base::DictionaryValue> result = CreateResult();
346 for (const auto& path : paths)
347 AddEntryToResult(path, std::string(), result.get());
348 SetResult(std::move(result));
349 SendResponse(true);
350 } 150 }
351 151
352 std::unique_ptr<base::DictionaryValue> FileSystemEntryFunction::CreateResult() { 152 void ChromeFileSystemDelegate::ShowSelectFileDialogForWebContents(
353 std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue()); 153 scoped_refptr<ui::SelectFileDialog> dialog,
354 result->Set("entries", base::MakeUnique<base::ListValue>()); 154 content::WebContents* web_contents,
355 result->SetBoolean("multiple", multiple_); 155 ui::SelectFileDialog::Type type,
356 return result; 156 const base::FilePath& default_path,
157 const ui::SelectFileDialog::FileTypeInfo* file_types) {
158 gfx::NativeWindow owning_window =
159 web_contents ? platform_util::GetTopLevel(web_contents->GetNativeView())
160 : nullptr;
161 dialog->SelectFile(type, base::string16(), default_path, file_types, 0,
162 base::FilePath::StringType(), owning_window, nullptr);
357 } 163 }
358 164
359 void FileSystemEntryFunction::AddEntryToResult(const base::FilePath& path, 165 void ChromeFileSystemDelegate::ConfirmSensitiveDirectoryAccess(
360 const std::string& id_override, 166 bool writable,
361 base::DictionaryValue* result) { 167 const base::string16& app_name,
362 GrantedFileEntry file_entry = app_file_handler_util::CreateFileEntry( 168 content::WebContents* web_contents,
363 GetProfile(), 169 const base::Closure& on_accept,
364 extension(), 170 const base::Closure& on_cancel) {
365 render_frame_host()->GetProcess()->GetID(), 171 CreateDirectoryAccessConfirmationDialog(writable, app_name, web_contents,
366 path, 172 on_accept, on_cancel);
367 is_directory_);
368 base::ListValue* entries;
369 bool success = result->GetList("entries", &entries);
370 DCHECK(success);
371
372 std::unique_ptr<base::DictionaryValue> entry(new base::DictionaryValue());
373 entry->SetString("fileSystemId", file_entry.filesystem_id);
374 entry->SetString("baseName", file_entry.registered_name);
375 if (id_override.empty())
376 entry->SetString("id", file_entry.id);
377 else
378 entry->SetString("id", id_override);
379 entry->SetBoolean("isDirectory", is_directory_);
380 entries->Append(std::move(entry));
381 } 173 }
382 174
383 void FileSystemEntryFunction::HandleWritableFileError( 175 bool ChromeFileSystemDelegate::GetDescriptionIdForAcceptType(
384 const base::FilePath& error_path) { 176 const std::string& accept_type,
385 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); 177 int* description_id) {
386 error_ = base::StringPrintf(kWritableFileErrorFormat, 178 if (accept_type == "image/*")
387 error_path.BaseName().AsUTF8Unsafe().c_str()); 179 *description_id = IDS_IMAGE_FILES;
388 SendResponse(false); 180 else if (accept_type == "audio/*")
389 } 181 *description_id = IDS_AUDIO_FILES;
390 182 else if (accept_type == "video/*")
391 bool FileSystemGetWritableEntryFunction::RunAsync() { 183 *description_id = IDS_VIDEO_FILES;
392 std::string filesystem_name; 184 else
393 std::string filesystem_path;
394 EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &filesystem_name));
395 EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &filesystem_path));
396
397 if (!app_file_handler_util::HasFileSystemWritePermission(extension_.get())) {
398 error_ = kRequiresFileSystemWriteError;
399 return false; 185 return false;
400 }
401
402 if (!app_file_handler_util::ValidateFileEntryAndGetPath(
403 filesystem_name, filesystem_path,
404 render_frame_host()->GetProcess()->GetID(), &path_, &error_))
405 return false;
406
407 base::PostTaskWithTraitsAndReply(
408 FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
409 base::BindOnce(&FileSystemGetWritableEntryFunction::SetIsDirectoryAsync,
410 this),
411 base::BindOnce(
412 &FileSystemGetWritableEntryFunction::CheckPermissionAndSendResponse,
413 this));
414 return true; 186 return true;
415 } 187 }
416 188
417 void FileSystemGetWritableEntryFunction::CheckPermissionAndSendResponse() { 189 #if defined(OS_CHROMEOS)
418 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); 190 bool ChromeFileSystemDelegate::IsGrantable(
419 if (is_directory_ && 191 content::BrowserContext* browser_context,
420 !extension_->permissions_data()->HasAPIPermission( 192 content::RenderFrameHost* render_frame_host,
421 APIPermission::kFileSystemDirectory)) { 193 const Extension& extension) {
422 error_ = kRequiresFileSystemDirectoryError; 194 // Only kiosk apps in kiosk sessions can use this API.
423 SendResponse(false); 195 // Additionally it is enabled for whitelisted component extensions and apps.
424 } 196 ConsentProviderDelegate consent_provider_delegate(
425 std::vector<base::FilePath> paths; 197 Profile::FromBrowserContext(browser_context));
426 paths.push_back(path_); 198 ConsentProvider consent_provider(&consent_provider_delegate);
427 PrepareFilesForWritableApp(paths); 199 return consent_provider.IsGrantable(extension);
428 } 200 }
429 201
430 void FileSystemGetWritableEntryFunction::SetIsDirectoryAsync() { 202 void ChromeFileSystemDelegate::RequestFileSystem(
431 if (base::DirectoryExists(path_)) { 203 content::BrowserContext* browser_context,
432 is_directory_ = true; 204 scoped_refptr<UIThreadExtensionFunction> requester,
433 } 205 const Extension& extension,
434 } 206 std::string volume_id,
207 bool writable,
208 const FileSystemCallback& success_callback,
209 const ErrorCallback& error_callback) {
210 ConsentProviderDelegate consent_provider_delegate(
211 Profile::FromBrowserContext(browser_context));
212 ConsentProvider consent_provider(&consent_provider_delegate);
435 213
436 ExtensionFunction::ResponseAction FileSystemIsWritableEntryFunction::Run() { 214 if (!consent_provider.IsGrantable(extension)) {
437 std::string filesystem_name; 215 error_callback.Run(kNotSupportedOnNonKioskSessionError);
438 std::string filesystem_path;
439 EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &filesystem_name));
440 EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &filesystem_path));
441
442 std::string filesystem_id;
443 if (!storage::CrackIsolatedFileSystemName(filesystem_name, &filesystem_id))
444 return RespondNow(Error(app_file_handler_util::kInvalidParameters));
445
446 content::ChildProcessSecurityPolicy* policy =
447 content::ChildProcessSecurityPolicy::GetInstance();
448 int renderer_id = render_frame_host()->GetProcess()->GetID();
449 bool is_writable = policy->CanReadWriteFileSystem(renderer_id,
450 filesystem_id);
451
452 return RespondNow(OneArgument(base::MakeUnique<base::Value>(is_writable)));
453 }
454
455 // Handles showing a dialog to the user to ask for the filename for a file to
456 // save or open.
457 class FileSystemChooseEntryFunction::FilePicker
458 : public ui::SelectFileDialog::Listener {
459 public:
460 FilePicker(FileSystemChooseEntryFunction* function,
461 content::WebContents* web_contents,
462 const base::FilePath& suggested_name,
463 const ui::SelectFileDialog::FileTypeInfo& file_type_info,
464 ui::SelectFileDialog::Type picker_type)
465 : function_(function) {
466 select_file_dialog_ = ui::SelectFileDialog::Create(
467 this, new ChromeSelectFilePolicy(web_contents));
468 gfx::NativeWindow owning_window = web_contents ?
469 platform_util::GetTopLevel(web_contents->GetNativeView()) :
470 NULL;
471
472 if (g_skip_picker_for_test) {
473 if (g_use_suggested_path_for_test) {
474 content::BrowserThread::PostTask(
475 content::BrowserThread::UI, FROM_HERE,
476 base::BindOnce(
477 &FileSystemChooseEntryFunction::FilePicker::FileSelected,
478 base::Unretained(this), suggested_name, 1,
479 static_cast<void*>(NULL)));
480 } else if (g_path_to_be_picked_for_test) {
481 content::BrowserThread::PostTask(
482 content::BrowserThread::UI, FROM_HERE,
483 base::BindOnce(
484 &FileSystemChooseEntryFunction::FilePicker::FileSelected,
485 base::Unretained(this), *g_path_to_be_picked_for_test, 1,
486 static_cast<void*>(NULL)));
487 } else if (g_paths_to_be_picked_for_test) {
488 content::BrowserThread::PostTask(
489 content::BrowserThread::UI, FROM_HERE,
490 base::BindOnce(
491 &FileSystemChooseEntryFunction::FilePicker::MultiFilesSelected,
492 base::Unretained(this), *g_paths_to_be_picked_for_test,
493 static_cast<void*>(NULL)));
494 } else {
495 content::BrowserThread::PostTask(
496 content::BrowserThread::UI, FROM_HERE,
497 base::BindOnce(&FileSystemChooseEntryFunction::FilePicker::
498 FileSelectionCanceled,
499 base::Unretained(this), static_cast<void*>(NULL)));
500 }
501 return;
502 }
503
504 select_file_dialog_->SelectFile(picker_type,
505 base::string16(),
506 suggested_name,
507 &file_type_info,
508 0,
509 base::FilePath::StringType(),
510 owning_window,
511 NULL);
512 }
513
514 ~FilePicker() override {}
515
516 private:
517 // ui::SelectFileDialog::Listener implementation.
518 void FileSelected(const base::FilePath& path,
519 int index,
520 void* params) override {
521 std::vector<base::FilePath> paths;
522 paths.push_back(path);
523 MultiFilesSelected(paths, params);
524 }
525
526 void FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file,
527 int index,
528 void* params) override {
529 // Normally, file.local_path is used because it is a native path to the
530 // local read-only cached file in the case of remote file system like
531 // Chrome OS's Google Drive integration. Here, however, |file.file_path| is
532 // necessary because we need to create a FileEntry denoting the remote file,
533 // not its cache. On other platforms than Chrome OS, they are the same.
534 //
535 // TODO(kinaba): remove this, once after the file picker implements proper
536 // switch of the path treatment depending on the |allowed_paths|.
537 FileSelected(file.file_path, index, params);
538 }
539
540 void MultiFilesSelected(const std::vector<base::FilePath>& files,
541 void* params) override {
542 function_->FilesSelected(files);
543 delete this;
544 }
545
546 void MultiFilesSelectedWithExtraInfo(
547 const std::vector<ui::SelectedFileInfo>& files,
548 void* params) override {
549 std::vector<base::FilePath> paths;
550 for (std::vector<ui::SelectedFileInfo>::const_iterator it = files.begin();
551 it != files.end(); ++it) {
552 paths.push_back(it->file_path);
553 }
554 MultiFilesSelected(paths, params);
555 }
556
557 void FileSelectionCanceled(void* params) override {
558 function_->FileSelectionCanceled();
559 delete this;
560 }
561
562 scoped_refptr<ui::SelectFileDialog> select_file_dialog_;
563 scoped_refptr<FileSystemChooseEntryFunction> function_;
564
565 DISALLOW_COPY_AND_ASSIGN(FilePicker);
566 };
567
568 void FileSystemChooseEntryFunction::ShowPicker(
569 const ui::SelectFileDialog::FileTypeInfo& file_type_info,
570 ui::SelectFileDialog::Type picker_type) {
571 // TODO(asargent/benwells) - As a short term remediation for crbug.com/179010
572 // we're adding the ability for a whitelisted extension to use this API since
573 // chrome.fileBrowserHandler.selectFile is ChromeOS-only. Eventually we'd
574 // like a better solution and likely this code will go back to being
575 // platform-app only.
576 content::WebContents* const web_contents =
577 extension_->is_platform_app()
578 ? GetWebContentsForRenderFrameHost(GetProfile(), render_frame_host())
579 : GetAssociatedWebContents();
580 if (!web_contents) {
581 error_ = kInvalidCallingPage;
582 SendResponse(false);
583 return; 216 return;
584 } 217 }
585 218
586 // The file picker will hold a reference to this function instance, preventing 219 using file_manager::VolumeManager;
587 // its destruction (and subsequent sending of the function response) until the 220 using file_manager::Volume;
588 // user has selected a file or cancelled the picker. At that point, the picker 221 VolumeManager* const volume_manager = VolumeManager::Get(browser_context);
589 // will delete itself, which will also free the function instance. 222 DCHECK(volume_manager);
590 new FilePicker(
591 this, web_contents, initial_path_, file_type_info, picker_type);
592 }
593 223
594 // static 224 if (writable &&
595 void FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest( 225 !app_file_handler_util::HasFileSystemWritePermission(&extension)) {
596 base::FilePath* path) { 226 error_callback.Run(kRequiresFileSystemWriteError);
597 g_skip_picker_for_test = true;
598 g_use_suggested_path_for_test = false;
599 g_path_to_be_picked_for_test = path;
600 g_paths_to_be_picked_for_test = NULL;
601 }
602
603 void FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathsForTest(
604 std::vector<base::FilePath>* paths) {
605 g_skip_picker_for_test = true;
606 g_use_suggested_path_for_test = false;
607 g_paths_to_be_picked_for_test = paths;
608 }
609
610 // static
611 void FileSystemChooseEntryFunction::SkipPickerAndSelectSuggestedPathForTest() {
612 g_skip_picker_for_test = true;
613 g_use_suggested_path_for_test = true;
614 g_path_to_be_picked_for_test = NULL;
615 g_paths_to_be_picked_for_test = NULL;
616 }
617
618 // static
619 void FileSystemChooseEntryFunction::SkipPickerAndAlwaysCancelForTest() {
620 g_skip_picker_for_test = true;
621 g_use_suggested_path_for_test = false;
622 g_path_to_be_picked_for_test = NULL;
623 g_paths_to_be_picked_for_test = NULL;
624 }
625
626 // static
627 void FileSystemChooseEntryFunction::StopSkippingPickerForTest() {
628 g_skip_picker_for_test = false;
629 }
630
631 // static
632 void FileSystemChooseEntryFunction::SkipDirectoryConfirmationForTest() {
633 g_skip_directory_confirmation_for_test = true;
634 g_allow_directory_access_for_test = true;
635 }
636
637 // static
638 void FileSystemChooseEntryFunction::AutoCancelDirectoryConfirmationForTest() {
639 g_skip_directory_confirmation_for_test = true;
640 g_allow_directory_access_for_test = false;
641 }
642
643 // static
644 void FileSystemChooseEntryFunction::StopSkippingDirectoryConfirmationForTest() {
645 g_skip_directory_confirmation_for_test = false;
646 }
647
648 // static
649 void FileSystemChooseEntryFunction::RegisterTempExternalFileSystemForTest(
650 const std::string& name, const base::FilePath& path) {
651 // For testing on Chrome OS, where to deal with remote and local paths
652 // smoothly, all accessed paths need to be registered in the list of
653 // external mount points.
654 storage::ExternalMountPoints::GetSystemInstance()->RegisterFileSystem(
655 name,
656 storage::kFileSystemTypeNativeLocal,
657 storage::FileSystemMountOption(),
658 path);
659 }
660
661 void FileSystemChooseEntryFunction::FilesSelected(
662 const std::vector<base::FilePath>& paths) {
663 DCHECK(!paths.empty());
664 base::FilePath last_choose_directory;
665 if (is_directory_) {
666 last_choose_directory = paths[0];
667 } else {
668 last_choose_directory = paths[0].DirName();
669 }
670 file_system_api::SetLastChooseEntryDirectory(
671 ExtensionPrefs::Get(GetProfile()),
672 extension()->id(),
673 last_choose_directory);
674 if (is_directory_) {
675 // Get the WebContents for the app window to be the parent window of the
676 // confirmation dialog if necessary.
677 content::WebContents* const web_contents =
678 GetWebContentsForRenderFrameHost(GetProfile(), render_frame_host());
679 if (!web_contents) {
680 error_ = kInvalidCallingPage;
681 SendResponse(false);
682 return;
683 }
684
685 DCHECK_EQ(paths.size(), 1u);
686 bool non_native_path = false;
687 #if defined(OS_CHROMEOS)
688 non_native_path =
689 file_manager::util::IsUnderNonNativeLocalPath(GetProfile(), paths[0]);
690 #endif
691
692 base::PostTaskWithTraits(
693 FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
694 base::BindOnce(
695 &FileSystemChooseEntryFunction::ConfirmDirectoryAccessAsync, this,
696 non_native_path, paths, web_contents));
697 return; 227 return;
698 } 228 }
699 229
700 OnDirectoryAccessConfirmed(paths); 230 base::WeakPtr<file_manager::Volume> volume =
701 } 231 volume_manager->FindVolumeById(volume_id);
702 232 if (!volume.get()) {
703 void FileSystemChooseEntryFunction::FileSelectionCanceled() { 233 error_callback.Run(kVolumeNotFoundError);
704 error_ = kUserCancelled;
705 SendResponse(false);
706 }
707
708 void FileSystemChooseEntryFunction::ConfirmDirectoryAccessAsync(
709 bool non_native_path,
710 const std::vector<base::FilePath>& paths,
711 content::WebContents* web_contents) {
712 const base::FilePath check_path =
713 non_native_path ? paths[0] : base::MakeAbsoluteFilePath(paths[0]);
714 if (check_path.empty()) {
715 content::BrowserThread::PostTask(
716 content::BrowserThread::UI, FROM_HERE,
717 base::BindOnce(&FileSystemChooseEntryFunction::FileSelectionCanceled,
718 this));
719 return; 234 return;
720 } 235 }
721 236
722 for (size_t i = 0; i < arraysize(kGraylistedPaths); i++) {
723 base::FilePath graylisted_path;
724 if (PathService::Get(kGraylistedPaths[i], &graylisted_path) &&
725 (check_path == graylisted_path ||
726 check_path.IsParent(graylisted_path))) {
727 if (g_skip_directory_confirmation_for_test) {
728 if (g_allow_directory_access_for_test) {
729 break;
730 } else {
731 content::BrowserThread::PostTask(
732 content::BrowserThread::UI, FROM_HERE,
733 base::BindOnce(
734 &FileSystemChooseEntryFunction::FileSelectionCanceled, this));
735 }
736 return;
737 }
738
739 content::BrowserThread::PostTask(
740 content::BrowserThread::UI, FROM_HERE,
741 base::BindOnce(
742 CreateDirectoryAccessConfirmationDialog,
743 app_file_handler_util::HasFileSystemWritePermission(
744 extension_.get()),
745 base::UTF8ToUTF16(extension_->name()), web_contents,
746 base::Bind(
747 &FileSystemChooseEntryFunction::OnDirectoryAccessConfirmed,
748 this, paths),
749 base::Bind(&FileSystemChooseEntryFunction::FileSelectionCanceled,
750 this)));
751 return;
752 }
753 }
754
755 content::BrowserThread::PostTask(
756 content::BrowserThread::UI, FROM_HERE,
757 base::BindOnce(&FileSystemChooseEntryFunction::OnDirectoryAccessConfirmed,
758 this, paths));
759 }
760
761 void FileSystemChooseEntryFunction::OnDirectoryAccessConfirmed(
762 const std::vector<base::FilePath>& paths) {
763 if (app_file_handler_util::HasFileSystemWritePermission(extension_.get())) {
764 PrepareFilesForWritableApp(paths);
765 return;
766 }
767
768 // Don't need to check the file, it's for reading.
769 RegisterFileSystemsAndSendResponse(paths);
770 }
771
772 void FileSystemChooseEntryFunction::BuildFileTypeInfo(
773 ui::SelectFileDialog::FileTypeInfo* file_type_info,
774 const base::FilePath::StringType& suggested_extension,
775 const AcceptOptions* accepts,
776 const bool* acceptsAllTypes) {
777 file_type_info->include_all_files = true;
778 if (acceptsAllTypes)
779 file_type_info->include_all_files = *acceptsAllTypes;
780
781 bool need_suggestion = !file_type_info->include_all_files &&
782 !suggested_extension.empty();
783
784 if (accepts) {
785 for (const file_system::AcceptOption& option : *accepts) {
786 base::string16 description;
787 std::vector<base::FilePath::StringType> extensions;
788
789 if (!GetFileTypesFromAcceptOption(option, &extensions, &description))
790 continue; // No extensions were found.
791
792 file_type_info->extensions.push_back(extensions);
793 file_type_info->extension_description_overrides.push_back(description);
794
795 // If we still need to find suggested_extension, hunt for it inside the
796 // extensions returned from GetFileTypesFromAcceptOption.
797 if (need_suggestion && std::find(extensions.begin(),
798 extensions.end(), suggested_extension) != extensions.end()) {
799 need_suggestion = false;
800 }
801 }
802 }
803
804 // If there's nothing in our accepted extension list or we couldn't find the
805 // suggested extension required, then default to accepting all types.
806 if (file_type_info->extensions.empty() || need_suggestion)
807 file_type_info->include_all_files = true;
808 }
809
810 void FileSystemChooseEntryFunction::BuildSuggestion(
811 const std::string *opt_name,
812 base::FilePath* suggested_name,
813 base::FilePath::StringType* suggested_extension) {
814 if (opt_name) {
815 *suggested_name = base::FilePath::FromUTF8Unsafe(*opt_name);
816
817 // Don't allow any path components; shorten to the base name. This should
818 // result in a relative path, but in some cases may not. Clear the
819 // suggestion for safety if this is the case.
820 *suggested_name = suggested_name->BaseName();
821 if (suggested_name->IsAbsolute())
822 *suggested_name = base::FilePath();
823
824 *suggested_extension = suggested_name->Extension();
825 if (!suggested_extension->empty())
826 suggested_extension->erase(suggested_extension->begin()); // drop the .
827 }
828 }
829
830 void FileSystemChooseEntryFunction::SetInitialPathAndShowPicker(
831 const base::FilePath& previous_path,
832 const base::FilePath& suggested_name,
833 const ui::SelectFileDialog::FileTypeInfo& file_type_info,
834 ui::SelectFileDialog::Type picker_type,
835 bool is_previous_path_directory) {
836 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
837 if (is_previous_path_directory) {
838 initial_path_ = previous_path.Append(suggested_name);
839 } else {
840 base::FilePath documents_dir;
841 if (PathService::Get(chrome::DIR_USER_DOCUMENTS, &documents_dir)) {
842 initial_path_ = documents_dir.Append(suggested_name);
843 } else {
844 initial_path_ = suggested_name;
845 }
846 }
847 ShowPicker(file_type_info, picker_type);
848 }
849
850 bool FileSystemChooseEntryFunction::RunAsync() {
851 std::unique_ptr<ChooseEntry::Params> params(
852 ChooseEntry::Params::Create(*args_));
853 EXTENSION_FUNCTION_VALIDATE(params.get());
854
855 base::FilePath suggested_name;
856 ui::SelectFileDialog::FileTypeInfo file_type_info;
857 ui::SelectFileDialog::Type picker_type =
858 ui::SelectFileDialog::SELECT_OPEN_FILE;
859
860 file_system::ChooseEntryOptions* options = params->options.get();
861 if (options) {
862 multiple_ = options->accepts_multiple && *options->accepts_multiple;
863 if (multiple_)
864 picker_type = ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE;
865
866 if (options->type == file_system::CHOOSE_ENTRY_TYPE_OPENWRITABLEFILE &&
867 !app_file_handler_util::HasFileSystemWritePermission(
868 extension_.get())) {
869 error_ = kRequiresFileSystemWriteError;
870 return false;
871 } else if (options->type == file_system::CHOOSE_ENTRY_TYPE_SAVEFILE) {
872 if (!app_file_handler_util::HasFileSystemWritePermission(
873 extension_.get())) {
874 error_ = kRequiresFileSystemWriteError;
875 return false;
876 }
877 if (multiple_) {
878 error_ = kMultipleUnsupportedError;
879 return false;
880 }
881 picker_type = ui::SelectFileDialog::SELECT_SAVEAS_FILE;
882 } else if (options->type == file_system::CHOOSE_ENTRY_TYPE_OPENDIRECTORY) {
883 is_directory_ = true;
884 if (!extension_->permissions_data()->HasAPIPermission(
885 APIPermission::kFileSystemDirectory)) {
886 error_ = kRequiresFileSystemDirectoryError;
887 return false;
888 }
889 if (multiple_) {
890 error_ = kMultipleUnsupportedError;
891 return false;
892 }
893 picker_type = ui::SelectFileDialog::SELECT_FOLDER;
894 }
895
896 base::FilePath::StringType suggested_extension;
897 BuildSuggestion(options->suggested_name.get(), &suggested_name,
898 &suggested_extension);
899
900 BuildFileTypeInfo(&file_type_info, suggested_extension,
901 options->accepts.get(), options->accepts_all_types.get());
902 }
903
904 file_type_info.allowed_paths = ui::SelectFileDialog::FileTypeInfo::ANY_PATH;
905
906 base::FilePath previous_path = file_system_api::GetLastChooseEntryDirectory(
907 ExtensionPrefs::Get(GetProfile()), extension()->id());
908
909 if (previous_path.empty()) {
910 SetInitialPathAndShowPicker(previous_path, suggested_name, file_type_info,
911 picker_type, false);
912 return true;
913 }
914
915 base::Callback<void(bool)> set_initial_path_callback = base::Bind(
916 &FileSystemChooseEntryFunction::SetInitialPathAndShowPicker, this,
917 previous_path, suggested_name, file_type_info, picker_type);
918
919 // Check whether the |previous_path| is a non-native directory.
920 #if defined(OS_CHROMEOS)
921 if (file_manager::util::IsUnderNonNativeLocalPath(GetProfile(),
922 previous_path)) {
923 file_manager::util::IsNonNativeLocalPathDirectory(
924 GetProfile(), previous_path, set_initial_path_callback);
925 return true;
926 }
927 #endif
928 base::PostTaskWithTraitsAndReplyWithResult(
929 FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
930 base::Bind(&base::DirectoryExists, previous_path),
931 set_initial_path_callback);
932
933 return true;
934 }
935
936 bool FileSystemRetainEntryFunction::RunAsync() {
937 std::string entry_id;
938 EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &entry_id));
939 SavedFilesService* saved_files_service = SavedFilesService::Get(GetProfile());
940 // Add the file to the retain list if it is not already on there.
941 if (!saved_files_service->IsRegistered(extension_->id(), entry_id)) {
942 std::string filesystem_name;
943 std::string filesystem_path;
944 base::FilePath path;
945 EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &filesystem_name));
946 EXTENSION_FUNCTION_VALIDATE(args_->GetString(2, &filesystem_path));
947 if (!app_file_handler_util::ValidateFileEntryAndGetPath(
948 filesystem_name, filesystem_path,
949 render_frame_host()->GetProcess()->GetID(), &path, &error_)) {
950 return false;
951 }
952
953 std::string filesystem_id;
954 if (!storage::CrackIsolatedFileSystemName(filesystem_name, &filesystem_id))
955 return false;
956
957 const GURL site = util::GetSiteForExtensionId(extension_id(), GetProfile());
958 storage::FileSystemContext* const context =
959 content::BrowserContext::GetStoragePartitionForSite(GetProfile(), site)
960 ->GetFileSystemContext();
961 const storage::FileSystemURL url = context->CreateCrackedFileSystemURL(
962 site,
963 storage::kFileSystemTypeIsolated,
964 IsolatedContext::GetInstance()
965 ->CreateVirtualRootPath(filesystem_id)
966 .Append(base::FilePath::FromUTF8Unsafe(filesystem_path)));
967
968 content::BrowserThread::PostTask(
969 content::BrowserThread::IO, FROM_HERE,
970 base::BindOnce(
971 base::IgnoreResult(
972 &storage::FileSystemOperationRunner::GetMetadata),
973 context->operation_runner()->AsWeakPtr(), url,
974 storage::FileSystemOperation::GET_METADATA_FIELD_IS_DIRECTORY,
975 base::Bind(
976 &PassFileInfoToUIThread,
977 base::Bind(&FileSystemRetainEntryFunction::RetainFileEntry,
978 this, entry_id, path))));
979 return true;
980 }
981
982 saved_files_service->EnqueueFileEntry(extension_->id(), entry_id);
983 SendResponse(true);
984 return true;
985 }
986
987 void FileSystemRetainEntryFunction::RetainFileEntry(
988 const std::string& entry_id,
989 const base::FilePath& path,
990 std::unique_ptr<base::File::Info> file_info) {
991 if (!file_info) {
992 SendResponse(false);
993 return;
994 }
995
996 SavedFilesService* saved_files_service = SavedFilesService::Get(GetProfile());
997 saved_files_service->RegisterFileEntry(
998 extension_->id(), entry_id, path, file_info->is_directory);
999 saved_files_service->EnqueueFileEntry(extension_->id(), entry_id);
1000 SendResponse(true);
1001 }
1002
1003 ExtensionFunction::ResponseAction FileSystemIsRestorableFunction::Run() {
1004 std::string entry_id;
1005 EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &entry_id));
1006 return RespondNow(OneArgument(base::MakeUnique<base::Value>(
1007 SavedFilesService::Get(Profile::FromBrowserContext(browser_context()))
1008 ->IsRegistered(extension_->id(), entry_id))));
1009 }
1010
1011 bool FileSystemRestoreEntryFunction::RunAsync() {
1012 std::string entry_id;
1013 bool needs_new_entry;
1014 EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &entry_id));
1015 EXTENSION_FUNCTION_VALIDATE(args_->GetBoolean(1, &needs_new_entry));
1016 const SavedFileEntry* file_entry = SavedFilesService::Get(
1017 GetProfile())->GetFileEntry(extension_->id(), entry_id);
1018 if (!file_entry) {
1019 error_ = kUnknownIdError;
1020 return false;
1021 }
1022
1023 SavedFilesService::Get(GetProfile())
1024 ->EnqueueFileEntry(extension_->id(), entry_id);
1025
1026 // Only create a new file entry if the renderer requests one.
1027 // |needs_new_entry| will be false if the renderer already has an Entry for
1028 // |entry_id|.
1029 if (needs_new_entry) {
1030 is_directory_ = file_entry->is_directory;
1031 std::unique_ptr<base::DictionaryValue> result = CreateResult();
1032 AddEntryToResult(file_entry->path, file_entry->id, result.get());
1033 SetResult(std::move(result));
1034 }
1035 SendResponse(true);
1036 return true;
1037 }
1038
1039 ExtensionFunction::ResponseAction FileSystemObserveDirectoryFunction::Run() {
1040 NOTIMPLEMENTED();
1041 return RespondNow(Error(kUnknownIdError));
1042 }
1043
1044 ExtensionFunction::ResponseAction FileSystemUnobserveEntryFunction::Run() {
1045 NOTIMPLEMENTED();
1046 return RespondNow(Error(kUnknownIdError));
1047 }
1048
1049 ExtensionFunction::ResponseAction FileSystemGetObservedEntriesFunction::Run() {
1050 NOTIMPLEMENTED();
1051 return RespondNow(Error(kUnknownIdError));
1052 }
1053
1054 #if !defined(OS_CHROMEOS)
1055 ExtensionFunction::ResponseAction FileSystemRequestFileSystemFunction::Run() {
1056 using api::file_system::RequestFileSystem::Params;
1057 const std::unique_ptr<Params> params(Params::Create(*args_));
1058 EXTENSION_FUNCTION_VALIDATE(params);
1059
1060 NOTIMPLEMENTED();
1061 return RespondNow(Error(kNotSupportedOnCurrentPlatformError));
1062 }
1063
1064 ExtensionFunction::ResponseAction FileSystemGetVolumeListFunction::Run() {
1065 NOTIMPLEMENTED();
1066 return RespondNow(Error(kNotSupportedOnCurrentPlatformError));
1067 }
1068 #else
1069
1070 FileSystemRequestFileSystemFunction::FileSystemRequestFileSystemFunction()
1071 : chrome_details_(this) {
1072 }
1073
1074 FileSystemRequestFileSystemFunction::~FileSystemRequestFileSystemFunction() {
1075 }
1076
1077 ExtensionFunction::ResponseAction FileSystemRequestFileSystemFunction::Run() {
1078 using api::file_system::RequestFileSystem::Params;
1079 const std::unique_ptr<Params> params(Params::Create(*args_));
1080 EXTENSION_FUNCTION_VALIDATE(params);
1081
1082 // Only kiosk apps in kiosk sessions can use this API.
1083 // Additionally it is enabled for whitelisted component extensions and apps.
1084 file_system_api::ConsentProviderDelegate consent_provider_delegate(
1085 chrome_details_.GetProfile(), render_frame_host());
1086 file_system_api::ConsentProvider consent_provider(&consent_provider_delegate);
1087
1088 if (!consent_provider.IsGrantable(*extension()))
1089 return RespondNow(Error(kNotSupportedOnNonKioskSessionError));
1090
1091 using file_manager::VolumeManager;
1092 using file_manager::Volume;
1093 VolumeManager* const volume_manager =
1094 VolumeManager::Get(chrome_details_.GetProfile());
1095 DCHECK(volume_manager);
1096
1097 const bool writable =
1098 params->options.writable.get() && *params->options.writable.get();
1099 if (writable &&
1100 !app_file_handler_util::HasFileSystemWritePermission(extension_.get())) {
1101 return RespondNow(Error(kRequiresFileSystemWriteError));
1102 }
1103
1104 base::WeakPtr<file_manager::Volume> volume =
1105 volume_manager->FindVolumeById(params->options.volume_id);
1106 if (!volume.get())
1107 return RespondNow(Error(kVolumeNotFoundError));
1108
1109 const GURL site = 237 const GURL site =
1110 util::GetSiteForExtensionId(extension_id(), chrome_details_.GetProfile()); 238 util::GetSiteForExtensionId(extension.id(), browser_context);
1111 scoped_refptr<storage::FileSystemContext> file_system_context = 239 scoped_refptr<storage::FileSystemContext> file_system_context =
1112 content::BrowserContext::GetStoragePartitionForSite( 240 content::BrowserContext::GetStoragePartitionForSite(browser_context, site)
1113 chrome_details_.GetProfile(), site)->GetFileSystemContext(); 241 ->GetFileSystemContext();
1114 storage::ExternalFileSystemBackend* const backend = 242 storage::ExternalFileSystemBackend* const backend =
1115 file_system_context->external_backend(); 243 file_system_context->external_backend();
1116 DCHECK(backend); 244 DCHECK(backend);
1117 245
1118 base::FilePath virtual_path; 246 base::FilePath virtual_path;
1119 if (!backend->GetVirtualPath(volume->mount_path(), &virtual_path)) 247 if (!backend->GetVirtualPath(volume->mount_path(), &virtual_path)) {
1120 return RespondNow(Error(kSecurityError)); 248 error_callback.Run(kSecurityError);
249 return;
250 }
1121 251
1122 if (writable && (volume->is_read_only())) 252 if (writable && (volume->is_read_only())) {
1123 return RespondNow(Error(kSecurityError)); 253 error_callback.Run(kSecurityError);
254 return;
255 }
1124 256
1125 consent_provider.RequestConsent( 257 const ConsentProvider::ConsentCallback& callback = base::Bind(
1126 *extension(), volume, writable, 258 &ChromeFileSystemDelegate::OnConsentReceived, base::Unretained(this),
1127 base::Bind(&FileSystemRequestFileSystemFunction::OnConsentReceived, this, 259 browser_context, requester, success_callback, error_callback,
1128 volume, writable)); 260 extension.id(), volume, writable);
1129 return RespondLater(); 261
262 consent_provider.RequestConsent(extension, requester->render_frame_host(),
263 volume, writable, callback);
1130 } 264 }
1131 265
1132 void FileSystemRequestFileSystemFunction::OnConsentReceived( 266 void ChromeFileSystemDelegate::GetVolumeList(
267 content::BrowserContext* browser_context,
268 const VolumeListCallback& success_callback,
269 const ErrorCallback& error_callback) {
270 std::vector<file_system::Volume> result_volume_list;
271 FillVolumeList(browser_context, &result_volume_list);
272
273 success_callback.Run(result_volume_list);
274 }
275
276 void ChromeFileSystemDelegate::OnConsentReceived(
277 content::BrowserContext* browser_context,
278 scoped_refptr<UIThreadExtensionFunction> requester,
279 const FileSystemCallback& success_callback,
280 const ErrorCallback& error_callback,
281 const std::string& extension_id,
1133 const base::WeakPtr<file_manager::Volume>& volume, 282 const base::WeakPtr<file_manager::Volume>& volume,
1134 bool writable, 283 bool writable,
1135 ConsentProvider::Consent result) { 284 ConsentProvider::Consent result) {
1136 using file_manager::VolumeManager; 285 using file_manager::VolumeManager;
1137 using file_manager::Volume; 286 using file_manager::Volume;
1138 287
1139 // Render frame host can be gone before this callback method is executed. 288 // Render frame host can be gone before this callback method is executed.
1140 if (!render_frame_host()) { 289 if (!requester->render_frame_host()) {
1141 Respond(Error("")); 290 error_callback.Run("");
1142 return; 291 return;
1143 } 292 }
1144 293
1145 switch (result) { 294 switch (result) {
1146 case ConsentProvider::CONSENT_REJECTED: 295 case ConsentProvider::CONSENT_REJECTED:
1147 Respond(Error(kSecurityError)); 296 error_callback.Run(kSecurityError);
1148 return; 297 return;
1149 298
1150 case ConsentProvider::CONSENT_IMPOSSIBLE: 299 case ConsentProvider::CONSENT_IMPOSSIBLE:
1151 Respond(Error(kConsentImpossible)); 300 error_callback.Run(kConsentImpossible);
1152 return; 301 return;
1153 302
1154 case ConsentProvider::CONSENT_GRANTED: 303 case ConsentProvider::CONSENT_GRANTED:
1155 break; 304 break;
1156 } 305 }
1157 306
1158 if (!volume.get()) { 307 if (!volume.get()) {
1159 Respond(Error(kVolumeNotFoundError)); 308 error_callback.Run(kVolumeNotFoundError);
1160 return; 309 return;
1161 } 310 }
1162 311
1163 const GURL site = 312 const GURL site = util::GetSiteForExtensionId(extension_id, browser_context);
1164 util::GetSiteForExtensionId(extension_id(), chrome_details_.GetProfile());
1165 scoped_refptr<storage::FileSystemContext> file_system_context = 313 scoped_refptr<storage::FileSystemContext> file_system_context =
1166 content::BrowserContext::GetStoragePartitionForSite( 314 content::BrowserContext::GetStoragePartitionForSite(browser_context, site)
1167 chrome_details_.GetProfile(), site)->GetFileSystemContext(); 315 ->GetFileSystemContext();
1168 storage::ExternalFileSystemBackend* const backend = 316 storage::ExternalFileSystemBackend* const backend =
1169 file_system_context->external_backend(); 317 file_system_context->external_backend();
1170 DCHECK(backend); 318 DCHECK(backend);
1171 319
1172 base::FilePath virtual_path; 320 base::FilePath virtual_path;
1173 if (!backend->GetVirtualPath(volume->mount_path(), &virtual_path)) { 321 if (!backend->GetVirtualPath(volume->mount_path(), &virtual_path)) {
1174 Respond(Error(kSecurityError)); 322 error_callback.Run(kSecurityError);
1175 return; 323 return;
1176 } 324 }
1177 325
1178 storage::IsolatedContext* const isolated_context = 326 storage::IsolatedContext* const isolated_context =
1179 storage::IsolatedContext::GetInstance(); 327 storage::IsolatedContext::GetInstance();
1180 DCHECK(isolated_context); 328 DCHECK(isolated_context);
1181 329
1182 const storage::FileSystemURL original_url = 330 const storage::FileSystemURL original_url =
1183 file_system_context->CreateCrackedFileSystemURL( 331 file_system_context->CreateCrackedFileSystemURL(
1184 GURL(std::string(kExtensionScheme) + url::kStandardSchemeSeparator + 332 GURL(std::string(kExtensionScheme) + url::kStandardSchemeSeparator +
1185 extension_id()), 333 extension_id),
1186 storage::kFileSystemTypeExternal, virtual_path); 334 storage::kFileSystemTypeExternal, virtual_path);
1187 335
1188 // Set a fixed register name, as the automatic one would leak the mount point 336 // Set a fixed register name, as the automatic one would leak the mount point
1189 // directory. 337 // directory.
1190 std::string register_name = "fs"; 338 std::string register_name = "fs";
1191 const std::string file_system_id = 339 const std::string file_system_id =
1192 isolated_context->RegisterFileSystemForPath( 340 isolated_context->RegisterFileSystemForPath(
1193 storage::kFileSystemTypeNativeForPlatformApp, 341 storage::kFileSystemTypeNativeForPlatformApp,
1194 std::string() /* file_system_id */, original_url.path(), 342 std::string() /* file_system_id */, original_url.path(),
1195 &register_name); 343 &register_name);
1196 if (file_system_id.empty()) { 344 if (file_system_id.empty()) {
1197 Respond(Error(kSecurityError)); 345 error_callback.Run(kSecurityError);
1198 return; 346 return;
1199 } 347 }
1200 348
1201 backend->GrantFileAccessToExtension(extension_->id(), virtual_path); 349 backend->GrantFileAccessToExtension(extension_id, virtual_path);
1202 350
1203 // Grant file permissions to the renderer hosting component. 351 // Grant file permissions to the renderer hosting component.
1204 content::ChildProcessSecurityPolicy* policy = 352 content::ChildProcessSecurityPolicy* policy =
1205 content::ChildProcessSecurityPolicy::GetInstance(); 353 content::ChildProcessSecurityPolicy::GetInstance();
1206 DCHECK(policy); 354 DCHECK(policy);
1207 355
356 const auto process_id = requester->render_frame_host()->GetProcess()->GetID();
1208 // Read-only permisisons. 357 // Read-only permisisons.
1209 policy->GrantReadFile(render_frame_host()->GetProcess()->GetID(), 358 policy->GrantReadFile(process_id, volume->mount_path());
1210 volume->mount_path()); 359 policy->GrantReadFileSystem(process_id, file_system_id);
1211 policy->GrantReadFileSystem(render_frame_host()->GetProcess()->GetID(),
1212 file_system_id);
1213 360
1214 // Additional write permissions. 361 // Additional write permissions.
1215 if (writable) { 362 if (writable) {
1216 policy->GrantCreateReadWriteFile(render_frame_host()->GetProcess()->GetID(), 363 policy->GrantCreateReadWriteFile(process_id, volume->mount_path());
1217 volume->mount_path()); 364 policy->GrantCopyInto(process_id, volume->mount_path());
1218 policy->GrantCopyInto(render_frame_host()->GetProcess()->GetID(), 365 policy->GrantWriteFileSystem(process_id, file_system_id);
1219 volume->mount_path()); 366 policy->GrantDeleteFromFileSystem(process_id, file_system_id);
1220 policy->GrantWriteFileSystem(render_frame_host()->GetProcess()->GetID(), 367 policy->GrantCreateFileForFileSystem(process_id, file_system_id);
1221 file_system_id);
1222 policy->GrantDeleteFromFileSystem(
1223 render_frame_host()->GetProcess()->GetID(), file_system_id);
1224 policy->GrantCreateFileForFileSystem(
1225 render_frame_host()->GetProcess()->GetID(), file_system_id);
1226 } 368 }
1227 369
1228 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); 370 success_callback.Run(file_system_id, register_name);
1229 dict->SetString("file_system_id", file_system_id); 371 }
1230 dict->SetString("file_system_path", register_name); 372 #endif // defined(OS_CHROMEOS)
1231 373
1232 Respond(OneArgument(std::move(dict))); 374 std::unique_ptr<file_system_api::SavedFilesServiceDelegate>
375 ChromeFileSystemDelegate::CreateSavedFilesServiceDelegate(
376 content::BrowserContext* browser_context) {
377 return base::MakeUnique<apps::SavedFilesServiceDelegateImpl>(browser_context);
1233 } 378 }
1234 379
1235 FileSystemGetVolumeListFunction::FileSystemGetVolumeListFunction()
1236 : chrome_details_(this) {
1237 }
1238
1239 FileSystemGetVolumeListFunction::~FileSystemGetVolumeListFunction() {
1240 }
1241
1242 ExtensionFunction::ResponseAction FileSystemGetVolumeListFunction::Run() {
1243 // Only kiosk apps in kiosk sessions can use this API.
1244 // Additionally it is enabled for whitelisted component extensions and apps.
1245 file_system_api::ConsentProviderDelegate consent_provider_delegate(
1246 chrome_details_.GetProfile(), render_frame_host());
1247 file_system_api::ConsentProvider consent_provider(&consent_provider_delegate);
1248
1249 if (!consent_provider.IsGrantable(*extension()))
1250 return RespondNow(Error(kNotSupportedOnNonKioskSessionError));
1251 std::vector<api::file_system::Volume> result_volume_list;
1252 FillVolumeList(chrome_details_.GetProfile(), &result_volume_list);
1253
1254 return RespondNow(ArgumentList(
1255 api::file_system::GetVolumeList::Results::Create(result_volume_list)));
1256 }
1257 #endif
1258
1259 } // namespace extensions 380 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698