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

Side by Side Diff: extensions/browser/api/file_system/file_system_api.cc

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

Powered by Google App Engine
This is Rietveld 408576698