diff options
author | pilgrim <pilgrim@chromium.org> | 2014-09-05 10:30:15 -0700 |
---|---|---|
committer | Commit bot <commit-bot@chromium.org> | 2014-09-05 17:32:24 +0000 |
commit | 4af8c2120e23d17c1cac3f929c3a1d901c5701ab (patch) | |
tree | 40e4ca0d45ec498ea74b9b4b232764abc1ec6ab1 | |
parent | a602902631a762be0b49ac0af09de0c9c840e183 (diff) | |
download | chromium_src-4af8c2120e23d17c1cac3f929c3a1d901c5701ab.zip chromium_src-4af8c2120e23d17c1cac3f929c3a1d901c5701ab.tar.gz chromium_src-4af8c2120e23d17c1cac3f929c3a1d901c5701ab.tar.bz2 |
Migrate webkit/browser/ to storage/browser/
using TBR because Darin told me he defers to James' judgement. Using NOTRY because there is one presubmit error (dump_file_system.cc was moved and it spews printf).
BUG=338338
TBR=darin@chromium.org
NOTRY=true
Review URL: https://codereview.chromium.org/539143002
Cr-Commit-Position: refs/heads/master@{#293547}
251 files changed, 10339 insertions, 9937 deletions
@@ -61,6 +61,7 @@ group("root") { "//sandbox", "//sdch", "//skia", + "//storage/browser", "//sql", "//sync", "//third_party/WebKit/public:all_blink", @@ -126,7 +127,6 @@ group("root") { "//ui/wm", "//url", "//v8:v8", - "//webkit/browser:storage", ] if (!is_win) { @@ -221,6 +221,7 @@ group("root") { # Not tested on Android yet: "//google_apis/gcm", "//remoting/client/plugin", + "//storage/browser", "//third_party/cld_2", "//third_party/libaddressinput", "//third_party/ffmpeg", @@ -228,7 +229,6 @@ group("root") { "//ui/app_list", "//ui/web_dialogs", "//ui/wm", - "//webkit/browser:storage", ] } diff --git a/android_webview/native/webview_native.gyp b/android_webview/native/webview_native.gyp index 790d40e..52b3e45 100644 --- a/android_webview/native/webview_native.gyp +++ b/android_webview/native/webview_native.gyp @@ -19,11 +19,11 @@ '../../media/media.gyp:player_android', '../../net/net.gyp:net', '../../skia/skia.gyp:skia', + '../../storage/storage_browser.gyp:storage', '../../storage/storage_common.gyp:storage_common', '../../ui/base/ui_base.gyp:ui_base', '../../ui/gfx/gfx.gyp:gfx', '../../ui/gfx/gfx.gyp:gfx_geometry', - '../../webkit/storage_browser.gyp:storage', '../../third_party/boringssl/boringssl.gyp:boringssl', 'android_webview_native_jni', ], diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index d3dc853..01d6c72 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn @@ -166,6 +166,7 @@ static_library("browser") { "//mojo/system", "//net:extras", "//net:net_with_v8", + "//storage/browser", "//storage/common", "//third_party/WebKit/public:resources", "//third_party/expat", @@ -180,7 +181,6 @@ static_library("browser") { "//ui/surface", "//ui/web_dialogs", "//v8", - "//webkit/browser:storage", ## TODO(tonyg): Remove this dependency (crbug.com/280157). #"../testing/perf/perf_test.gyp:*", TODO(GYP) ] diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index 8beed8a..a3cb5cc 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn @@ -72,7 +72,7 @@ static_library("extensions") { "//ui/resources", "//ui/strings", "//url", - "//webkit/browser:storage", + "//storage/browser", ] forward_dependent_configs_from = [ diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 077de8c..34c421b 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn @@ -95,6 +95,8 @@ static_library("ui") { "//media", "//mojo/system", "//net:net_with_v8", + "//storage/browser", + "//storage/common", "//third_party/WebKit/public:resources", "//third_party/adobe/flash:flapper_version_h", "//third_party/expat", @@ -107,8 +109,6 @@ static_library("ui") { "//ui/surface", "//ui/web_dialogs", "//v8", - "//webkit/browser:storage", - "//storage/common", ] # TODO(GYP) #'defines': [ diff --git a/chrome/chrome_browser.gypi b/chrome/chrome_browser.gypi index ef926a3..638df70 100644 --- a/chrome/chrome_browser.gypi +++ b/chrome/chrome_browser.gypi @@ -2928,6 +2928,7 @@ '../mojo/mojo_base.gyp:mojo_system_impl', '../net/net.gyp:net_extras', '../net/net.gyp:net_with_v8', + '../storage/storage_browser.gyp:storage', '../storage/storage_common.gyp:storage_common', # TODO(tonyg): Remove this dependency (crbug.com/280157). '../testing/perf/perf_test.gyp:*', @@ -2942,7 +2943,6 @@ '../ui/surface/surface.gyp:surface', '../ui/web_dialogs/web_dialogs.gyp:web_dialogs', '../v8/tools/gyp/v8.gyp:v8', - '../webkit/storage_browser.gyp:storage', ], 'sources': [ '<@(chrome_browser_non_ios_sources)', diff --git a/chrome/chrome_browser_chromeos.gypi b/chrome/chrome_browser_chromeos.gypi index cbc5c40..e8dbe10 100644 --- a/chrome/chrome_browser_chromeos.gypi +++ b/chrome/chrome_browser_chromeos.gypi @@ -73,6 +73,7 @@ '../net/net.gyp:net', '../ppapi/ppapi_internal.gyp:ppapi_ipc', # For PpapiMsg_LoadPlugin '../skia/skia.gyp:skia', + '../storage/storage_browser.gyp:storage', '../storage/storage_common.gyp:storage_common', '../sync/sync.gyp:sync', '../third_party/adobe/flash/flash_player.gyp:flapper_version_h', @@ -106,7 +107,6 @@ '../ui/web_dialogs/web_dialogs.gyp:web_dialogs', '../url/url.gyp:url_lib', '../v8/tools/gyp/v8.gyp:v8', - '../webkit/storage_browser.gyp:storage', 'chrome_resources.gyp:chrome_strings', ], 'defines': [ diff --git a/chrome/chrome_browser_extensions.gypi b/chrome/chrome_browser_extensions.gypi index 1fe2547..36bae50 100644 --- a/chrome/chrome_browser_extensions.gypi +++ b/chrome/chrome_browser_extensions.gypi @@ -936,6 +936,7 @@ '../extensions/extensions_strings.gyp:extensions_strings', '../net/net.gyp:net', '../skia/skia.gyp:skia', + '../storage/storage_browser.gyp:storage', '../storage/storage_common.gyp:storage_common', '../sync/sync.gyp:sync', '../third_party/cacheinvalidation/cacheinvalidation.gyp:cacheinvalidation', @@ -951,7 +952,6 @@ '../ui/resources/ui_resources.gyp:ui_resources', '../ui/strings/ui_strings.gyp:ui_strings', '../url/url.gyp:url_lib', - '../webkit/storage_browser.gyp:storage', ], 'include_dirs': [ '..', diff --git a/chrome/chrome_browser_ui.gypi b/chrome/chrome_browser_ui.gypi index ebf8f4b..25a28f6 100644 --- a/chrome/chrome_browser_ui.gypi +++ b/chrome/chrome_browser_ui.gypi @@ -2625,6 +2625,7 @@ '../media/media.gyp:media', '../mojo/mojo_base.gyp:mojo_system_impl', '../net/net.gyp:net_with_v8', + '../storage/storage_browser.gyp:storage', '../storage/storage_common.gyp:storage_common', '../third_party/expat/expat.gyp:expat', '../third_party/leveldatabase/leveldatabase.gyp:leveldatabase', @@ -2635,7 +2636,6 @@ '../ui/surface/surface.gyp:surface', '../ui/web_dialogs/web_dialogs.gyp:web_dialogs', '../v8/tools/gyp/v8.gyp:v8', - '../webkit/storage_browser.gyp:storage', ], 'defines': [ '<@(nacl_defines)', diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index a809944..36898fb 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn @@ -98,6 +98,7 @@ source_set("browser") { "//mojo/public/interfaces/application", "//mojo/public/js/bindings", "//net:http_server", + "//storage/browser", "//storage/common", "//third_party/WebKit/public:resources", "//third_party/angle:commit_id", @@ -106,7 +107,6 @@ source_set("browser") { "//third_party/libyuv", "//ui/resources", "//ui/surface", - "//webkit/browser:storage", ] } diff --git a/content/common/BUILD.gn b/content/common/BUILD.gn index d2c028d..51766f1 100644 --- a/content/common/BUILD.gn +++ b/content/common/BUILD.gn @@ -61,10 +61,10 @@ source_set("common") { "//mojo/public/interfaces/application", "//mojo/system", "//sandbox", + "//storage/browser", + "//storage/common", "//third_party/WebKit/public:blink", "//ui/gl", - "//webkit/browser:storage", - "//storage/common", "//webkit/common/gpu", ] } diff --git a/content/content_browser.gypi b/content/content_browser.gypi index 5c77b89..bf012dd 100644 --- a/content/content_browser.gypi +++ b/content/content_browser.gypi @@ -1598,11 +1598,11 @@ '../mojo/mojo_base.gyp:mojo_cpp_bindings', '../mojo/mojo_base.gyp:mojo_js_bindings', '../net/net.gyp:http_server', + '../storage/storage_browser.gyp:storage', '../storage/storage_common.gyp:storage_common', '../third_party/angle/src/build_angle.gyp:commit_id', '../third_party/leveldatabase/leveldatabase.gyp:leveldatabase', '../ui/surface/surface.gyp:surface', - '../webkit/storage_browser.gyp:storage', ], }], ['enable_printing!=0', { diff --git a/content/content_common.gypi b/content/content_common.gypi index a8de172..0187344 100644 --- a/content/content_common.gypi +++ b/content/content_common.gypi @@ -564,11 +564,11 @@ '../mojo/mojo_base.gyp:mojo_cpp_bindings', '../mojo/mojo_base.gyp:mojo_environment_chromium', '../mojo/mojo_base.gyp:mojo_system_impl', + '../storage/storage_browser.gyp:storage', '../storage/storage_common.gyp:storage_common', '../third_party/WebKit/public/blink.gyp:blink', '../ui/gl/gl.gyp:gl', '../webkit/common/gpu/webkit_gpu.gyp:webkit_gpu', - '../webkit/storage_browser.gyp:storage', ], 'actions': [ { diff --git a/content/content_shell.gypi b/content/content_shell.gypi index 5ca79a3..f530e5a 100644 --- a/content/content_shell.gypi +++ b/content/content_shell.gypi @@ -54,6 +54,7 @@ '../net/net.gyp:net', '../net/net.gyp:net_resources', '../skia/skia.gyp:skia', + '../storage/storage_browser.gyp:storage', '../third_party/WebKit/public/blink.gyp:blink', '../third_party/WebKit/public/blink.gyp:blink_test_support', '../ui/base/ui_base.gyp:ui_base', @@ -64,7 +65,6 @@ '../ui/gl/gl.gyp:gl', '../url/url.gyp:url_lib', '../v8/tools/gyp/v8.gyp:v8', - '../webkit/storage_browser.gyp:storage', ], 'include_dirs': [ '..', diff --git a/content/content_tests.gypi b/content/content_tests.gypi index 56fc31a..dfca6c5 100644 --- a/content/content_tests.gypi +++ b/content/content_tests.gypi @@ -277,13 +277,13 @@ '../ppapi/ppapi_internal.gyp:ppapi_proxy', '../ppapi/ppapi_internal.gyp:ppapi_shared', '../ppapi/ppapi_internal.gyp:ppapi_unittest_shared', + '../storage/storage_browser.gyp:storage', '../storage/storage_common.gyp:storage_common', '../third_party/WebKit/public/blink.gyp:blink', '../ui/compositor/compositor.gyp:compositor_test_support', '../ui/surface/surface.gyp:surface', '../v8/tools/gyp/v8.gyp:v8', '../webkit/common/gpu/webkit_gpu.gyp:webkit_gpu', - '../webkit/storage_browser.gyp:storage', ], 'export_dependent_settings': [ '../third_party/WebKit/public/blink.gyp:blink', @@ -761,6 +761,7 @@ '../ipc/ipc.gyp:test_support_ipc', '../media/media.gyp:media_test_support', '../media/media.gyp:shared_memory_support', + '../storage/storage_browser.gyp:storage', '../storage/storage_common.gyp:storage_common', '../third_party/WebKit/public/blink.gyp:blink', '../third_party/icu/icu.gyp:icui18n', @@ -768,7 +769,6 @@ '../third_party/leveldatabase/leveldatabase.gyp:leveldatabase', '../third_party/libjingle/libjingle.gyp:libjingle', '../ui/gl/gl.gyp:gl', - '../webkit/storage_browser.gyp:storage', ], }], ['enable_plugins==0', { diff --git a/content/shell/BUILD.gn b/content/shell/BUILD.gn index 412e889..3ef1c6d 100644 --- a/content/shell/BUILD.gn +++ b/content/shell/BUILD.gn @@ -227,6 +227,7 @@ static_library("content_shell_lib") { "//net", "//net:net_resources", "//skia", + "//storage/browser", "//third_party/WebKit/public:blink", "//third_party/WebKit/public:resources", "//third_party/WebKit/public:test_support", @@ -239,7 +240,6 @@ static_library("content_shell_lib") { "//ui/gl", "//url", "//v8", - "//webkit/browser:storage", #'copy_test_netscape_plugin', TODO(GYP) ] diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index d3a7802..75ada2c 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn @@ -20,6 +20,7 @@ static_library("test_support") { "//content/public/common", "//net:test_support", "//skia", + "//storage/common", "//testing/gmock", "//testing/gtest", "//ui/accessibility:ax_gen", @@ -32,7 +33,6 @@ static_library("test_support") { "//ui/gfx:test_support", "//ui/resources", "//url", - "//storage/common", ] if (!is_ios) { @@ -53,12 +53,12 @@ static_library("test_support") { "//ppapi:ppapi_proxy", "//ppapi:ppapi_shared", "//ppapi:ppapi_unittest_shared", + "//storage/browser", "//storage/common", "//third_party/WebKit/public:blink", "//ui/surface", "//v8", "//webkit/common/gpu", - "//webkit/browser:storage", ] forward_dependent_configs_from = [ diff --git a/storage/DEPS b/storage/DEPS index 8e3d4fd..c311233 100644 --- a/storage/DEPS +++ b/storage/DEPS @@ -1,5 +1,7 @@ include_rules = [ "+net", "+sql", + "+third_party/leveldatabase", + "+third_party/sqlite", "+third_party/WebKit/public/platform", ] diff --git a/webkit/browser/BUILD.gn b/storage/browser/BUILD.gn index 0a74f5e..7b0b461 100644 --- a/webkit/browser/BUILD.gn +++ b/storage/browser/BUILD.gn @@ -2,9 +2,9 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -# GYP version: webkit/storage_browser.gyp:storage -component("storage") { - output_name = "storage" +# GYP version: storage/storage_browser.gyp:storage +component("browser") { + output_name = "storage_browser" sources = [ "storage_browser_export.h", "blob/blob_data_handle.cc", @@ -185,7 +185,7 @@ executable("dump_file_system") { ] deps = [ - ":storage", + ":browser", "//base", "//storage/common", ] diff --git a/webkit/browser/DEPS b/storage/browser/DEPS index 62bbdd0..62bbdd0 100644 --- a/webkit/browser/DEPS +++ b/storage/browser/DEPS diff --git a/webkit/browser/blob/OWNERS b/storage/browser/blob/OWNERS index c7e8dcb..c7e8dcb 100644 --- a/webkit/browser/blob/OWNERS +++ b/storage/browser/blob/OWNERS diff --git a/webkit/browser/blob/blob_data_handle.cc b/storage/browser/blob/blob_data_handle.cc index 667228a..cf647b4 100644 --- a/webkit/browser/blob/blob_data_handle.cc +++ b/storage/browser/blob/blob_data_handle.cc @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/blob/blob_data_handle.h" +#include "storage/browser/blob/blob_data_handle.h" #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/sequenced_task_runner.h" -#include "webkit/browser/blob/blob_storage_context.h" -#include "webkit/common/blob/blob_data.h" +#include "storage/browser/blob/blob_storage_context.h" +#include "storage/common/blob/blob_data.h" namespace storage { diff --git a/storage/browser/blob/blob_data_handle.h b/storage/browser/blob/blob_data_handle.h new file mode 100644 index 0000000..1120bdf --- /dev/null +++ b/storage/browser/blob/blob_data_handle.h @@ -0,0 +1,71 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_BLOB_BLOB_DATA_HANDLE_H_ +#define STORAGE_BROWSER_BLOB_BLOB_DATA_HANDLE_H_ + +#include <string> + +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "base/supports_user_data.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class SequencedTaskRunner; +} + +namespace storage { + +class BlobData; +class BlobStorageContext; + +// A scoper object for use in chrome's main browser process, ensures +// the underlying BlobData and its uuid remain in BlobStorageContext's +// collection for the duration. This object has delete semantics and +// maybe deleted on any thread. +class STORAGE_EXPORT BlobDataHandle + : public base::SupportsUserData::Data { + public: + BlobDataHandle(const BlobDataHandle& other); // May be copied on any thread. + virtual ~BlobDataHandle(); // Maybe be deleted on any thread. + BlobData* data() const; // May only be accessed on the IO thread. + + std::string uuid() const; // May be accessed on any thread. + + private: + class BlobDataHandleShared + : public base::RefCountedThreadSafe<BlobDataHandleShared> { + public: + BlobDataHandleShared(BlobData* blob_data, + BlobStorageContext* context, + base::SequencedTaskRunner* task_runner); + + BlobData* data() const; + const std::string& uuid() const; + + private: + friend class base::DeleteHelper<BlobDataHandleShared>; + friend class base::RefCountedThreadSafe<BlobDataHandleShared>; + friend class BlobDataHandle; + + virtual ~BlobDataHandleShared(); + + scoped_refptr<BlobData> blob_data_; + base::WeakPtr<BlobStorageContext> context_; + + DISALLOW_COPY_AND_ASSIGN(BlobDataHandleShared); + }; + + friend class BlobStorageContext; + BlobDataHandle(BlobData* blob_data, BlobStorageContext* context, + base::SequencedTaskRunner* task_runner); + + scoped_refptr<base::SequencedTaskRunner> io_task_runner_; + scoped_refptr<BlobDataHandleShared> shared_; +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_BLOB_BLOB_DATA_HANDLE_H_ diff --git a/webkit/browser/blob/blob_storage_context.cc b/storage/browser/blob/blob_storage_context.cc index 9c5f9bc..554c84e 100644 --- a/webkit/browser/blob/blob_storage_context.cc +++ b/storage/browser/blob/blob_storage_context.cc @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/blob/blob_storage_context.h" +#include "storage/browser/blob/blob_storage_context.h" #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/message_loop/message_loop_proxy.h" +#include "storage/browser/blob/blob_data_handle.h" +#include "storage/common/blob/blob_data.h" #include "url/gurl.h" -#include "webkit/browser/blob/blob_data_handle.h" -#include "webkit/common/blob/blob_data.h" namespace storage { diff --git a/storage/browser/blob/blob_storage_context.h b/storage/browser/blob/blob_storage_context.h new file mode 100644 index 0000000..7ccc133 --- /dev/null +++ b/storage/browser/blob/blob_storage_context.h @@ -0,0 +1,118 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_BLOB_BLOB_STORAGE_CONTEXT_H_ +#define STORAGE_BROWSER_BLOB_BLOB_STORAGE_CONTEXT_H_ + +#include <map> +#include <string> + +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "storage/browser/blob/blob_data_handle.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/blob/blob_data.h" + +class GURL; + +namespace base { +class FilePath; +class Time; +} + +namespace content { +class BlobStorageHost; +} + +namespace storage { + +class BlobDataHandle; + +// This class handles the logistics of blob Storage within the browser process, +// and maintains a mapping from blob uuid to the data. The class is single +// threaded and should only be used on the IO thread. +// In chromium, there is one instance per profile. +class STORAGE_EXPORT BlobStorageContext + : public base::SupportsWeakPtr<BlobStorageContext> { + public: + BlobStorageContext(); + ~BlobStorageContext(); + + scoped_ptr<BlobDataHandle> GetBlobDataFromUUID(const std::string& uuid); + scoped_ptr<BlobDataHandle> GetBlobDataFromPublicURL(const GURL& url); + + // Useful for coining blobs from within the browser process. If the + // blob cannot be added due to memory consumption, returns NULL. + scoped_ptr<BlobDataHandle> AddFinishedBlob(const BlobData* blob_data); + + // Useful for coining blob urls from within the browser process. + bool RegisterPublicBlobURL(const GURL& url, const std::string& uuid); + void RevokePublicBlobURL(const GURL& url); + + private: + friend class content::BlobStorageHost; + friend class BlobDataHandle::BlobDataHandleShared; + friend class ViewBlobInternalsJob; + + enum EntryFlags { + BEING_BUILT = 1 << 0, + EXCEEDED_MEMORY = 1 << 1, + }; + + struct BlobMapEntry { + int refcount; + int flags; + scoped_refptr<BlobData> data; + + BlobMapEntry(); + BlobMapEntry(int refcount, int flags, BlobData* data); + ~BlobMapEntry(); + }; + + typedef std::map<std::string, BlobMapEntry> + BlobMap; + typedef std::map<GURL, std::string> BlobURLMap; + + void StartBuildingBlob(const std::string& uuid); + void AppendBlobDataItem(const std::string& uuid, + const BlobData::Item& data_item); + void FinishBuildingBlob(const std::string& uuid, const std::string& type); + void CancelBuildingBlob(const std::string& uuid); + void IncrementBlobRefCount(const std::string& uuid); + void DecrementBlobRefCount(const std::string& uuid); + + bool ExpandStorageItems(BlobData* target_blob_data, + BlobData* src_blob_data, + uint64 offset, + uint64 length); + bool AppendBytesItem(BlobData* target_blob_data, + const char* data, int64 length); + void AppendFileItem(BlobData* target_blob_data, + const base::FilePath& file_path, + uint64 offset, uint64 length, + const base::Time& expected_modification_time); + void AppendFileSystemFileItem( + BlobData* target_blob_data, + const GURL& url, uint64 offset, uint64 length, + const base::Time& expected_modification_time); + + bool IsInUse(const std::string& uuid); + bool IsBeingBuilt(const std::string& uuid); + bool IsUrlRegistered(const GURL& blob_url); + + BlobMap blob_map_; + BlobURLMap public_blob_urls_; + + // Used to keep track of how much memory is being utilized for blob data, + // we count only the items of TYPE_DATA which are held in memory and not + // items of TYPE_FILE. + int64 memory_usage_; + + DISALLOW_COPY_AND_ASSIGN(BlobStorageContext); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_BLOB_BLOB_STORAGE_CONTEXT_H_ diff --git a/webkit/browser/blob/blob_url_request_job.cc b/storage/browser/blob/blob_url_request_job.cc index 9eb196a..0084277 100644 --- a/webkit/browser/blob/blob_url_request_job.cc +++ b/storage/browser/blob/blob_url_request_job.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/blob/blob_url_request_job.h" +#include "storage/browser/blob/blob_url_request_job.h" #include <limits> @@ -26,9 +26,9 @@ #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_error_job.h" #include "net/url_request/url_request_status.h" -#include "webkit/browser/blob/file_stream_reader.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_url.h" +#include "storage/browser/blob/file_stream_reader.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_url.h" namespace storage { diff --git a/storage/browser/blob/blob_url_request_job.h b/storage/browser/blob/blob_url_request_job.h new file mode 100644 index 0000000..58b6620 --- /dev/null +++ b/storage/browser/blob/blob_url_request_job.h @@ -0,0 +1,129 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_BLOB_BLOB_URL_REQUEST_JOB_H_ +#define STORAGE_BROWSER_BLOB_BLOB_URL_REQUEST_JOB_H_ + +#include <map> + +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "net/http/http_byte_range.h" +#include "net/http/http_status_code.h" +#include "net/url_request/url_request_job.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/blob/blob_data.h" + +namespace base { +class MessageLoopProxy; +} + +namespace storage { +class FileSystemContext; +} + +namespace net { +class DrainableIOBuffer; +class IOBuffer; +} + +namespace storage { + +class FileStreamReader; + +// A request job that handles reading blob URLs. +class STORAGE_EXPORT BlobURLRequestJob + : public net::URLRequestJob { + public: + BlobURLRequestJob(net::URLRequest* request, + net::NetworkDelegate* network_delegate, + const scoped_refptr<BlobData>& blob_data, + storage::FileSystemContext* file_system_context, + base::MessageLoopProxy* resolving_message_loop_proxy); + + // net::URLRequestJob methods. + virtual void Start() OVERRIDE; + virtual void Kill() OVERRIDE; + virtual bool ReadRawData(net::IOBuffer* buf, + int buf_size, + int* bytes_read) OVERRIDE; + virtual bool GetMimeType(std::string* mime_type) const OVERRIDE; + virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE; + virtual int GetResponseCode() const OVERRIDE; + virtual void SetExtraRequestHeaders( + const net::HttpRequestHeaders& headers) OVERRIDE; + + protected: + virtual ~BlobURLRequestJob(); + + private: + typedef std::map<size_t, FileStreamReader*> IndexToReaderMap; + + // For preparing for read: get the size, apply the range and perform seek. + void DidStart(); + bool AddItemLength(size_t index, int64 item_length); + void CountSize(); + void DidCountSize(int error); + void DidGetFileItemLength(size_t index, int64 result); + void Seek(int64 offset); + + // For reading the blob. + bool ReadLoop(int* bytes_read); + bool ReadItem(); + void AdvanceItem(); + void AdvanceBytesRead(int result); + bool ReadBytesItem(const BlobData::Item& item, int bytes_to_read); + bool ReadFileItem(FileStreamReader* reader, int bytes_to_read); + + void DidReadFile(int result); + void DeleteCurrentFileReader(); + + int ComputeBytesToRead() const; + int BytesReadCompleted(); + + // These methods convert the result of blob data reading into response headers + // and pass it to URLRequestJob's NotifyDone() or NotifyHeadersComplete(). + void NotifySuccess(); + void NotifyFailure(int); + void HeadersCompleted(net::HttpStatusCode status_code); + + // Returns a FileStreamReader for a blob item at |index|. + // If the item at |index| is not of file this returns NULL. + FileStreamReader* GetFileStreamReader(size_t index); + + // Creates a FileStreamReader for the item at |index| with additional_offset. + void CreateFileStreamReader(size_t index, int64 additional_offset); + + scoped_refptr<BlobData> blob_data_; + + // Variables for controlling read from |blob_data_|. + scoped_refptr<storage::FileSystemContext> file_system_context_; + scoped_refptr<base::MessageLoopProxy> file_thread_proxy_; + std::vector<int64> item_length_list_; + int64 total_size_; + int64 remaining_bytes_; + int pending_get_file_info_count_; + IndexToReaderMap index_to_reader_; + size_t current_item_index_; + int64 current_item_offset_; + + // Holds the buffer for read data with the IOBuffer interface. + scoped_refptr<net::DrainableIOBuffer> read_buf_; + + // Is set when NotifyFailure() is called and reset when DidStart is called. + bool error_; + + bool byte_range_set_; + net::HttpByteRange byte_range_; + + scoped_ptr<net::HttpResponseInfo> response_info_; + + base::WeakPtrFactory<BlobURLRequestJob> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(BlobURLRequestJob); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_BLOB_BLOB_URL_REQUEST_JOB_H_ diff --git a/webkit/browser/blob/blob_url_request_job_factory.cc b/storage/browser/blob/blob_url_request_job_factory.cc index d95f150..60f9c73 100644 --- a/webkit/browser/blob/blob_url_request_job_factory.cc +++ b/storage/browser/blob/blob_url_request_job_factory.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/blob/blob_url_request_job_factory.h" +#include "storage/browser/blob/blob_url_request_job_factory.h" #include "base/basictypes.h" #include "base/compiler_specific.h" @@ -11,10 +11,10 @@ #include "net/base/request_priority.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_job_factory.h" -#include "webkit/browser/blob/blob_data_handle.h" -#include "webkit/browser/blob/blob_storage_context.h" -#include "webkit/browser/blob/blob_url_request_job.h" -#include "webkit/browser/fileapi/file_system_context.h" +#include "storage/browser/blob/blob_data_handle.h" +#include "storage/browser/blob/blob_storage_context.h" +#include "storage/browser/blob/blob_url_request_job.h" +#include "storage/browser/fileapi/file_system_context.h" namespace storage { diff --git a/storage/browser/blob/blob_url_request_job_factory.h b/storage/browser/blob/blob_url_request_job_factory.h new file mode 100644 index 0000000..e1769eb --- /dev/null +++ b/storage/browser/blob/blob_url_request_job_factory.h @@ -0,0 +1,71 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_BLOB_BLOB_URL_REQUEST_JOB_FACTORY_H_ +#define STORAGE_BROWSER_BLOB_BLOB_URL_REQUEST_JOB_FACTORY_H_ + +#include "base/compiler_specific.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "net/url_request/url_request.h" +#include "net/url_request/url_request_job_factory.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class MessageLoopProxy; +} // namespace base + +namespace storage { +class FileSystemContext; +} // namespace storage + +namespace net { +class URLRequestContext; +} // namespace net + +namespace storage { + +class BlobData; +class BlobDataHandle; +class BlobStorageContext; + +class STORAGE_EXPORT BlobProtocolHandler + : public net::URLRequestJobFactory::ProtocolHandler { + public: + // A helper to manufacture an URLRequest to retrieve the given blob. + static scoped_ptr<net::URLRequest> CreateBlobRequest( + scoped_ptr<BlobDataHandle> blob_data_handle, + const net::URLRequestContext* request_context, + net::URLRequest::Delegate* request_delegate); + + // This class ignores the request's URL and uses the value given + // to SetRequestedBlobDataHandle instead. + static void SetRequestedBlobDataHandle( + net::URLRequest* request, + scoped_ptr<BlobDataHandle> blob_data_handle); + + BlobProtocolHandler( + BlobStorageContext* context, + storage::FileSystemContext* file_system_context, + const scoped_refptr<base::MessageLoopProxy>& file_loop_proxy); + virtual ~BlobProtocolHandler(); + + virtual net::URLRequestJob* MaybeCreateJob( + net::URLRequest* request, + net::NetworkDelegate* network_delegate) const OVERRIDE; + + private: + scoped_refptr<BlobData> LookupBlobData( + net::URLRequest* request) const; + + base::WeakPtr<BlobStorageContext> context_; + const scoped_refptr<storage::FileSystemContext> file_system_context_; + const scoped_refptr<base::MessageLoopProxy> file_loop_proxy_; + + DISALLOW_COPY_AND_ASSIGN(BlobProtocolHandler); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_BLOB_BLOB_URL_REQUEST_JOB_FACTORY_H_ diff --git a/webkit/browser/blob/file_stream_reader.cc b/storage/browser/blob/file_stream_reader.cc index afb2ab8..5c4aaa2 100644 --- a/webkit/browser/blob/file_stream_reader.cc +++ b/storage/browser/blob/file_stream_reader.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/blob/file_stream_reader.h" +#include "storage/browser/blob/file_stream_reader.h" #include "base/time/time.h" diff --git a/storage/browser/blob/file_stream_reader.h b/storage/browser/blob/file_stream_reader.h new file mode 100644 index 0000000..9b2ce02 --- /dev/null +++ b/storage/browser/blob/file_stream_reader.h @@ -0,0 +1,99 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BLOB_FILE_STREAM_READER_H_ +#define STORAGE_BLOB_FILE_STREAM_READER_H_ + +#include "base/basictypes.h" +#include "base/compiler_specific.h" +#include "base/files/file.h" +#include "net/base/completion_callback.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class FilePath; +class TaskRunner; +class Time; +} + +namespace net { +class IOBuffer; +} + +namespace storage { +class FileSystemContext; +class FileSystemURL; +} + +namespace storage { + +// A generic interface for reading a file-like object. +class FileStreamReader { + public: + // Creates a new FileReader for a local file |file_path|. + // |initial_offset| specifies the offset in the file where the first read + // should start. If the given offset is out of the file range any + // read operation may error out with net::ERR_REQUEST_RANGE_NOT_SATISFIABLE. + // |expected_modification_time| specifies the expected last modification + // If the value is non-null, the reader will check the underlying file's + // actual modification time to see if the file has been modified, and if + // it does any succeeding read operations should fail with + // ERR_UPLOAD_FILE_CHANGED error. + STORAGE_EXPORT static FileStreamReader* + CreateForLocalFile(base::TaskRunner* task_runner, + const base::FilePath& file_path, + int64 initial_offset, + const base::Time& expected_modification_time); + + // Creates a new reader for a filesystem URL |url| form |initial_offset|. + // |expected_modification_time| specifies the expected last modification if + // the value is non-null, the reader will check the underlying file's actual + // modification time to see if the file has been modified, and if it does any + // succeeding read operations should fail with ERR_UPLOAD_FILE_CHANGED error. + STORAGE_EXPORT static FileStreamReader* + CreateForFileSystemFile(storage::FileSystemContext* context, + const storage::FileSystemURL& url, + int64 initial_offset, + const base::Time& expected_modification_time); + + // Verify if the underlying file has not been modified. + STORAGE_EXPORT static bool VerifySnapshotTime( + const base::Time& expected_modification_time, + const base::File::Info& file_info); + + // It is valid to delete the reader at any time. If the stream is deleted + // while it has a pending read, its callback will not be called. + virtual ~FileStreamReader() {} + + // Reads from the current cursor position asynchronously. + // + // Up to buf_len bytes will be copied into buf. (In other words, partial + // reads are allowed.) Returns the number of bytes copied, 0 if at + // end-of-file, or an error code if the operation could not be performed. + // If the read could not complete synchronously, then ERR_IO_PENDING is + // returned, and the callback will be run on the thread where Read() + // was called, when the read has completed. + // + // It is invalid to call Read while there is an in-flight Read operation. + // + // If the stream is deleted while it has an in-flight Read operation + // |callback| will not be called. + virtual int Read(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback) = 0; + + // Returns the length of the file if it could successfully retrieve the + // file info *and* its last modification time equals to + // expected modification time (rv >= 0 cases). + // Otherwise, a negative error code is returned (rv < 0 cases). + // If the stream is deleted while it has an in-flight GetLength operation + // |callback| will not be called. + // Note that the return type is int64 to return a larger file's size (a file + // larger than 2G) but an error code should fit in the int range (may be + // smaller than int64 range). + virtual int64 GetLength(const net::Int64CompletionCallback& callback) = 0; +}; + +} // namespace storage + +#endif // STORAGE_BLOB_FILE_STREAM_READER_H_ diff --git a/webkit/browser/blob/local_file_stream_reader.cc b/storage/browser/blob/local_file_stream_reader.cc index 177f381..e6403b7 100644 --- a/webkit/browser/blob/local_file_stream_reader.cc +++ b/storage/browser/blob/local_file_stream_reader.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/blob/local_file_stream_reader.h" +#include "storage/browser/blob/local_file_stream_reader.h" #include "base/files/file_util.h" #include "base/files/file_util_proxy.h" diff --git a/storage/browser/blob/local_file_stream_reader.h b/storage/browser/blob/local_file_stream_reader.h new file mode 100644 index 0000000..b9e3328 --- /dev/null +++ b/storage/browser/blob/local_file_stream_reader.h @@ -0,0 +1,81 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_BLOB_LOCAL_FILE_STREAM_READER_H_ +#define STORAGE_BROWSER_BLOB_LOCAL_FILE_STREAM_READER_H_ + +#include "base/basictypes.h" +#include "base/compiler_specific.h" +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/memory/weak_ptr.h" +#include "base/time/time.h" +#include "storage/browser/blob/file_stream_reader.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class TaskRunner; +} + +namespace content { +class LocalFileStreamReaderTest; +} + +namespace net { +class FileStream; +} + +namespace storage { + +// A thin wrapper of net::FileStream with range support for sliced file +// handling. +class STORAGE_EXPORT LocalFileStreamReader + : public NON_EXPORTED_BASE(FileStreamReader) { + public: + virtual ~LocalFileStreamReader(); + + // FileStreamReader overrides. + virtual int Read(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback) OVERRIDE; + virtual int64 GetLength( + const net::Int64CompletionCallback& callback) OVERRIDE; + + private: + friend class FileStreamReader; + friend class content::LocalFileStreamReaderTest; + + LocalFileStreamReader(base::TaskRunner* task_runner, + const base::FilePath& file_path, + int64 initial_offset, + const base::Time& expected_modification_time); + int Open(const net::CompletionCallback& callback); + + // Callbacks that are chained from Open for Read. + void DidVerifyForOpen(const net::CompletionCallback& callback, + int64 get_length_result); + void DidOpenFileStream(const net::CompletionCallback& callback, + int result); + void DidSeekFileStream(const net::CompletionCallback& callback, + int64 seek_result); + void DidOpenForRead(net::IOBuffer* buf, + int buf_len, + const net::CompletionCallback& callback, + int open_result); + + void DidGetFileInfoForGetLength(const net::Int64CompletionCallback& callback, + base::File::Error error, + const base::File::Info& file_info); + + scoped_refptr<base::TaskRunner> task_runner_; + scoped_ptr<net::FileStream> stream_impl_; + const base::FilePath file_path_; + const int64 initial_offset_; + const base::Time expected_modification_time_; + bool has_pending_open_; + base::WeakPtrFactory<LocalFileStreamReader> weak_factory_; +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_BLOB_LOCAL_FILE_STREAM_READER_H_ diff --git a/webkit/browser/blob/view_blob_internals_job.cc b/storage/browser/blob/view_blob_internals_job.cc index d9a4319..2065a31 100644 --- a/webkit/browser/blob/view_blob_internals_job.cc +++ b/storage/browser/blob/view_blob_internals_job.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/blob/view_blob_internals_job.h" +#include "storage/browser/blob/view_blob_internals_job.h" #include "base/bind.h" #include "base/compiler_specific.h" @@ -18,8 +18,8 @@ #include "net/base/escape.h" #include "net/base/net_errors.h" #include "net/url_request/url_request.h" -#include "webkit/browser/blob/blob_storage_context.h" -#include "webkit/common/blob/blob_data.h" +#include "storage/browser/blob/blob_storage_context.h" +#include "storage/common/blob/blob_data.h" namespace { diff --git a/storage/browser/blob/view_blob_internals_job.h b/storage/browser/blob/view_blob_internals_job.h new file mode 100644 index 0000000..3fc2f08 --- /dev/null +++ b/storage/browser/blob/view_blob_internals_job.h @@ -0,0 +1,57 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_BLOB_VIEW_BLOB_INTERNALS_JOB_H_ +#define STORAGE_BROWSER_BLOB_VIEW_BLOB_INTERNALS_JOB_H_ + +#include <string> + +#include "base/memory/weak_ptr.h" +#include "net/url_request/url_request_simple_job.h" +#include "storage/browser/storage_browser_export.h" + +namespace net { +class URLRequest; +} // namespace net + +namespace storage { + +class BlobData; +class BlobStorageContext; + +// A job subclass that implements a protocol to inspect the internal +// state of blob registry. +class STORAGE_EXPORT ViewBlobInternalsJob + : public net::URLRequestSimpleJob { + public: + ViewBlobInternalsJob(net::URLRequest* request, + net::NetworkDelegate* network_delegate, + BlobStorageContext* blob_storage_context); + + virtual void Start() OVERRIDE; + virtual int GetData(std::string* mime_type, + std::string* charset, + std::string* data, + const net::CompletionCallback& callback) const OVERRIDE; + virtual bool IsRedirectResponse(GURL* location, + int* http_status_code) OVERRIDE; + virtual void Kill() OVERRIDE; + + private: + virtual ~ViewBlobInternalsJob(); + + void GenerateHTML(std::string* out) const; + static void GenerateHTMLForBlobData(const BlobData& blob_data, + int refcount, + std::string* out); + + BlobStorageContext* blob_storage_context_; + base::WeakPtrFactory<ViewBlobInternalsJob> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(ViewBlobInternalsJob); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_BLOB_VIEW_BLOB_INTERNALS_JOB_H_ diff --git a/webkit/browser/database/database_quota_client.cc b/storage/browser/database/database_quota_client.cc index 19f746a..5119a1c 100644 --- a/webkit/browser/database/database_quota_client.cc +++ b/storage/browser/database/database_quota_client.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/database/database_quota_client.h" +#include "storage/browser/database/database_quota_client.h" #include <vector> @@ -14,9 +14,9 @@ #include "base/task_runner_util.h" #include "net/base/net_errors.h" #include "net/base/net_util.h" -#include "webkit/browser/database/database_tracker.h" -#include "webkit/browser/database/database_util.h" -#include "webkit/common/database/database_identifier.h" +#include "storage/browser/database/database_tracker.h" +#include "storage/browser/database/database_util.h" +#include "storage/common/database/database_identifier.h" using storage::QuotaClient; diff --git a/storage/browser/database/database_quota_client.h b/storage/browser/database/database_quota_client.h new file mode 100644 index 0000000..ae276c7 --- /dev/null +++ b/storage/browser/database/database_quota_client.h @@ -0,0 +1,57 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_DATABASE_DATABASE_QUOTA_CLIENT_H_ +#define STORAGE_BROWSER_DATABASE_DATABASE_QUOTA_CLIENT_H_ + +#include <set> +#include <string> + +#include "base/memory/ref_counted.h" +#include "base/message_loop/message_loop_proxy.h" +#include "storage/browser/quota/quota_client.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/quota/quota_types.h" + +namespace storage { + +class DatabaseTracker; + +// A QuotaClient implementation to integrate WebSQLDatabases +// with the quota management system. This interface is used +// on the IO thread by the quota manager. +class STORAGE_EXPORT_PRIVATE DatabaseQuotaClient + : public storage::QuotaClient { + public: + DatabaseQuotaClient( + base::MessageLoopProxy* tracker_thread, + DatabaseTracker* tracker); + virtual ~DatabaseQuotaClient(); + + // QuotaClient method overrides + virtual ID id() const OVERRIDE; + virtual void OnQuotaManagerDestroyed() OVERRIDE; + virtual void GetOriginUsage(const GURL& origin_url, + storage::StorageType type, + const GetUsageCallback& callback) OVERRIDE; + virtual void GetOriginsForType(storage::StorageType type, + const GetOriginsCallback& callback) OVERRIDE; + virtual void GetOriginsForHost(storage::StorageType type, + const std::string& host, + const GetOriginsCallback& callback) OVERRIDE; + virtual void DeleteOriginData(const GURL& origin, + storage::StorageType type, + const DeletionCallback& callback) OVERRIDE; + virtual bool DoesSupport(storage::StorageType type) const OVERRIDE; + + private: + scoped_refptr<base::MessageLoopProxy> db_tracker_thread_; + scoped_refptr<DatabaseTracker> db_tracker_; // only used on its thread + + DISALLOW_COPY_AND_ASSIGN(DatabaseQuotaClient); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_DATABASE_DATABASE_QUOTA_CLIENT_H_ diff --git a/webkit/browser/database/database_tracker.cc b/storage/browser/database/database_tracker.cc index 9f76495..b7e4623 100644 --- a/webkit/browser/database/database_tracker.cc +++ b/storage/browser/database/database_tracker.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/database/database_tracker.h" +#include "storage/browser/database/database_tracker.h" #include <algorithm> #include <vector> @@ -19,13 +19,13 @@ #include "sql/connection.h" #include "sql/meta_table.h" #include "sql/transaction.h" +#include "storage/browser/database/database_quota_client.h" +#include "storage/browser/database/database_util.h" +#include "storage/browser/database/databases_table.h" +#include "storage/browser/quota/quota_manager_proxy.h" +#include "storage/browser/quota/special_storage_policy.h" +#include "storage/common/database/database_identifier.h" #include "third_party/sqlite/sqlite3.h" -#include "webkit/browser/database/database_quota_client.h" -#include "webkit/browser/database/database_util.h" -#include "webkit/browser/database/databases_table.h" -#include "webkit/browser/quota/quota_manager_proxy.h" -#include "webkit/browser/quota/special_storage_policy.h" -#include "webkit/common/database/database_identifier.h" namespace storage { diff --git a/storage/browser/database/database_tracker.h b/storage/browser/database/database_tracker.h new file mode 100644 index 0000000..f998b4b --- /dev/null +++ b/storage/browser/database/database_tracker.h @@ -0,0 +1,319 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_DATABASE_DATABASE_TRACKER_H_ +#define STORAGE_BROWSER_DATABASE_DATABASE_TRACKER_H_ + +#include <map> +#include <set> +#include <utility> + +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/gtest_prod_util.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/observer_list.h" +#include "base/strings/string16.h" +#include "base/strings/string_util.h" +#include "base/time/time.h" +#include "net/base/completion_callback.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/database/database_connections.h" + +namespace base { +class MessageLoopProxy; +} + +namespace content { +class DatabaseTracker_TestHelper_Test; +class MockDatabaseTracker; +} + +namespace sql { +class Connection; +class MetaTable; +} + +namespace storage { +class QuotaManagerProxy; +class SpecialStoragePolicy; +} + +namespace storage { + +STORAGE_EXPORT extern const base::FilePath::CharType + kDatabaseDirectoryName[]; +STORAGE_EXPORT extern const base::FilePath::CharType + kTrackerDatabaseFileName[]; + +class DatabasesTable; + +// This class is used to store information about all databases in an origin. +class STORAGE_EXPORT OriginInfo { + public: + OriginInfo(); + OriginInfo(const OriginInfo& origin_info); + ~OriginInfo(); + + const std::string& GetOriginIdentifier() const { return origin_identifier_; } + int64 TotalSize() const { return total_size_; } + void GetAllDatabaseNames(std::vector<base::string16>* databases) const; + int64 GetDatabaseSize(const base::string16& database_name) const; + base::string16 GetDatabaseDescription( + const base::string16& database_name) const; + + protected: + typedef std::map<base::string16, std::pair<int64, base::string16> > + DatabaseInfoMap; + + OriginInfo(const std::string& origin_identifier, int64 total_size); + + std::string origin_identifier_; + int64 total_size_; + DatabaseInfoMap database_info_; +}; + +// This class manages the main database and keeps track of open databases. +// +// The data in this class is not thread-safe, so all methods of this class +// should be called on the same thread. The only exceptions are the ctor(), +// the dtor() and the database_directory() and quota_manager_proxy() getters. +// +// Furthermore, some methods of this class have to read/write data from/to +// the disk. Therefore, in a multi-threaded application, all methods of this +// class should be called on the thread dedicated to file operations (file +// thread in the browser process, for example), if such a thread exists. +class STORAGE_EXPORT DatabaseTracker + : public base::RefCountedThreadSafe<DatabaseTracker> { + public: + class Observer { + public: + virtual void OnDatabaseSizeChanged(const std::string& origin_identifier, + const base::string16& database_name, + int64 database_size) = 0; + virtual void OnDatabaseScheduledForDeletion( + const std::string& origin_identifier, + const base::string16& database_name) = 0; + + protected: + virtual ~Observer() {} + }; + + DatabaseTracker(const base::FilePath& profile_path, + bool is_incognito, + storage::SpecialStoragePolicy* special_storage_policy, + storage::QuotaManagerProxy* quota_manager_proxy, + base::MessageLoopProxy* db_tracker_thread); + + void DatabaseOpened(const std::string& origin_identifier, + const base::string16& database_name, + const base::string16& database_details, + int64 estimated_size, + int64* database_size); + void DatabaseModified(const std::string& origin_identifier, + const base::string16& database_name); + void DatabaseClosed(const std::string& origin_identifier, + const base::string16& database_name); + void HandleSqliteError(const std::string& origin_identifier, + const base::string16& database_name, + int error); + + void CloseDatabases(const DatabaseConnections& connections); + + void AddObserver(Observer* observer); + void RemoveObserver(Observer* observer); + + void CloseTrackerDatabaseAndClearCaches(); + + const base::FilePath& DatabaseDirectory() const { return db_dir_; } + base::FilePath GetFullDBFilePath(const std::string& origin_identifier, + const base::string16& database_name); + + // virtual for unit-testing only + virtual bool GetOriginInfo(const std::string& origin_id, OriginInfo* info); + virtual bool GetAllOriginIdentifiers(std::vector<std::string>* origin_ids); + virtual bool GetAllOriginsInfo(std::vector<OriginInfo>* origins_info); + + // Safe to call on any thread. + storage::QuotaManagerProxy* quota_manager_proxy() const { + return quota_manager_proxy_.get(); + } + + bool IsDatabaseScheduledForDeletion(const std::string& origin_identifier, + const base::string16& database_name); + + // Deletes a single database. Returns net::OK on success, net::FAILED on + // failure, or net::ERR_IO_PENDING and |callback| is invoked upon completion, + // if non-NULL. + int DeleteDatabase(const std::string& origin_identifier, + const base::string16& database_name, + const net::CompletionCallback& callback); + + // Delete any databases that have been touched since the cutoff date that's + // supplied, omitting any that match IDs within |protected_origins|. + // Returns net::OK on success, net::FAILED if not all databases could be + // deleted, and net::ERR_IO_PENDING and |callback| is invoked upon completion, + // if non-NULL. Protected origins, according the the SpecialStoragePolicy, + // are not deleted by this method. + int DeleteDataModifiedSince(const base::Time& cutoff, + const net::CompletionCallback& callback); + + // Delete all databases that belong to the given origin. Returns net::OK on + // success, net::FAILED if not all databases could be deleted, and + // net::ERR_IO_PENDING and |callback| is invoked upon completion, if non-NULL. + // virtual for unit testing only + virtual int DeleteDataForOrigin(const std::string& origin_identifier, + const net::CompletionCallback& callback); + + bool IsIncognitoProfile() const { return is_incognito_; } + + const base::File* GetIncognitoFile(const base::string16& vfs_file_path) const; + const base::File* SaveIncognitoFile(const base::string16& vfs_file_path, + base::File file); + void CloseIncognitoFileHandle(const base::string16& vfs_file_path); + bool HasSavedIncognitoFileHandle(const base::string16& vfs_file_path) const; + + // Shutdown the database tracker, deleting database files if the tracker is + // used for an incognito profile. + void Shutdown(); + // Disables the exit-time deletion of session-only data. + void SetForceKeepSessionState(); + + private: + friend class base::RefCountedThreadSafe<DatabaseTracker>; + friend class content::DatabaseTracker_TestHelper_Test; + friend class content::MockDatabaseTracker; // for testing + + typedef std::map<std::string, std::set<base::string16> > DatabaseSet; + typedef std::vector<std::pair<net::CompletionCallback, DatabaseSet> > + PendingDeletionCallbacks; + typedef std::map<base::string16, base::File*> FileHandlesMap; + typedef std::map<std::string, base::string16> OriginDirectoriesMap; + + class CachedOriginInfo : public OriginInfo { + public: + CachedOriginInfo() : OriginInfo(std::string(), 0) {} + void SetOriginIdentifier(const std::string& origin_identifier) { + origin_identifier_ = origin_identifier; + } + void SetDatabaseSize(const base::string16& database_name, int64 new_size) { + int64 old_size = 0; + if (database_info_.find(database_name) != database_info_.end()) + old_size = database_info_[database_name].first; + database_info_[database_name].first = new_size; + if (new_size != old_size) + total_size_ += new_size - old_size; + } + void SetDatabaseDescription(const base::string16& database_name, + const base::string16& description) { + database_info_[database_name].second = description; + } + }; + + // virtual for unit-testing only. + virtual ~DatabaseTracker(); + + // Deletes the directory that stores all DBs in incognito mode, if it exists. + void DeleteIncognitoDBDirectory(); + + // Deletes session-only databases. Blocks databases from being created/opened. + void ClearSessionOnlyOrigins(); + + bool DeleteClosedDatabase(const std::string& origin_identifier, + const base::string16& database_name); + + // Delete all files belonging to the given origin given that no database + // connections within this origin are open, or if |force| is true, delete + // the meta data and rename the associated directory. + bool DeleteOrigin(const std::string& origin_identifier, bool force); + void DeleteDatabaseIfNeeded(const std::string& origin_identifier, + const base::string16& database_name); + + bool LazyInit(); + bool UpgradeToCurrentVersion(); + void InsertOrUpdateDatabaseDetails(const std::string& origin_identifier, + const base::string16& database_name, + const base::string16& database_details, + int64 estimated_size); + + void ClearAllCachedOriginInfo(); + CachedOriginInfo* MaybeGetCachedOriginInfo( + const std::string& origin_identifier, + bool create_if_needed); + CachedOriginInfo* GetCachedOriginInfo( + const std::string& origin_identifier) { + return MaybeGetCachedOriginInfo(origin_identifier, true); + } + + int64 GetDBFileSize(const std::string& origin_identifier, + const base::string16& database_name); + int64 SeedOpenDatabaseInfo(const std::string& origin_identifier, + const base::string16& database_name, + const base::string16& description); + int64 UpdateOpenDatabaseInfoAndNotify(const std::string& origin_identifier, + const base::string16& database_name, + const base::string16* opt_description); + int64 UpdateOpenDatabaseSizeAndNotify(const std::string& origin_identifier, + const base::string16& database_name) { + return UpdateOpenDatabaseInfoAndNotify( + origin_identifier, database_name, NULL); + } + + + void ScheduleDatabaseForDeletion(const std::string& origin_identifier, + const base::string16& database_name); + // Schedule a set of open databases for deletion. If non-null, callback is + // invoked upon completion. + void ScheduleDatabasesForDeletion(const DatabaseSet& databases, + const net::CompletionCallback& callback); + + // Returns the directory where all DB files for the given origin are stored. + base::string16 GetOriginDirectory(const std::string& origin_identifier); + + bool is_initialized_; + const bool is_incognito_; + bool force_keep_session_state_; + bool shutting_down_; + const base::FilePath profile_path_; + const base::FilePath db_dir_; + scoped_ptr<sql::Connection> db_; + scoped_ptr<DatabasesTable> databases_table_; + scoped_ptr<sql::MetaTable> meta_table_; + ObserverList<Observer, true> observers_; + std::map<std::string, CachedOriginInfo> origins_info_map_; + DatabaseConnections database_connections_; + + // The set of databases that should be deleted but are still opened + DatabaseSet dbs_to_be_deleted_; + PendingDeletionCallbacks deletion_callbacks_; + + // Apps and Extensions can have special rights. + scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy_; + + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy_; + + // The database tracker thread we're supposed to run file IO on. + scoped_refptr<base::MessageLoopProxy> db_tracker_thread_; + + // When in incognito mode, store a DELETE_ON_CLOSE handle to each + // main DB and journal file that was accessed. When the incognito profile + // goes away (or when the browser crashes), all these handles will be + // closed, and the files will be deleted. + FileHandlesMap incognito_file_handles_; + + // In a non-incognito profile, all DBs in an origin are stored in a directory + // named after the origin. In an incognito profile though, we do not want the + // directory structure to reveal the origins visited by the user (in case the + // browser process crashes and those directories are not deleted). So we use + // this map to assign directory names that do not reveal this information. + OriginDirectoriesMap incognito_origin_directories_; + int incognito_origin_directories_generator_; + + FRIEND_TEST_ALL_PREFIXES(DatabaseTracker, TestHelper); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_DATABASE_DATABASE_TRACKER_H_ diff --git a/webkit/browser/database/database_util.cc b/storage/browser/database/database_util.cc index c6d797a..113f533 100644 --- a/webkit/browser/database/database_util.cc +++ b/storage/browser/database/database_util.cc @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/database/database_util.h" +#include "storage/browser/database/database_util.h" #include "base/basictypes.h" #include "base/strings/utf_string_conversions.h" -#include "webkit/browser/database/database_tracker.h" -#include "webkit/browser/database/vfs_backend.h" -#include "webkit/common/database/database_identifier.h" +#include "storage/browser/database/database_tracker.h" +#include "storage/browser/database/vfs_backend.h" +#include "storage/common/database/database_identifier.h" namespace storage { diff --git a/storage/browser/database/database_util.h b/storage/browser/database/database_util.h new file mode 100644 index 0000000..6c67fac --- /dev/null +++ b/storage/browser/database/database_util.h @@ -0,0 +1,39 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_DATABASE_DATABASE_UTIL_H_ +#define STORAGE_BROWSER_DATABASE_DATABASE_UTIL_H_ + +#include <string> +#include "base/strings/string16.h" +#include "storage/browser/storage_browser_export.h" +#include "url/gurl.h" + +namespace base { +class FilePath; +} + +namespace storage { + +class DatabaseTracker; + +class STORAGE_EXPORT DatabaseUtil { + public: + static const char kJournalFileSuffix[]; + + // Extract various information from a database vfs_file_name. All return + // parameters are optional. + static bool CrackVfsFileName(const base::string16& vfs_file_name, + std::string* origin_identifier, + base::string16* database_name, + base::string16* sqlite_suffix); + static base::FilePath GetFullFilePathForVfsFile( + DatabaseTracker* db_tracker, + const base::string16& vfs_file_name); + static bool IsValidOriginIdentifier(const std::string& origin_identifier); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_DATABASE_DATABASE_UTIL_H_ diff --git a/webkit/browser/database/databases_table.cc b/storage/browser/database/databases_table.cc index c5e239b..6d84ae8 100644 --- a/webkit/browser/database/databases_table.cc +++ b/storage/browser/database/databases_table.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/database/databases_table.h" +#include "storage/browser/database/databases_table.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" diff --git a/storage/browser/database/databases_table.h b/storage/browser/database/databases_table.h new file mode 100644 index 0000000..2ade812 --- /dev/null +++ b/storage/browser/database/databases_table.h @@ -0,0 +1,54 @@ +// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_DATABASE_DATABASES_TABLE_H_ +#define STORAGE_BROWSER_DATABASE_DATABASES_TABLE_H_ + +#include <vector> + +#include "base/strings/string16.h" +#include "storage/browser/storage_browser_export.h" + +namespace sql { +class Connection; +} + +namespace storage { + +struct STORAGE_EXPORT_PRIVATE DatabaseDetails { + DatabaseDetails(); + ~DatabaseDetails(); + + std::string origin_identifier; + base::string16 database_name; + base::string16 description; + int64 estimated_size; +}; + +class STORAGE_EXPORT_PRIVATE DatabasesTable { + public: + explicit DatabasesTable(sql::Connection* db) : db_(db) { } + + bool Init(); + int64 GetDatabaseID(const std::string& origin_identifier, + const base::string16& database_name); + bool GetDatabaseDetails(const std::string& origin_identifier, + const base::string16& database_name, + DatabaseDetails* details); + bool InsertDatabaseDetails(const DatabaseDetails& details); + bool UpdateDatabaseDetails(const DatabaseDetails& details); + bool DeleteDatabaseDetails(const std::string& origin_identifier, + const base::string16& database_name); + bool GetAllOriginIdentifiers(std::vector<std::string>* origin_identifiers); + bool GetAllDatabaseDetailsForOriginIdentifier( + const std::string& origin_identifier, + std::vector<DatabaseDetails>* details); + bool DeleteOriginIdentifier(const std::string& origin_identifier); + private: + sql::Connection* db_; +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_DATABASE_DATABASES_TABLE_H_ diff --git a/webkit/browser/database/vfs_backend.cc b/storage/browser/database/vfs_backend.cc index 4c8e578..1f8c97b 100644 --- a/webkit/browser/database/vfs_backend.cc +++ b/storage/browser/database/vfs_backend.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/database/vfs_backend.h" +#include "storage/browser/database/vfs_backend.h" #include "base/files/file_path.h" #include "base/files/file_util.h" diff --git a/storage/browser/database/vfs_backend.h b/storage/browser/database/vfs_backend.h new file mode 100644 index 0000000..0ee1dd3 --- /dev/null +++ b/storage/browser/database/vfs_backend.h @@ -0,0 +1,42 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_DATABASE_VFS_BACKEND_H_ +#define STORAGE_BROWSER_DATABASE_VFS_BACKEND_H_ + +#include "base/files/file.h" +#include "base/process/process.h" +#include "base/strings/string16.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class FilePath; +} + +namespace storage { + +class STORAGE_EXPORT VfsBackend { + public: + static base::File OpenFile(const base::FilePath& file_path, + int desired_flags); + + static base::File OpenTempFileInDirectory(const base::FilePath& dir_path, + int desired_flags); + + static int DeleteFile(const base::FilePath& file_path, bool sync_dir); + + static uint32 GetFileAttributes(const base::FilePath& file_path); + + static int64 GetFileSize(const base::FilePath& file_path); + + // Used to make decisions in the DatabaseDispatcherHost. + static bool OpenTypeIsReadWrite(int desired_flags); + + private: + static bool OpenFileFlagsAreConsistent(int desired_flags); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_DATABASE_VFS_BACKEND_H_ diff --git a/webkit/browser/fileapi/OWNERS b/storage/browser/fileapi/OWNERS index 232db84..232db84 100644 --- a/webkit/browser/fileapi/OWNERS +++ b/storage/browser/fileapi/OWNERS diff --git a/storage/browser/fileapi/async_file_util.h b/storage/browser/fileapi/async_file_util.h new file mode 100644 index 0000000..eab6af7 --- /dev/null +++ b/storage/browser/fileapi/async_file_util.h @@ -0,0 +1,366 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_ASYNC_FILE_UTIL_H_ +#define STORAGE_BROWSER_FILEAPI_ASYNC_FILE_UTIL_H_ + +#include <vector> + +#include "base/basictypes.h" +#include "base/callback_forward.h" +#include "base/files/file.h" +#include "base/files/file_util_proxy.h" +#include "base/memory/scoped_ptr.h" +#include "storage/browser/fileapi/file_system_operation.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/fileapi/directory_entry.h" + +namespace base { +class Time; +} + +namespace storage { +class ShareableFileReference; +} + +namespace storage { + +class FileSystemOperationContext; +class FileSystemURL; + +// An interface which provides filesystem-specific file operations for +// FileSystemOperationImpl. +// +// Each filesystem which needs to be dispatched from FileSystemOperationImpl +// must implement this interface or a synchronous version of interface: +// FileSystemFileUtil. +// +// As far as an instance of this class is owned by a FileSystemBackend +// (which is owned by FileSystemContext), it's guaranteed that this instance's +// alive while FileSystemOperationContext given to each operation is kept +// alive. (Note that this instance might be freed on different thread +// from the thread it is created.) +// +// It is NOT valid to give null callback to this class, and implementors +// can assume that they don't get any null callbacks. +// +class AsyncFileUtil { + public: + typedef base::Callback<void(base::File::Error result)> StatusCallback; + + // |on_close_callback| will be called after the |file| is closed in the + // child process. |on_close_callback|.is_null() can be true, if no operation + // is needed on closing the file. + typedef base::Callback< + void(base::File file, + const base::Closure& on_close_callback)> CreateOrOpenCallback; + + typedef base::Callback< + void(base::File::Error result, + bool created)> EnsureFileExistsCallback; + + typedef base::Callback< + void(base::File::Error result, + const base::File::Info& file_info)> GetFileInfoCallback; + + typedef std::vector<DirectoryEntry> EntryList; + typedef base::Callback< + void(base::File::Error result, + const EntryList& file_list, + bool has_more)> ReadDirectoryCallback; + + typedef base::Callback< + void(base::File::Error result, + const base::File::Info& file_info, + const base::FilePath& platform_path, + const scoped_refptr<storage::ShareableFileReference>& file_ref)> + CreateSnapshotFileCallback; + + typedef base::Callback<void(int64 size)> CopyFileProgressCallback; + + typedef FileSystemOperation::CopyOrMoveOption CopyOrMoveOption; + + // Creates an AsyncFileUtil instance which performs file operations on + // local native file system. The created instance assumes + // FileSystemURL::path() has the target platform path. + STORAGE_EXPORT static AsyncFileUtil* + CreateForLocalFileSystem(); + + AsyncFileUtil() {} + virtual ~AsyncFileUtil() {} + + // Creates or opens a file with the given flags. + // If File::FLAG_CREATE is set in |file_flags| it always tries to create + // a new file at the given |url| and calls back with + // File::FILE_ERROR_FILE_EXISTS if the |url| already exists. + // + // FileSystemOperationImpl::OpenFile calls this. + // This is used only by Pepper/NaCl File API. + // + virtual void CreateOrOpen( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + int file_flags, + const CreateOrOpenCallback& callback) = 0; + + // Ensures that the given |url| exist. This creates a empty new file + // at |url| if the |url| does not exist. + // + // FileSystemOperationImpl::CreateFile calls this. + // + // This reports following error code via |callback|: + // - File::FILE_OK and created==true if a file has not existed and + // is created at |url|. + // - File::FILE_OK and created==false if the file already exists. + // - Other error code (with created=false) if a file hasn't existed yet + // and there was an error while creating a new file. + // + virtual void EnsureFileExists( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const EnsureFileExistsCallback& callback) = 0; + + // Creates directory at given url. + // + // FileSystemOperationImpl::CreateDirectory calls this. + // + // This reports following error code via |callback|: + // - File::FILE_ERROR_NOT_FOUND if the |url|'s parent directory + // does not exist and |recursive| is false. + // - File::FILE_ERROR_EXISTS if a directory already exists at |url| + // and |exclusive| is true. + // - File::FILE_ERROR_EXISTS if a file already exists at |url| + // (regardless of |exclusive| value). + // - Other error code if it failed to create a directory. + // + virtual void CreateDirectory( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + bool exclusive, + bool recursive, + const StatusCallback& callback) = 0; + + // Retrieves the information about a file. + // + // FileSystemOperationImpl::GetMetadata calls this. + // + // This reports following error code via |callback|: + // - File::FILE_ERROR_NOT_FOUND if the file doesn't exist. + // - Other error code if there was an error while retrieving the file info. + // + virtual void GetFileInfo( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const GetFileInfoCallback& callback) = 0; + + // Reads contents of a directory at |path|. + // + // FileSystemOperationImpl::ReadDirectory calls this. + // + // Note that the |name| field of each entry in |file_list| + // returned by |callback| should have a base file name + // of the entry relative to the directory, but not an absolute path. + // + // (E.g. if ReadDirectory is called for a directory + // 'path/to/dir' and the directory has entries 'a' and 'b', + // the returned |file_list| should include entries whose names + // are 'a' and 'b', but not '/path/to/dir/a' and '/path/to/dir/b'.) + // + // This reports following error code via |callback|: + // - File::FILE_ERROR_NOT_FOUND if the target directory doesn't exist. + // - File::FILE_ERROR_NOT_A_DIRECTORY if an entry exists at |url| but + // is a file (not a directory). + // + virtual void ReadDirectory( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const ReadDirectoryCallback& callback) = 0; + + // Modifies timestamps of a file or directory at |url| with + // |last_access_time| and |last_modified_time|. The function DOES NOT + // create a file unlike 'touch' command on Linux. + // + // FileSystemOperationImpl::TouchFile calls this. + // This is used only by Pepper/NaCl File API. + // + virtual void Touch( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const base::Time& last_access_time, + const base::Time& last_modified_time, + const StatusCallback& callback) = 0; + + // Truncates a file at |path| to |length|. If |length| is larger than + // the original file size, the file will be extended, and the extended + // part is filled with null bytes. + // + // FileSystemOperationImpl::Truncate calls this. + // + // This reports following error code via |callback|: + // - File::FILE_ERROR_NOT_FOUND if the file doesn't exist. + // + virtual void Truncate( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + int64 length, + const StatusCallback& callback) = 0; + + // Copies a file from |src_url| to |dest_url|. + // This must be called for files that belong to the same filesystem + // (i.e. type() and origin() of the |src_url| and |dest_url| must match). + // |progress_callback| is a callback to report the progress update. + // See file_system_operations.h for details. This should be called on the + // same thread as where the method's called (IO thread). Calling this + // is optional. It is recommended to use this callback for heavier operations + // (such as file network downloading), so that, e.g., clients (UIs) can + // update its state to show progress to users. This may be a null callback. + // + // FileSystemOperationImpl::Copy calls this for same-filesystem copy case. + // + // This reports following error code via |callback|: + // - File::FILE_ERROR_NOT_FOUND if |src_url| + // or the parent directory of |dest_url| does not exist. + // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. + // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and + // is not a file. + // - File::FILE_ERROR_FAILED if |dest_url| does not exist and + // its parent path is a file. + // + virtual void CopyFileLocal( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + const CopyFileProgressCallback& progress_callback, + const StatusCallback& callback) = 0; + + // Moves a local file from |src_url| to |dest_url|. + // This must be called for files that belong to the same filesystem + // (i.e. type() and origin() of the |src_url| and |dest_url| must match). + // + // FileSystemOperationImpl::Move calls this for same-filesystem move case. + // + // This reports following error code via |callback|: + // - File::FILE_ERROR_NOT_FOUND if |src_url| + // or the parent directory of |dest_url| does not exist. + // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. + // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and + // is not a file. + // - File::FILE_ERROR_FAILED if |dest_url| does not exist and + // its parent path is a file. + // + virtual void MoveFileLocal( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + const StatusCallback& callback) = 0; + + // Copies in a single file from a different filesystem. + // + // FileSystemOperationImpl::Copy or Move calls this for cross-filesystem + // cases. + // + // This reports following error code via |callback|: + // - File::FILE_ERROR_NOT_FOUND if |src_file_path| + // or the parent directory of |dest_url| does not exist. + // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and + // is not a file. + // - File::FILE_ERROR_FAILED if |dest_url| does not exist and + // its parent path is a file. + // + virtual void CopyInForeignFile( + scoped_ptr<FileSystemOperationContext> context, + const base::FilePath& src_file_path, + const FileSystemURL& dest_url, + const StatusCallback& callback) = 0; + + // Deletes a single file. + // + // FileSystemOperationImpl::RemoveFile calls this. + // + // This reports following error code via |callback|: + // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. + // - File::FILE_ERROR_NOT_A_FILE if |url| is not a file. + // + virtual void DeleteFile( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const StatusCallback& callback) = 0; + + // Removes a single empty directory. + // + // FileSystemOperationImpl::RemoveDirectory calls this. + // + // This reports following error code via |callback|: + // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. + // - File::FILE_ERROR_NOT_A_DIRECTORY if |url| is not a directory. + // - File::FILE_ERROR_NOT_EMPTY if |url| is not empty. + // + virtual void DeleteDirectory( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const StatusCallback& callback) = 0; + + // Removes a single file or a single directory with its contents + // (i.e. files/subdirectories under the directory). + // + // FileSystemOperationImpl::Remove calls this. + // On some platforms, such as Chrome OS Drive File System, recursive file + // deletion can be implemented more efficiently than calling DeleteFile() and + // DeleteDirectory() for each files/directories. + // This method is optional, so if not supported, + // File::FILE_ERROR_INVALID_OPERATION should be returned via |callback|. + // + // This reports following error code via |callback|: + // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. + // - File::FILE_ERROR_INVALID_OPERATION if this operation is not supported. + virtual void DeleteRecursively( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const StatusCallback& callback) = 0; + + // Creates a local snapshot file for a given |url| and returns the + // metadata and platform path of the snapshot file via |callback|. + // In regular filesystem cases the implementation may simply return + // the metadata of the file itself (as well as GetMetadata does), + // while in non-regular filesystem case the backend may create a + // temporary snapshot file which holds the file data and return + // the metadata of the temporary file. + // + // In the callback, it returns: + // |file_info| is the metadata of the snapshot file created. + // |platform_path| is the full absolute platform path to the snapshot + // file created. If a file is not backed by a real local file in + // the implementor's FileSystem, the implementor must create a + // local snapshot file and return the path of the created file. + // + // If implementors creates a temporary file for snapshotting and wants + // FileAPI backend to take care of the lifetime of the file (so that + // it won't get deleted while JS layer has any references to the created + // File/Blob object), it should return non-empty |file_ref|. + // Via the |file_ref| implementors can schedule a file deletion + // or arbitrary callbacks when the last reference of File/Blob is dropped. + // + // FileSystemOperationImpl::CreateSnapshotFile calls this. + // + // This reports following error code via |callback|: + // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. + // - File::FILE_ERROR_NOT_A_FILE if |url| exists but is a directory. + // + // The field values of |file_info| are undefined (implementation + // dependent) in error cases, and the caller should always + // check the return code. + virtual void CreateSnapshotFile( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const CreateSnapshotFileCallback& callback) = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(AsyncFileUtil); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_ASYNC_FILE_UTIL_H_ diff --git a/webkit/browser/fileapi/async_file_util_adapter.cc b/storage/browser/fileapi/async_file_util_adapter.cc index 62244b7..3bb20f9 100644 --- a/webkit/browser/fileapi/async_file_util_adapter.cc +++ b/storage/browser/fileapi/async_file_util_adapter.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/async_file_util_adapter.h" +#include "storage/browser/fileapi/async_file_util_adapter.h" #include <vector> @@ -10,12 +10,12 @@ #include "base/sequenced_task_runner.h" #include "base/task_runner_util.h" #include "base/thread_task_runner_handle.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_file_util.h" -#include "webkit/browser/fileapi/file_system_operation_context.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/common/blob/shareable_file_reference.h" -#include "webkit/common/fileapi/file_system_util.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_file_util.h" +#include "storage/browser/fileapi/file_system_operation_context.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/common/blob/shareable_file_reference.h" +#include "storage/common/fileapi/file_system_util.h" using base::Bind; using base::Callback; diff --git a/storage/browser/fileapi/async_file_util_adapter.h b/storage/browser/fileapi/async_file_util_adapter.h new file mode 100644 index 0000000..4ba4542 --- /dev/null +++ b/storage/browser/fileapi/async_file_util_adapter.h @@ -0,0 +1,118 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_ASYNC_FILE_UTIL_ADAPTER_H_ +#define STORAGE_BROWSER_FILEAPI_ASYNC_FILE_UTIL_ADAPTER_H_ + +#include "base/memory/scoped_ptr.h" +#include "storage/browser/fileapi/async_file_util.h" + +namespace storage { + +class FileSystemFileUtil; + +// An adapter class for FileSystemFileUtil classes to provide asynchronous +// interface. +// +// A filesystem can do either: +// - implement a synchronous version of FileUtil by extending +// FileSystemFileUtil and atach it to this adapter, or +// - directly implement AsyncFileUtil. +// +// This instance (as thus this->sync_file_util_) is guaranteed to be alive +// as far as FileSystemOperationContext given to each operation is kept alive. +class STORAGE_EXPORT AsyncFileUtilAdapter + : public NON_EXPORTED_BASE(AsyncFileUtil) { + public: + // Creates a new AsyncFileUtil for |sync_file_util|. This takes the + // ownership of |sync_file_util|. (This doesn't take scoped_ptr<> just + // to save extra make_scoped_ptr; in all use cases a new fresh FileUtil is + // created only for this adapter.) + explicit AsyncFileUtilAdapter(FileSystemFileUtil* sync_file_util); + + virtual ~AsyncFileUtilAdapter(); + + FileSystemFileUtil* sync_file_util() { + return sync_file_util_.get(); + } + + // AsyncFileUtil overrides. + virtual void CreateOrOpen( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + int file_flags, + const CreateOrOpenCallback& callback) OVERRIDE; + virtual void EnsureFileExists( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const EnsureFileExistsCallback& callback) OVERRIDE; + virtual void CreateDirectory( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + bool exclusive, + bool recursive, + const StatusCallback& callback) OVERRIDE; + virtual void GetFileInfo( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const GetFileInfoCallback& callback) OVERRIDE; + virtual void ReadDirectory( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const ReadDirectoryCallback& callback) OVERRIDE; + virtual void Touch( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const base::Time& last_access_time, + const base::Time& last_modified_time, + const StatusCallback& callback) OVERRIDE; + virtual void Truncate( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + int64 length, + const StatusCallback& callback) OVERRIDE; + virtual void CopyFileLocal( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + const CopyFileProgressCallback& progress_callback, + const StatusCallback& callback) OVERRIDE; + virtual void MoveFileLocal( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + const StatusCallback& callback) OVERRIDE; + virtual void CopyInForeignFile( + scoped_ptr<FileSystemOperationContext> context, + const base::FilePath& src_file_path, + const FileSystemURL& dest_url, + const StatusCallback& callback) OVERRIDE; + virtual void DeleteFile( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const StatusCallback& callback) OVERRIDE; + virtual void DeleteDirectory( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const StatusCallback& callback) OVERRIDE; + virtual void DeleteRecursively( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const StatusCallback& callback) OVERRIDE; + virtual void CreateSnapshotFile( + scoped_ptr<FileSystemOperationContext> context, + const FileSystemURL& url, + const CreateSnapshotFileCallback& callback) OVERRIDE; + + private: + scoped_ptr<FileSystemFileUtil> sync_file_util_; + + DISALLOW_COPY_AND_ASSIGN(AsyncFileUtilAdapter); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_ASYNC_FILE_UTIL_ADAPTER_H_ diff --git a/storage/browser/fileapi/copy_or_move_file_validator.h b/storage/browser/fileapi/copy_or_move_file_validator.h new file mode 100644 index 0000000..f79c473 --- /dev/null +++ b/storage/browser/fileapi/copy_or_move_file_validator.h @@ -0,0 +1,54 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_COPY_OR_MOVE_FILE_VALIDATOR_H_ +#define STORAGE_BROWSER_FILEAPI_COPY_OR_MOVE_FILE_VALIDATOR_H_ + +#include "base/callback.h" +#include "base/files/file.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class FilePath; +} + +namespace storage { + +class FileSystemURL; + +class STORAGE_EXPORT CopyOrMoveFileValidator { + public: + // Callback that is invoked when validation completes. A result of + // base::File::FILE_OK means the file validated. + typedef base::Callback<void(base::File::Error result)> ResultCallback; + + virtual ~CopyOrMoveFileValidator() {} + + // Called on a source file before copying or moving to the final + // destination. + virtual void StartPreWriteValidation( + const ResultCallback& result_callback) = 0; + + // Called on a destination file after copying or moving to the final + // destination. Suitable for running Anti-Virus checks. + virtual void StartPostWriteValidation( + const base::FilePath& dest_platform_path, + const ResultCallback& result_callback) = 0; +}; + +class CopyOrMoveFileValidatorFactory { + public: + virtual ~CopyOrMoveFileValidatorFactory() {} + + // This method must always return a non-NULL validator. |src_url| is needed + // in addition to |platform_path| because in the obfuscated file system + // case, |platform_path| will be an obfuscated filename and extension. + virtual CopyOrMoveFileValidator* CreateCopyOrMoveFileValidator( + const FileSystemURL& src_url, + const base::FilePath& platform_path) = 0; +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_COPY_OR_MOVE_FILE_VALIDATOR_H_ diff --git a/webkit/browser/fileapi/copy_or_move_operation_delegate.cc b/storage/browser/fileapi/copy_or_move_operation_delegate.cc index 84a6472..84244df 100644 --- a/webkit/browser/fileapi/copy_or_move_operation_delegate.cc +++ b/storage/browser/fileapi/copy_or_move_operation_delegate.cc @@ -2,22 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/copy_or_move_operation_delegate.h" +#include "storage/browser/fileapi/copy_or_move_operation_delegate.h" #include "base/bind.h" #include "base/files/file_path.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" -#include "webkit/browser/blob/file_stream_reader.h" -#include "webkit/browser/fileapi/copy_or_move_file_validator.h" -#include "webkit/browser/fileapi/file_observers.h" -#include "webkit/browser/fileapi/file_stream_writer.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation_runner.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/fileapi/recursive_operation_delegate.h" -#include "webkit/common/blob/shareable_file_reference.h" -#include "webkit/common/fileapi/file_system_util.h" +#include "storage/browser/blob/file_stream_reader.h" +#include "storage/browser/fileapi/copy_or_move_file_validator.h" +#include "storage/browser/fileapi/file_observers.h" +#include "storage/browser/fileapi/file_stream_writer.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation_runner.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/recursive_operation_delegate.h" +#include "storage/common/blob/shareable_file_reference.h" +#include "storage/common/fileapi/file_system_util.h" namespace storage { diff --git a/storage/browser/fileapi/copy_or_move_operation_delegate.h b/storage/browser/fileapi/copy_or_move_operation_delegate.h new file mode 100644 index 0000000..0b97d1c --- /dev/null +++ b/storage/browser/fileapi/copy_or_move_operation_delegate.h @@ -0,0 +1,162 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_COPY_OR_MOVE_OPERATION_DELEGATE_H_ +#define STORAGE_BROWSER_FILEAPI_COPY_OR_MOVE_OPERATION_DELEGATE_H_ + +#include <set> +#include <stack> + +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/time/time.h" +#include "storage/browser/fileapi/recursive_operation_delegate.h" + +namespace net { +class DrainableIOBuffer; +class IOBufferWithSize; +} + +namespace storage { +class FileStreamReader; +class ShareableFileReference; +} + +namespace storage { + +class CopyOrMoveFileValidator; +class FileStreamWriter; + +// A delegate class for recursive copy or move operations. +class CopyOrMoveOperationDelegate + : public RecursiveOperationDelegate { + public: + class CopyOrMoveImpl; + typedef FileSystemOperation::CopyProgressCallback CopyProgressCallback; + typedef FileSystemOperation::CopyOrMoveOption CopyOrMoveOption; + + enum OperationType { + OPERATION_COPY, + OPERATION_MOVE + }; + + // Helper to copy a file by reader and writer streams. + // Export for testing. + class STORAGE_EXPORT StreamCopyHelper { + public: + StreamCopyHelper( + scoped_ptr<storage::FileStreamReader> reader, + scoped_ptr<FileStreamWriter> writer, + bool need_flush, + int buffer_size, + const FileSystemOperation::CopyFileProgressCallback& + file_progress_callback, + const base::TimeDelta& min_progress_callback_invocation_span); + ~StreamCopyHelper(); + + void Run(const StatusCallback& callback); + + // Requests cancelling. After the cancelling is done, |callback| passed to + // Run will be called. + void Cancel(); + + private: + // Reads the content from the |reader_|. + void Read(const StatusCallback& callback); + void DidRead(const StatusCallback& callback, int result); + + // Writes the content in |buffer| to |writer_|. + void Write(const StatusCallback& callback, + scoped_refptr<net::DrainableIOBuffer> buffer); + void DidWrite(const StatusCallback& callback, + scoped_refptr<net::DrainableIOBuffer> buffer, int result); + + // Flushes the written content in |writer_|. + void Flush(const StatusCallback& callback, bool is_eof); + void DidFlush(const StatusCallback& callback, bool is_eof, int result); + + scoped_ptr<storage::FileStreamReader> reader_; + scoped_ptr<FileStreamWriter> writer_; + const bool need_flush_; + FileSystemOperation::CopyFileProgressCallback file_progress_callback_; + scoped_refptr<net::IOBufferWithSize> io_buffer_; + int64 num_copied_bytes_; + int64 previous_flush_offset_; + base::Time last_progress_callback_invocation_time_; + base::TimeDelta min_progress_callback_invocation_span_; + bool cancel_requested_; + base::WeakPtrFactory<StreamCopyHelper> weak_factory_; + DISALLOW_COPY_AND_ASSIGN(StreamCopyHelper); + }; + + CopyOrMoveOperationDelegate( + FileSystemContext* file_system_context, + const FileSystemURL& src_root, + const FileSystemURL& dest_root, + OperationType operation_type, + CopyOrMoveOption option, + const CopyProgressCallback& progress_callback, + const StatusCallback& callback); + virtual ~CopyOrMoveOperationDelegate(); + + // RecursiveOperationDelegate overrides: + virtual void Run() OVERRIDE; + virtual void RunRecursively() OVERRIDE; + virtual void ProcessFile(const FileSystemURL& url, + const StatusCallback& callback) OVERRIDE; + virtual void ProcessDirectory(const FileSystemURL& url, + const StatusCallback& callback) OVERRIDE; + virtual void PostProcessDirectory(const FileSystemURL& url, + const StatusCallback& callback) OVERRIDE; + + + protected: + virtual void OnCancel() OVERRIDE; + + private: + void DidCopyOrMoveFile(const FileSystemURL& src_url, + const FileSystemURL& dest_url, + const StatusCallback& callback, + CopyOrMoveImpl* impl, + base::File::Error error); + void DidTryRemoveDestRoot(const StatusCallback& callback, + base::File::Error error); + void ProcessDirectoryInternal(const FileSystemURL& src_url, + const FileSystemURL& dest_url, + const StatusCallback& callback); + void DidCreateDirectory(const FileSystemURL& src_url, + const FileSystemURL& dest_url, + const StatusCallback& callback, + base::File::Error error); + void PostProcessDirectoryAfterGetMetadata( + const FileSystemURL& src_url, + const StatusCallback& callback, + base::File::Error error, + const base::File::Info& file_info); + void PostProcessDirectoryAfterTouchFile(const FileSystemURL& src_url, + const StatusCallback& callback, + base::File::Error error); + void DidRemoveSourceForMove(const StatusCallback& callback, + base::File::Error error); + + void OnCopyFileProgress(const FileSystemURL& src_url, int64 size); + FileSystemURL CreateDestURL(const FileSystemURL& src_url) const; + + FileSystemURL src_root_; + FileSystemURL dest_root_; + bool same_file_system_; + OperationType operation_type_; + CopyOrMoveOption option_; + CopyProgressCallback progress_callback_; + StatusCallback callback_; + + std::set<CopyOrMoveImpl*> running_copy_set_; + base::WeakPtrFactory<CopyOrMoveOperationDelegate> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(CopyOrMoveOperationDelegate); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_COPY_OR_MOVE_OPERATION_DELEGATE_H_ diff --git a/webkit/browser/fileapi/dragged_file_util.cc b/storage/browser/fileapi/dragged_file_util.cc index 7b02798..1f15188 100644 --- a/webkit/browser/fileapi/dragged_file_util.cc +++ b/storage/browser/fileapi/dragged_file_util.cc @@ -2,18 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/dragged_file_util.h" +#include "storage/browser/fileapi/dragged_file_util.h" #include <string> #include <vector> #include "base/files/file_util.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation_context.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/fileapi/isolated_context.h" -#include "webkit/browser/fileapi/native_file_util.h" -#include "webkit/common/blob/shareable_file_reference.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation_context.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/isolated_context.h" +#include "storage/browser/fileapi/native_file_util.h" +#include "storage/common/blob/shareable_file_reference.h" namespace storage { diff --git a/storage/browser/fileapi/dragged_file_util.h b/storage/browser/fileapi/dragged_file_util.h new file mode 100644 index 0000000..205e8ef --- /dev/null +++ b/storage/browser/fileapi/dragged_file_util.h @@ -0,0 +1,41 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_DRAGGED_FILE_UTIL_H_ +#define STORAGE_BROWSER_FILEAPI_DRAGGED_FILE_UTIL_H_ + +#include "base/memory/scoped_ptr.h" +#include "storage/browser/fileapi/local_file_util.h" +#include "storage/browser/storage_browser_export.h" + +namespace storage { + +class FileSystemOperationContext; + +// Dragged file system is a specialized LocalFileUtil where read access to +// the virtual root directory (i.e. empty cracked path case) is allowed +// and single isolated context may be associated with multiple file paths. +class STORAGE_EXPORT_PRIVATE DraggedFileUtil + : public LocalFileUtil { + public: + DraggedFileUtil(); + virtual ~DraggedFileUtil() {} + + // FileSystemFileUtil overrides. + virtual base::File::Error GetFileInfo( + FileSystemOperationContext* context, + const FileSystemURL& url, + base::File::Info* file_info, + base::FilePath* platform_path) OVERRIDE; + virtual scoped_ptr<AbstractFileEnumerator> CreateFileEnumerator( + FileSystemOperationContext* context, + const FileSystemURL& root_url) OVERRIDE; + + private: + DISALLOW_COPY_AND_ASSIGN(DraggedFileUtil); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_DRAGGED_FILE_UTIL_H_ diff --git a/webkit/browser/fileapi/dump_file_system.cc b/storage/browser/fileapi/dump_file_system.cc index 0f30ef2..49a2fa3 100644 --- a/webkit/browser/fileapi/dump_file_system.cc +++ b/storage/browser/fileapi/dump_file_system.cc @@ -38,12 +38,12 @@ #include "base/files/file_util.h" #include "base/format_macros.h" #include "base/strings/stringprintf.h" -#include "webkit/browser/fileapi/obfuscated_file_util.h" -#include "webkit/browser/fileapi/sandbox_directory_database.h" -#include "webkit/browser/fileapi/sandbox_file_system_backend.h" -#include "webkit/browser/fileapi/sandbox_origin_database.h" -#include "webkit/common/fileapi/file_system_types.h" -#include "webkit/common/fileapi/file_system_util.h" +#include "storage/browser/fileapi/obfuscated_file_util.h" +#include "storage/browser/fileapi/sandbox_directory_database.h" +#include "storage/browser/fileapi/sandbox_file_system_backend.h" +#include "storage/browser/fileapi/sandbox_origin_database.h" +#include "storage/common/fileapi/file_system_types.h" +#include "storage/common/fileapi/file_system_util.h" namespace { diff --git a/webkit/browser/fileapi/external_mount_points.cc b/storage/browser/fileapi/external_mount_points.cc index 29ea8ae..baa0c49 100644 --- a/webkit/browser/fileapi/external_mount_points.cc +++ b/storage/browser/fileapi/external_mount_points.cc @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/external_mount_points.h" +#include "storage/browser/fileapi/external_mount_points.h" #include "base/files/file_path.h" #include "base/lazy_instance.h" #include "base/path_service.h" #include "base/stl_util.h" -#include "webkit/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/file_system_url.h" namespace { diff --git a/storage/browser/fileapi/external_mount_points.h b/storage/browser/fileapi/external_mount_points.h new file mode 100644 index 0000000..26468c5 --- /dev/null +++ b/storage/browser/fileapi/external_mount_points.h @@ -0,0 +1,159 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_EXTERNAL_MOUNT_POINTS_H_ +#define STORAGE_BROWSER_FILEAPI_EXTERNAL_MOUNT_POINTS_H_ + +#include <map> +#include <string> +#include <vector> + +#include "base/memory/ref_counted.h" +#include "base/synchronization/lock.h" +#include "storage/browser/fileapi/mount_points.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/fileapi/file_system_mount_option.h" +#include "storage/common/fileapi/file_system_types.h" + +namespace base { +class FilePath; +} + +namespace storage { + +class FileSystemURL; + +// Manages external filesystem namespaces that are identified by 'mount name' +// and are persisted until RevokeFileSystem is called. +// Files in an external filesystem are identified by a filesystem URL like: +// +// filesystem:<origin>/external/<mount_name>/relative/path +// +class STORAGE_EXPORT ExternalMountPoints + : public base::RefCountedThreadSafe<ExternalMountPoints>, + public MountPoints { + public: + static ExternalMountPoints* GetSystemInstance(); + static scoped_refptr<ExternalMountPoints> CreateRefCounted(); + + // Registers a new named external filesystem. + // The |path| is registered as the root path of the mount point which + // is identified by a URL "filesystem:.../external/mount_name". + // + // For example, if the path "/media/removable" is registered with + // the mount_name "removable", a filesystem URL like + // "filesystem:.../external/removable/a/b" will be resolved as + // "/media/removable/a/b". + // + // The |mount_name| should NOT contain a path separator '/'. + // Returns false if the given name is already registered. + // + // Overlapping mount points in a single MountPoints instance are not allowed. + // Adding mount point whose path overlaps with an existing mount point will + // fail except for media galleries, which do not count toward registered + // paths for overlap calculation. + // + // If not empty, |path| must be absolute. It is allowed for the path to be + // empty, but |GetVirtualPath| will not work for those mount points. + // + // An external file system registered by this method can be revoked + // by calling RevokeFileSystem with |mount_name|. + bool RegisterFileSystem(const std::string& mount_name, + FileSystemType type, + const FileSystemMountOption& mount_option, + const base::FilePath& path); + + // MountPoints overrides. + virtual bool HandlesFileSystemMountType(FileSystemType type) const OVERRIDE; + virtual bool RevokeFileSystem(const std::string& mount_name) OVERRIDE; + virtual bool GetRegisteredPath(const std::string& mount_name, + base::FilePath* path) const OVERRIDE; + virtual bool CrackVirtualPath( + const base::FilePath& virtual_path, + std::string* mount_name, + FileSystemType* type, + std::string* cracked_id, + base::FilePath* path, + FileSystemMountOption* mount_option) const OVERRIDE; + virtual FileSystemURL CrackURL(const GURL& url) const OVERRIDE; + virtual FileSystemURL CreateCrackedFileSystemURL( + const GURL& origin, + FileSystemType type, + const base::FilePath& path) const OVERRIDE; + + // Returns a list of registered MountPointInfos (of <mount_name, path>). + void AddMountPointInfosTo(std::vector<MountPointInfo>* mount_points) const; + + // Converts a path on a registered file system to virtual path relative to the + // file system root. E.g. if 'Downloads' file system is mapped to + // '/usr/local/home/Downloads', and |absolute| path is set to + // '/usr/local/home/Downloads/foo', the method will set |virtual_path| to + // 'Downloads/foo'. + // Returns false if the path cannot be resolved (e.g. if the path is not + // part of any registered filesystem). + // + // Media gallery type file systems do not count for this calculation. i.e. + // if only a media gallery is registered for the path, false will be returned. + // If a media gallery and another file system are registered for related + // paths, only the other registration is taken into account. + // + // Returned virtual_path will have normalized path separators. + bool GetVirtualPath(const base::FilePath& absolute_path, + base::FilePath* virtual_path) const; + + // Returns the virtual root path that looks like /<mount_name>. + base::FilePath CreateVirtualRootPath(const std::string& mount_name) const; + + FileSystemURL CreateExternalFileSystemURL( + const GURL& origin, + const std::string& mount_name, + const base::FilePath& path) const; + + // Revoke all registered filesystems. Used only by testing (for clean-ups). + void RevokeAllFileSystems(); + + private: + friend class base::RefCountedThreadSafe<ExternalMountPoints>; + + // Represents each file system instance (defined in the .cc). + class Instance; + + typedef std::map<std::string, Instance*> NameToInstance; + + // Reverse map from registered path to its corresponding mount name. + typedef std::map<base::FilePath, std::string> PathToName; + + // Use |GetSystemInstance| of |CreateRefCounted| to get an instance. + ExternalMountPoints(); + virtual ~ExternalMountPoints(); + + // MountPoint overrides. + virtual FileSystemURL CrackFileSystemURL( + const FileSystemURL& url) const OVERRIDE; + + // Performs sanity checks on the new mount point. + // Checks the following: + // - there is no registered mount point with mount_name + // - path does not contain a reference to a parent + // - path is absolute + // - path does not overlap with an existing mount point path unless it is a + // media gallery type. + // + // |lock_| should be taken before calling this method. + bool ValidateNewMountPoint(const std::string& mount_name, + FileSystemType type, + const base::FilePath& path); + + // This lock needs to be obtained when accessing the instance_map_. + mutable base::Lock lock_; + + NameToInstance instance_map_; + PathToName path_to_name_map_; + + DISALLOW_COPY_AND_ASSIGN(ExternalMountPoints); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_EXTERNAL_MOUNT_POINTS_H_ diff --git a/storage/browser/fileapi/file_observers.h b/storage/browser/fileapi/file_observers.h new file mode 100644 index 0000000..7a07193 --- /dev/null +++ b/storage/browser/fileapi/file_observers.h @@ -0,0 +1,83 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_OBSERVERS_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_OBSERVERS_H_ + +#include "base/basictypes.h" +#include "storage/browser/storage_browser_export.h" + +// TODO(kinuko): Split this file into per-observer multiple files. + +namespace storage { + +class FileSystemURL; + +// An abstract interface to observe update operations. +// +// OnStartUpdate and OnEndUpdate are called once for each target url +// before and after following operations regardless of whether the operation +// is made recursively or not (i.e. StartUpdate() will be called only once +// for destination url regardless of whether it is recursive copy or not): +// CreateFile(), CreateDirectory(), +// Copy() (destination only), +// Move() (both for source and destination), +// Remove(), Write(), Truncate(), TouchFile() +// +// OnUpdate() is called each time the |url| is updated but works only for +// sandboxed files (where usage is tracked). +class STORAGE_EXPORT FileUpdateObserver { + public: + FileUpdateObserver() {} + virtual ~FileUpdateObserver() {} + + virtual void OnStartUpdate(const FileSystemURL& url) = 0; + virtual void OnUpdate(const FileSystemURL& url, int64 delta) = 0; + virtual void OnEndUpdate(const FileSystemURL& url) = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(FileUpdateObserver); +}; + +// An abstract interface to observe file access. +// OnAccess is called whenever an operation reads file contents or metadata. +// (It is called only once per operation regardless of whether the operation +// is recursive or not) +class STORAGE_EXPORT FileAccessObserver { + public: + FileAccessObserver() {} + virtual ~FileAccessObserver() {} + + virtual void OnAccess(const FileSystemURL& url) = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(FileAccessObserver); +}; + +// An abstract interface to observe file changes. +// Each method of this class is called once per file/directory is created, +// removed or modified. For recursive operations each method is called for +// each subdirectory/subfile. Currently ChangeObserver is only supported +// by the local sandbox file system. +class STORAGE_EXPORT FileChangeObserver { + public: + FileChangeObserver() {} + virtual ~FileChangeObserver() {} + + virtual void OnCreateFile(const FileSystemURL& url) = 0; + virtual void OnCreateFileFrom(const FileSystemURL& url, + const FileSystemURL& src) = 0; + virtual void OnRemoveFile(const FileSystemURL& url) = 0; + virtual void OnModifyFile(const FileSystemURL& url) = 0; + + virtual void OnCreateDirectory(const FileSystemURL& url) = 0; + virtual void OnRemoveDirectory(const FileSystemURL& url) = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(FileChangeObserver); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_OBSERVERS_H_ diff --git a/storage/browser/fileapi/file_permission_policy.h b/storage/browser/fileapi/file_permission_policy.h new file mode 100644 index 0000000..8580954 --- /dev/null +++ b/storage/browser/fileapi/file_permission_policy.h @@ -0,0 +1,28 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_PERMISSION_POLICY_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_PERMISSION_POLICY_H_ + +#include "storage/browser/storage_browser_export.h" + +namespace storage { + +enum FilePermissionPolicy { + // Any access should be always denied. + FILE_PERMISSION_ALWAYS_DENY = 0x0, + + // Access is sandboxed, no extra permission check is necessary. + FILE_PERMISSION_SANDBOX = 1 << 0, + + // Access should be restricted to read-only. + FILE_PERMISSION_READ_ONLY = 1 << 1, + + // Access should be examined by per-file permission policy. + FILE_PERMISSION_USE_FILE_PERMISSION = 1 << 2, +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_PERMISSION_POLICY_H_ diff --git a/storage/browser/fileapi/file_stream_writer.h b/storage/browser/fileapi/file_stream_writer.h new file mode 100644 index 0000000..ec59ec0 --- /dev/null +++ b/storage/browser/fileapi/file_stream_writer.h @@ -0,0 +1,87 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_STREAM_WRITER_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_STREAM_WRITER_H_ + +#include "base/basictypes.h" +#include "net/base/completion_callback.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class FilePath; +class TaskRunner; +} + +namespace net { +class IOBuffer; +} + +namespace storage { + +// A generic interface for writing to a file-like object. +class FileStreamWriter { + public: + enum OpenOrCreate { OPEN_EXISTING_FILE, CREATE_NEW_FILE }; + + // Creates a writer for the existing file in the path |file_path| starting + // from |initial_offset|. Uses |task_runner| for async file operations. + STORAGE_EXPORT static FileStreamWriter* CreateForLocalFile( + base::TaskRunner* task_runner, + const base::FilePath& file_path, + int64 initial_offset, + OpenOrCreate open_or_create); + + // Closes the file. If there's an in-flight operation, it is canceled (i.e., + // the callback function associated with the operation is not called). + virtual ~FileStreamWriter() {} + + // Writes to the current cursor position asynchronously. + // + // Up to buf_len bytes will be written. (In other words, partial + // writes are allowed.) If the write completed synchronously, it returns + // the number of bytes written. If the operation could not be performed, it + // returns an error code. Otherwise, net::ERR_IO_PENDING is returned, and the + // callback will be run on the thread where Write() was called when the write + // has completed. + // + // This errors out (either synchronously or via callback) with: + // net::ERR_FILE_NOT_FOUND: When the target file is not found. + // net::ERR_ACCESS_DENIED: When the target file is a directory or + // the writer has no permission on the file. + // net::ERR_FILE_NO_SPACE: When the write will result in out of quota + // or there is not enough room left on the disk. + // + // It is invalid to call Write while there is an in-flight async operation. + virtual int Write(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback) = 0; + + // Cancels an in-flight async operation. + // + // If the cancel is finished synchronously, it returns net::OK. If the + // cancel could not be performed, it returns an error code. Especially when + // there is no in-flight operation, net::ERR_UNEXPECTED is returned. + // Otherwise, net::ERR_IO_PENDING is returned, and the callback will be run on + // the thread where Cancel() was called when the cancel has completed. It is + // invalid to call Cancel() more than once on the same async operation. + // + // In either case, the callback function passed to the in-flight async + // operation is dismissed immediately when Cancel() is called, and thus + // will never be called. + virtual int Cancel(const net::CompletionCallback& callback) = 0; + + // Flushes the data written so far. + // + // If the flush finished synchronously, it return net::OK. If the flush could + // not be performed, it returns an error code. Otherwise, net::ERR_IO_PENDING + // is returned, and the callback will be run on the thread where Flush() was + // called when the flush has completed. + // + // It is invalid to call Flush while there is an in-flight async operation. + virtual int Flush(const net::CompletionCallback& callback) = 0; +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_STREAM_WRITER_H_ diff --git a/storage/browser/fileapi/file_system_backend.h b/storage/browser/fileapi/file_system_backend.h new file mode 100644 index 0000000..8f455d9 --- /dev/null +++ b/storage/browser/fileapi/file_system_backend.h @@ -0,0 +1,169 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_BACKEND_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_BACKEND_H_ + +#include <string> +#include <vector> + +#include "base/callback_forward.h" +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/memory/scoped_ptr.h" +#include "storage/browser/fileapi/file_permission_policy.h" +#include "storage/browser/fileapi/open_file_system_mode.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/fileapi/file_system_types.h" + +class GURL; + +namespace storage { + +class AsyncFileUtil; +class CopyOrMoveFileValidatorFactory; +class FileSystemURL; +class FileStreamReader; +class FileStreamWriter; +class FileSystemContext; +class FileSystemFileUtil; +class FileSystemOperation; +class FileSystemQuotaUtil; +class WatcherManager; + +// Callback to take GURL. +typedef base::Callback<void(const GURL& url)> URLCallback; + +// An interface for defining a file system backend. +// +// NOTE: when you implement a new FileSystemBackend for your own +// FileSystem module, please contact to kinuko@chromium.org. +// +class STORAGE_EXPORT FileSystemBackend { + public: + // Callback for InitializeFileSystem. + typedef base::Callback<void(const GURL& root_url, + const std::string& name, + base::File::Error error)> + OpenFileSystemCallback; + virtual ~FileSystemBackend() {} + + // Returns true if this filesystem backend can handle |type|. + // One filesystem backend may be able to handle multiple filesystem types. + virtual bool CanHandleType(FileSystemType type) const = 0; + + // This method is called right after the backend is registered in the + // FileSystemContext and before any other methods are called. Each backend can + // do additional initialization which depends on FileSystemContext here. + virtual void Initialize(FileSystemContext* context) = 0; + + // Resolves the filesystem root URL and the name for the given |url|. + // This verifies if it is allowed to request (or create) the filesystem and if + // it can access (or create) the root directory. + // If |mode| is CREATE_IF_NONEXISTENT calling this may also create the root + // directory (and/or related database entries etc) for the filesystem if it + // doesn't exist. + virtual void ResolveURL(const FileSystemURL& url, + OpenFileSystemMode mode, + const OpenFileSystemCallback& callback) = 0; + + // Returns the specialized AsyncFileUtil for this backend. + virtual AsyncFileUtil* GetAsyncFileUtil(FileSystemType type) = 0; + + // Returns the specialized WatcherManager for this backend. + virtual WatcherManager* GetWatcherManager(FileSystemType type) = 0; + + // Returns the specialized CopyOrMoveFileValidatorFactory for this backend + // and |type|. If |error_code| is File::FILE_OK and the result is NULL, + // then no validator is required. + virtual CopyOrMoveFileValidatorFactory* GetCopyOrMoveFileValidatorFactory( + FileSystemType type, base::File::Error* error_code) = 0; + + // Returns a new instance of the specialized FileSystemOperation for this + // backend based on the given triplet of |origin_url|, |file_system_type| + // and |virtual_path|. On failure to create a file system operation, set + // |error_code| correspondingly. + // This method is usually dispatched by + // FileSystemContext::CreateFileSystemOperation. + virtual FileSystemOperation* CreateFileSystemOperation( + const FileSystemURL& url, + FileSystemContext* context, + base::File::Error* error_code) const = 0; + + // Returns true if Blobs accessing |url| should use FileStreamReader. + // If false, Blobs are accessed using a snapshot file by calling + // AsyncFileUtil::CreateSnapshotFile. + virtual bool SupportsStreaming(const FileSystemURL& url) const = 0; + + // Returns true if specified |type| of filesystem can handle Copy() + // of the files in the same file system instead of streaming + // read/write implementation. + virtual bool HasInplaceCopyImplementation(FileSystemType type) const = 0; + + // Creates a new file stream reader for a given filesystem URL |url| with an + // offset |offset|. |expected_modification_time| specifies the expected last + // modification if the value is non-null, the reader will check the underlying + // file's actual modification time to see if the file has been modified, and + // if it does any succeeding read operations should fail with + // ERR_UPLOAD_FILE_CHANGED error. + // This method itself does *not* check if the given path exists and is a + // regular file. + // The |length| argument says how many bytes are going to be read using the + // instance of the file stream reader. If unknown, then equal to -1. + virtual scoped_ptr<storage::FileStreamReader> CreateFileStreamReader( + const FileSystemURL& url, + int64 offset, + const base::Time& expected_modification_time, + FileSystemContext* context) const = 0; + + // Creates a new file stream writer for a given filesystem URL |url| with an + // offset |offset|. + // This method itself does *not* check if the given path exists and is a + // regular file. + virtual scoped_ptr<FileStreamWriter> CreateFileStreamWriter( + const FileSystemURL& url, + int64 offset, + FileSystemContext* context) const = 0; + + // Returns the specialized FileSystemQuotaUtil for this backend. + // This could return NULL if this backend does not support quota. + virtual FileSystemQuotaUtil* GetQuotaUtil() = 0; +}; + +// An interface to control external file system access permissions. +// TODO(satorux): Move this out of 'storage/browser/fileapi'. crbug.com/257279 +class ExternalFileSystemBackend : public FileSystemBackend { + public: + // Returns true if |url| is allowed to be accessed. + // This is supposed to perform ExternalFileSystem-specific security + // checks. + virtual bool IsAccessAllowed(const storage::FileSystemURL& url) const = 0; + // Returns the list of top level directories that are exposed by this + // provider. This list is used to set appropriate child process file access + // permissions. + virtual std::vector<base::FilePath> GetRootDirectories() const = 0; + // Grants access to all external file system from extension identified with + // |extension_id|. + virtual void GrantFullAccessToExtension(const std::string& extension_id) = 0; + // Grants access to |virtual_path| from |origin_url|. + virtual void GrantFileAccessToExtension( + const std::string& extension_id, + const base::FilePath& virtual_path) = 0; + // Revokes file access from extension identified with |extension_id|. + virtual void RevokeAccessForExtension( + const std::string& extension_id) = 0; + // Gets virtual path by known filesystem path. Returns false when filesystem + // path is not exposed by this provider. + virtual bool GetVirtualPath(const base::FilePath& file_system_path, + base::FilePath* virtual_path) = 0; + // Gets a redirect URL for contents. e.g. Google Drive URL for hosted + // documents. Returns empty URL if the entry does not have the redirect URL. + virtual void GetRedirectURLForContents( + const storage::FileSystemURL& url, + const storage::URLCallback& callback) = 0; +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_BACKEND_H_ diff --git a/webkit/browser/fileapi/file_system_context.cc b/storage/browser/fileapi/file_system_context.cc index 7de00a5..f42e11a 100644 --- a/webkit/browser/fileapi/file_system_context.cc +++ b/storage/browser/fileapi/file_system_context.cc @@ -2,34 +2,34 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_context.h" #include "base/bind.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/task_runner_util.h" #include "net/url_request/url_request.h" +#include "storage/browser/blob/file_stream_reader.h" +#include "storage/browser/fileapi/copy_or_move_file_validator.h" +#include "storage/browser/fileapi/external_mount_points.h" +#include "storage/browser/fileapi/file_permission_policy.h" +#include "storage/browser/fileapi/file_stream_writer.h" +#include "storage/browser/fileapi/file_system_file_util.h" +#include "storage/browser/fileapi/file_system_operation.h" +#include "storage/browser/fileapi/file_system_operation_runner.h" +#include "storage/browser/fileapi/file_system_options.h" +#include "storage/browser/fileapi/file_system_quota_client.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/isolated_context.h" +#include "storage/browser/fileapi/isolated_file_system_backend.h" +#include "storage/browser/fileapi/mount_points.h" +#include "storage/browser/fileapi/quota/quota_reservation.h" +#include "storage/browser/fileapi/sandbox_file_system_backend.h" +#include "storage/browser/quota/quota_manager_proxy.h" +#include "storage/browser/quota/special_storage_policy.h" +#include "storage/common/fileapi/file_system_info.h" +#include "storage/common/fileapi/file_system_util.h" #include "url/gurl.h" -#include "webkit/browser/blob/file_stream_reader.h" -#include "webkit/browser/fileapi/copy_or_move_file_validator.h" -#include "webkit/browser/fileapi/external_mount_points.h" -#include "webkit/browser/fileapi/file_permission_policy.h" -#include "webkit/browser/fileapi/file_stream_writer.h" -#include "webkit/browser/fileapi/file_system_file_util.h" -#include "webkit/browser/fileapi/file_system_operation.h" -#include "webkit/browser/fileapi/file_system_operation_runner.h" -#include "webkit/browser/fileapi/file_system_options.h" -#include "webkit/browser/fileapi/file_system_quota_client.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/fileapi/isolated_context.h" -#include "webkit/browser/fileapi/isolated_file_system_backend.h" -#include "webkit/browser/fileapi/mount_points.h" -#include "webkit/browser/fileapi/quota/quota_reservation.h" -#include "webkit/browser/fileapi/sandbox_file_system_backend.h" -#include "webkit/browser/quota/quota_manager_proxy.h" -#include "webkit/browser/quota/special_storage_policy.h" -#include "webkit/common/fileapi/file_system_info.h" -#include "webkit/common/fileapi/file_system_util.h" using storage::QuotaClient; diff --git a/storage/browser/fileapi/file_system_context.h b/storage/browser/fileapi/file_system_context.h new file mode 100644 index 0000000..09b2409 --- /dev/null +++ b/storage/browser/fileapi/file_system_context.h @@ -0,0 +1,428 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_CONTEXT_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_CONTEXT_H_ + +#include <map> +#include <string> +#include <vector> + +#include "base/callback.h" +#include "base/files/file.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/scoped_vector.h" +#include "base/sequenced_task_runner_helpers.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/open_file_system_mode.h" +#include "storage/browser/fileapi/plugin_private_file_system_backend.h" +#include "storage/browser/fileapi/sandbox_file_system_backend_delegate.h" +#include "storage/browser/fileapi/task_runner_bound_observer_list.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/fileapi/file_system_types.h" + +namespace base { +class FilePath; +class SequencedTaskRunner; +class SingleThreadTaskRunner; +} + +namespace chrome { +class NativeMediaFileUtilTest; +} + +namespace storage { +class QuotaManagerProxy; +class SpecialStoragePolicy; +} + +namespace net { +class URLRequest; +} + +namespace storage { +class BlobURLRequestJobTest; +class FileStreamReader; +} + +namespace storage { + +class AsyncFileUtil; +class CopyOrMoveFileValidatorFactory; +class ExternalFileSystemBackend; +class ExternalMountPoints; +class FileStreamWriter; +class FileSystemBackend; +class FileSystemFileUtil; +class FileSystemOperation; +class FileSystemOperationRunner; +class FileSystemOptions; +class FileSystemQuotaUtil; +class FileSystemURL; +class IsolatedFileSystemBackend; +class MountPoints; +class QuotaReservation; +class SandboxFileSystemBackend; +class WatchManager; + +struct DefaultContextDeleter; +struct FileSystemInfo; + +// An auto mount handler will attempt to mount the file system requested in +// |url_request|. If the URL is for this auto mount handler, it returns true +// and calls |callback| when the attempt is complete. If the auto mounter +// does not recognize the URL, it returns false and does not call |callback|. +// Called on the IO thread. +typedef base::Callback<bool( + const net::URLRequest* url_request, + const FileSystemURL& filesystem_url, + const std::string& storage_domain, + const base::Callback<void(base::File::Error result)>& callback)> + URLRequestAutoMountHandler; + +// This class keeps and provides a file system context for FileSystem API. +// An instance of this class is created and owned by profile. +class STORAGE_EXPORT FileSystemContext + : public base::RefCountedThreadSafe<FileSystemContext, + DefaultContextDeleter> { + public: + // Returns file permission policy we should apply for the given |type|. + // The return value must be bitwise-or'd of FilePermissionPolicy. + // + // Note: if a part of a filesystem is returned via 'Isolated' mount point, + // its per-filesystem permission overrides the underlying filesystem's + // permission policy. + static int GetPermissionPolicy(FileSystemType type); + + // file_task_runner is used as default TaskRunner. + // Unless a FileSystemBackend is overridden in CreateFileSystemOperation, + // it is used for all file operations and file related meta operations. + // The code assumes that file_task_runner->RunsTasksOnCurrentThread() + // returns false if the current task is not running on the thread that allows + // blocking file operations (like SequencedWorkerPool implementation does). + // + // |external_mount_points| contains non-system external mount points available + // in the context. If not NULL, it will be used during URL cracking. + // |external_mount_points| may be NULL only on platforms different from + // ChromeOS (i.e. platforms that don't use external_mount_point_provider). + // + // |additional_backends| are added to the internal backend map + // to serve filesystem requests for non-regular types. + // If none is given, this context only handles HTML5 Sandbox FileSystem + // and Drag-and-drop Isolated FileSystem requests. + // + // |auto_mount_handlers| are used to resolve calls to + // AttemptAutoMountForURLRequest. Only external filesystems are auto mounted + // when a filesystem: URL request is made. + FileSystemContext( + base::SingleThreadTaskRunner* io_task_runner, + base::SequencedTaskRunner* file_task_runner, + ExternalMountPoints* external_mount_points, + storage::SpecialStoragePolicy* special_storage_policy, + storage::QuotaManagerProxy* quota_manager_proxy, + ScopedVector<FileSystemBackend> additional_backends, + const std::vector<URLRequestAutoMountHandler>& auto_mount_handlers, + const base::FilePath& partition_path, + const FileSystemOptions& options); + + bool DeleteDataForOriginOnFileTaskRunner(const GURL& origin_url); + + // Creates a new QuotaReservation for the given |origin_url| and |type|. + // Returns NULL if |type| does not support quota or reservation fails. + // This should be run on |default_file_task_runner_| and the returned value + // should be destroyed on the runner. + scoped_refptr<QuotaReservation> CreateQuotaReservationOnFileTaskRunner( + const GURL& origin_url, + FileSystemType type); + + storage::QuotaManagerProxy* quota_manager_proxy() const { + return quota_manager_proxy_.get(); + } + + // Discards inflight operations in the operation runner. + void Shutdown(); + + // Returns a quota util for a given filesystem type. This may + // return NULL if the type does not support the usage tracking or + // it is not a quota-managed storage. + FileSystemQuotaUtil* GetQuotaUtil(FileSystemType type) const; + + // Returns the appropriate AsyncFileUtil instance for the given |type|. + AsyncFileUtil* GetAsyncFileUtil(FileSystemType type) const; + + // Returns the appropriate CopyOrMoveFileValidatorFactory for the given + // |type|. If |error_code| is File::FILE_OK and the result is NULL, + // then no validator is required. + CopyOrMoveFileValidatorFactory* GetCopyOrMoveFileValidatorFactory( + FileSystemType type, base::File::Error* error_code) const; + + // Returns the file system backend instance for the given |type|. + // This may return NULL if it is given an invalid or unsupported filesystem + // type. + FileSystemBackend* GetFileSystemBackend( + FileSystemType type) const; + + // Returns the watcher manager for the given |type|. + // This may return NULL if the type does not support watching. + WatcherManager* GetWatcherManager(FileSystemType type) const; + + // Returns true for sandboxed filesystems. Currently this does + // the same as GetQuotaUtil(type) != NULL. (In an assumption that + // all sandboxed filesystems must cooperate with QuotaManager so that + // they can get deleted) + bool IsSandboxFileSystem(FileSystemType type) const; + + // Returns observers for the given filesystem type. + const UpdateObserverList* GetUpdateObservers(FileSystemType type) const; + const ChangeObserverList* GetChangeObservers(FileSystemType type) const; + const AccessObserverList* GetAccessObservers(FileSystemType type) const; + + // Returns all registered filesystem types. + void GetFileSystemTypes(std::vector<FileSystemType>* types) const; + + // Returns a FileSystemBackend instance for external filesystem + // type, which is used only by chromeos for now. This is equivalent to + // calling GetFileSystemBackend(kFileSystemTypeExternal). + ExternalFileSystemBackend* external_backend() const; + + // Used for OpenFileSystem. + typedef base::Callback<void(const GURL& root, + const std::string& name, + base::File::Error result)> + OpenFileSystemCallback; + + // Used for ResolveURL. + enum ResolvedEntryType { + RESOLVED_ENTRY_FILE, + RESOLVED_ENTRY_DIRECTORY, + RESOLVED_ENTRY_NOT_FOUND, + }; + typedef base::Callback<void(base::File::Error result, + const FileSystemInfo& info, + const base::FilePath& file_path, + ResolvedEntryType type)> ResolveURLCallback; + + // Used for DeleteFileSystem and OpenPluginPrivateFileSystem. + typedef base::Callback<void(base::File::Error result)> StatusCallback; + + // Opens the filesystem for the given |origin_url| and |type|, and dispatches + // |callback| on completion. + // If |create| is true this may actually set up a filesystem instance + // (e.g. by creating the root directory or initializing the database + // entry etc). + void OpenFileSystem( + const GURL& origin_url, + FileSystemType type, + OpenFileSystemMode mode, + const OpenFileSystemCallback& callback); + + // Opens the filesystem for the given |url| as read-only, if the filesystem + // backend referred by the URL allows opening by resolveURL. Otherwise it + // fails with FILE_ERROR_SECURITY. The entry pointed by the URL can be + // absent; in that case RESOLVED_ENTRY_NOT_FOUND type is returned to the + // callback for indicating the absence. Can be called from any thread with + // a message loop. |callback| is invoked on the caller thread. + void ResolveURL( + const FileSystemURL& url, + const ResolveURLCallback& callback); + + // Attempts to mount the filesystem needed to satisfy |url_request| made + // from |storage_domain|. If an appropriate file system is not found, + // callback will return an error. + void AttemptAutoMountForURLRequest(const net::URLRequest* url_request, + const std::string& storage_domain, + const StatusCallback& callback); + + // Deletes the filesystem for the given |origin_url| and |type|. This should + // be called on the IO thread. + void DeleteFileSystem( + const GURL& origin_url, + FileSystemType type, + const StatusCallback& callback); + + // Creates new FileStreamReader instance to read a file pointed by the given + // filesystem URL |url| starting from |offset|. |expected_modification_time| + // specifies the expected last modification if the value is non-null, the + // reader will check the underlying file's actual modification time to see if + // the file has been modified, and if it does any succeeding read operations + // should fail with ERR_UPLOAD_FILE_CHANGED error. + // This method internally cracks the |url|, get an appropriate + // FileSystemBackend for the URL and call the backend's CreateFileReader. + // The resolved FileSystemBackend could perform further specialization + // depending on the filesystem type pointed by the |url|. + scoped_ptr<storage::FileStreamReader> CreateFileStreamReader( + const FileSystemURL& url, + int64 offset, + const base::Time& expected_modification_time); + + // Creates new FileStreamWriter instance to write into a file pointed by + // |url| from |offset|. + scoped_ptr<FileStreamWriter> CreateFileStreamWriter( + const FileSystemURL& url, + int64 offset); + + // Creates a new FileSystemOperationRunner. + scoped_ptr<FileSystemOperationRunner> CreateFileSystemOperationRunner(); + + base::SequencedTaskRunner* default_file_task_runner() { + return default_file_task_runner_.get(); + } + + FileSystemOperationRunner* operation_runner() { + return operation_runner_.get(); + } + + const base::FilePath& partition_path() const { return partition_path_; } + + // Same as |CrackFileSystemURL|, but cracks FileSystemURL created from |url|. + FileSystemURL CrackURL(const GURL& url) const; + // Same as |CrackFileSystemURL|, but cracks FileSystemURL created from method + // arguments. + FileSystemURL CreateCrackedFileSystemURL(const GURL& origin, + FileSystemType type, + const base::FilePath& path) const; + +#if defined(OS_CHROMEOS) + // Used only on ChromeOS for now. + void EnableTemporaryFileSystemInIncognito(); +#endif + + SandboxFileSystemBackendDelegate* sandbox_delegate() { + return sandbox_delegate_.get(); + } + + // Returns true if the requested url is ok to be served. + // (E.g. this returns false if the context is created for incognito mode) + bool CanServeURLRequest(const FileSystemURL& url) const; + + // Returns true if a file in the file system should be flushed for each write + // completion. + bool ShouldFlushOnWriteCompletion(FileSystemType type) const; + + // This must be used to open 'plugin private' filesystem. + // See "plugin_private_file_system_backend.h" for more details. + void OpenPluginPrivateFileSystem( + const GURL& origin_url, + FileSystemType type, + const std::string& filesystem_id, + const std::string& plugin_id, + OpenFileSystemMode mode, + const StatusCallback& callback); + + private: + typedef std::map<FileSystemType, FileSystemBackend*> + FileSystemBackendMap; + + // For CreateFileSystemOperation. + friend class FileSystemOperationRunner; + + // For sandbox_backend(). + friend class content::SandboxFileSystemTestHelper; + + // For plugin_private_backend(). + friend class content::PluginPrivateFileSystemBackendTest; + + // Deleters. + friend struct DefaultContextDeleter; + friend class base::DeleteHelper<FileSystemContext>; + friend class base::RefCountedThreadSafe<FileSystemContext, + DefaultContextDeleter>; + ~FileSystemContext(); + + void DeleteOnCorrectThread() const; + + // Creates a new FileSystemOperation instance by getting an appropriate + // FileSystemBackend for |url| and calling the backend's corresponding + // CreateFileSystemOperation method. + // The resolved FileSystemBackend could perform further specialization + // depending on the filesystem type pointed by the |url|. + // + // Called by FileSystemOperationRunner. + FileSystemOperation* CreateFileSystemOperation( + const FileSystemURL& url, + base::File::Error* error_code); + + // For non-cracked isolated and external mount points, returns a FileSystemURL + // created by cracking |url|. The url is cracked using MountPoints registered + // as |url_crackers_|. If the url cannot be cracked, returns invalid + // FileSystemURL. + // + // If the original url does not point to an isolated or external filesystem, + // returns the original url, without attempting to crack it. + FileSystemURL CrackFileSystemURL(const FileSystemURL& url) const; + + // For initial backend_map construction. This must be called only from + // the constructor. + void RegisterBackend(FileSystemBackend* backend); + + void DidOpenFileSystemForResolveURL( + const FileSystemURL& url, + const ResolveURLCallback& callback, + const GURL& filesystem_root, + const std::string& filesystem_name, + base::File::Error error); + + // Returns a FileSystemBackend, used only by test code. + SandboxFileSystemBackend* sandbox_backend() const { + return sandbox_backend_.get(); + } + + // Used only by test code. + PluginPrivateFileSystemBackend* plugin_private_backend() const { + return plugin_private_backend_.get(); + } + + scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_; + scoped_refptr<base::SequencedTaskRunner> default_file_task_runner_; + + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy_; + + scoped_ptr<SandboxFileSystemBackendDelegate> sandbox_delegate_; + + // Regular file system backends. + scoped_ptr<SandboxFileSystemBackend> sandbox_backend_; + scoped_ptr<IsolatedFileSystemBackend> isolated_backend_; + + // Additional file system backends. + scoped_ptr<PluginPrivateFileSystemBackend> plugin_private_backend_; + ScopedVector<FileSystemBackend> additional_backends_; + + std::vector<URLRequestAutoMountHandler> auto_mount_handlers_; + + // Registered file system backends. + // The map must be constructed in the constructor since it can be accessed + // on multiple threads. + // This map itself doesn't retain each backend's ownership; ownerships + // of the backends are held by additional_backends_ or other scoped_ptr + // backend fields. + FileSystemBackendMap backend_map_; + + // External mount points visible in the file system context (excluding system + // external mount points). + scoped_refptr<ExternalMountPoints> external_mount_points_; + + // MountPoints used to crack FileSystemURLs. The MountPoints are ordered + // in order they should try to crack a FileSystemURL. + std::vector<MountPoints*> url_crackers_; + + // The base path of the storage partition for this context. + const base::FilePath partition_path_; + + bool is_incognito_; + + scoped_ptr<FileSystemOperationRunner> operation_runner_; + + DISALLOW_IMPLICIT_CONSTRUCTORS(FileSystemContext); +}; + +struct DefaultContextDeleter { + static void Destruct(const FileSystemContext* context) { + context->DeleteOnCorrectThread(); + } +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_CONTEXT_H_ diff --git a/webkit/browser/fileapi/file_system_dir_url_request_job.cc b/storage/browser/fileapi/file_system_dir_url_request_job.cc index acedbce..cce9c56 100644 --- a/webkit/browser/fileapi/file_system_dir_url_request_job.cc +++ b/storage/browser/fileapi/file_system_dir_url_request_job.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/file_system_dir_url_request_job.h" +#include "storage/browser/fileapi/file_system_dir_url_request_job.h" #include <algorithm> @@ -17,12 +17,12 @@ #include "net/base/net_errors.h" #include "net/base/net_util.h" #include "net/url_request/url_request.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation_runner.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/common/fileapi/directory_entry.h" +#include "storage/common/fileapi/file_system_util.h" #include "url/gurl.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation_runner.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/common/fileapi/directory_entry.h" -#include "webkit/common/fileapi/file_system_util.h" using net::NetworkDelegate; using net::URLRequest; diff --git a/storage/browser/fileapi/file_system_dir_url_request_job.h b/storage/browser/fileapi/file_system_dir_url_request_job.h new file mode 100644 index 0000000..8c71cdf --- /dev/null +++ b/storage/browser/fileapi/file_system_dir_url_request_job.h @@ -0,0 +1,69 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_DIR_URL_REQUEST_JOB_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_DIR_URL_REQUEST_JOB_H_ + +#include <string> +#include <vector> + +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/memory/weak_ptr.h" +#include "base/message_loop/message_loop_proxy.h" +#include "net/url_request/url_request_job.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/storage_browser_export.h" + +namespace storage { + +class FileSystemContext; +struct DirectoryEntry; + +// A request job that handles reading filesystem: URLs for directories. +class STORAGE_EXPORT_PRIVATE FileSystemDirURLRequestJob + : public net::URLRequestJob { + public: + FileSystemDirURLRequestJob( + net::URLRequest* request, + net::NetworkDelegate* network_delegate, + const std::string& storage_domain, + FileSystemContext* file_system_context); + + // URLRequestJob methods: + virtual void Start() OVERRIDE; + virtual void Kill() OVERRIDE; + virtual bool ReadRawData(net::IOBuffer* buf, + int buf_size, + int* bytes_read) OVERRIDE; + virtual bool GetCharset(std::string* charset) OVERRIDE; + + // FilterContext methods (via URLRequestJob): + virtual bool GetMimeType(std::string* mime_type) const OVERRIDE; + // TODO(adamk): Implement GetResponseInfo and GetResponseCode to simulate + // an HTTP response. + + private: + class CallbackDispatcher; + + virtual ~FileSystemDirURLRequestJob(); + + void StartAsync(); + void DidAttemptAutoMount(base::File::Error result); + void DidReadDirectory(base::File::Error result, + const std::vector<DirectoryEntry>& entries, + bool has_more); + + std::string data_; + FileSystemURL url_; + const std::string storage_domain_; + FileSystemContext* file_system_context_; + base::WeakPtrFactory<FileSystemDirURLRequestJob> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(FileSystemDirURLRequestJob); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_DIR_URL_REQUEST_JOB_H_ diff --git a/webkit/browser/fileapi/file_system_file_stream_reader.cc b/storage/browser/fileapi/file_system_file_stream_reader.cc index aa99ab9..60a806a 100644 --- a/webkit/browser/fileapi/file_system_file_stream_reader.cc +++ b/storage/browser/fileapi/file_system_file_stream_reader.cc @@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/file_system_file_stream_reader.h" +#include "storage/browser/fileapi/file_system_file_stream_reader.h" #include "base/files/file_util_proxy.h" #include "base/single_thread_task_runner.h" #include "net/base/file_stream.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" -#include "webkit/browser/blob/file_stream_reader.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation_runner.h" +#include "storage/browser/blob/file_stream_reader.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation_runner.h" using storage::FileStreamReader; diff --git a/storage/browser/fileapi/file_system_file_stream_reader.h b/storage/browser/fileapi/file_system_file_stream_reader.h new file mode 100644 index 0000000..3fe075b6 --- /dev/null +++ b/storage/browser/fileapi/file_system_file_stream_reader.h @@ -0,0 +1,79 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_FILE_STREAM_READER_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_FILE_STREAM_READER_H_ + +#include "base/bind.h" +#include "base/files/file.h" +#include "base/memory/ref_counted.h" +#include "base/time/time.h" +#include "storage/browser/blob/file_stream_reader.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/blob/shareable_file_reference.h" + +namespace base { +class FilePath; +class SequencedTaskRunner; +} + +namespace content { +class FileSystemFileStreamReaderTest; +} + +namespace storage { + +class FileSystemContext; + +// Generic FileStreamReader implementation for FileSystem files. +// Note: This generic implementation would work for any filesystems but +// remote filesystem should implement its own reader rather than relying +// on FileSystemOperation::GetSnapshotFile() which may force downloading +// the entire contents for remote files. +class STORAGE_EXPORT_PRIVATE FileSystemFileStreamReader + : public NON_EXPORTED_BASE(storage::FileStreamReader) { + public: + virtual ~FileSystemFileStreamReader(); + + // FileStreamReader overrides. + virtual int Read(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback) OVERRIDE; + virtual int64 GetLength( + const net::Int64CompletionCallback& callback) OVERRIDE; + + private: + friend class storage::FileStreamReader; + friend class content::FileSystemFileStreamReaderTest; + + FileSystemFileStreamReader(FileSystemContext* file_system_context, + const FileSystemURL& url, + int64 initial_offset, + const base::Time& expected_modification_time); + + int CreateSnapshot(const base::Closure& callback, + const net::CompletionCallback& error_callback); + void DidCreateSnapshot( + const base::Closure& callback, + const net::CompletionCallback& error_callback, + base::File::Error file_error, + const base::File::Info& file_info, + const base::FilePath& platform_path, + const scoped_refptr<storage::ShareableFileReference>& file_ref); + + scoped_refptr<FileSystemContext> file_system_context_; + FileSystemURL url_; + const int64 initial_offset_; + const base::Time expected_modification_time_; + scoped_ptr<storage::FileStreamReader> local_file_reader_; + scoped_refptr<storage::ShareableFileReference> snapshot_ref_; + bool has_pending_create_snapshot_; + base::WeakPtrFactory<FileSystemFileStreamReader> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(FileSystemFileStreamReader); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_FILE_STREAM_READER_H_ diff --git a/webkit/browser/fileapi/file_system_file_util.cc b/storage/browser/fileapi/file_system_file_util.cc index 35b1ceb..f356109 100644 --- a/webkit/browser/fileapi/file_system_file_util.cc +++ b/storage/browser/fileapi/file_system_file_util.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/file_system_file_util.h" +#include "storage/browser/fileapi/file_system_file_util.h" namespace storage { diff --git a/storage/browser/fileapi/file_system_file_util.h b/storage/browser/fileapi/file_system_file_util.h new file mode 100644 index 0000000..868d091 --- /dev/null +++ b/storage/browser/fileapi/file_system_file_util.h @@ -0,0 +1,186 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_FILE_UTIL_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_FILE_UTIL_H_ + +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/memory/scoped_ptr.h" +#include "storage/browser/fileapi/file_system_operation.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/blob/scoped_file.h" + +namespace base { +class Time; +} + +namespace storage { + +class FileSystemOperationContext; +class FileSystemURL; + +// A file utility interface that provides basic file utility methods for +// FileSystem API. +// +// Layering structure of the FileSystemFileUtil was split out. +// See http://crbug.com/128136 if you need it. +class STORAGE_EXPORT FileSystemFileUtil { + public: + typedef FileSystemOperation::CopyOrMoveOption CopyOrMoveOption; + + // It will be implemented by each subclass such as FileSystemFileEnumerator. + class STORAGE_EXPORT AbstractFileEnumerator { + public: + virtual ~AbstractFileEnumerator() {} + + // Returns an empty string if there are no more results. + virtual base::FilePath Next() = 0; + + // These methods return metadata for the file most recently returned by + // Next(). If Next() has never been called, or if Next() most recently + // returned an empty string, then return the default values of 0, + // "null time", and false, respectively. + virtual int64 Size() = 0; + virtual base::Time LastModifiedTime() = 0; + virtual bool IsDirectory() = 0; + }; + + class STORAGE_EXPORT EmptyFileEnumerator + : public AbstractFileEnumerator { + virtual base::FilePath Next() OVERRIDE; + virtual int64 Size() OVERRIDE; + virtual base::Time LastModifiedTime() OVERRIDE; + virtual bool IsDirectory() OVERRIDE; + }; + + virtual ~FileSystemFileUtil() {} + + // Creates or opens a file with the given flags. + // See header comments for AsyncFileUtil::CreateOrOpen() for more details. + // This is used only by Pepper/NaCl File API. + virtual base::File CreateOrOpen( + FileSystemOperationContext* context, + const FileSystemURL& url, + int file_flags) = 0; + + // Ensures that the given |url| exist. This creates a empty new file + // at |url| if the |url| does not exist. + // See header comments for AsyncFileUtil::EnsureFileExists() for more details. + virtual base::File::Error EnsureFileExists( + FileSystemOperationContext* context, + const FileSystemURL& url, bool* created) = 0; + + // Creates directory at given url. + // See header comments for AsyncFileUtil::CreateDirectory() for more details. + virtual base::File::Error CreateDirectory( + FileSystemOperationContext* context, + const FileSystemURL& url, + bool exclusive, + bool recursive) = 0; + + // Retrieves the information about a file. + // See header comments for AsyncFileUtil::GetFileInfo() for more details. + virtual base::File::Error GetFileInfo( + FileSystemOperationContext* context, + const FileSystemURL& url, + base::File::Info* file_info, + base::FilePath* platform_path) = 0; + + // Returns a pointer to a new instance of AbstractFileEnumerator which is + // implemented for each FileSystemFileUtil subclass. The instance needs to be + // freed by the caller, and its lifetime should not extend past when the + // current call returns to the main FILE message loop. + // + // The supplied context must remain valid at least lifetime of the enumerator + // instance. + virtual scoped_ptr<AbstractFileEnumerator> CreateFileEnumerator( + FileSystemOperationContext* context, + const FileSystemURL& root_url) = 0; + + // Maps |file_system_url| given |context| into |local_file_path| + // which represents physical file location on the host OS. + // This may not always make sense for all subclasses. + virtual base::File::Error GetLocalFilePath( + FileSystemOperationContext* context, + const FileSystemURL& file_system_url, + base::FilePath* local_file_path) = 0; + + // Updates the file metadata information. + // See header comments for AsyncFileUtil::Touch() for more details. + virtual base::File::Error Touch( + FileSystemOperationContext* context, + const FileSystemURL& url, + const base::Time& last_access_time, + const base::Time& last_modified_time) = 0; + + // Truncates a file to the given length. + // See header comments for AsyncFileUtil::Truncate() for more details. + virtual base::File::Error Truncate( + FileSystemOperationContext* context, + const FileSystemURL& url, + int64 length) = 0; + + // Copies or moves a single file from |src_url| to |dest_url|. + // The filesystem type of |src_url| and |dest_url| MUST be same. + // For |option|, please see file_system_operation.h + // + // This returns: + // - File::FILE_ERROR_NOT_FOUND if |src_url| + // or the parent directory of |dest_url| does not exist. + // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. + // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and + // is not a file. + // - File::FILE_ERROR_FAILED if |dest_url| does not exist and + // its parent path is a file. + // + virtual base::File::Error CopyOrMoveFile( + FileSystemOperationContext* context, + const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + bool copy) = 0; + + // Copies in a single file from a different filesystem. + // See header comments for AsyncFileUtil::CopyInForeignFile() for + // more details. + virtual base::File::Error CopyInForeignFile( + FileSystemOperationContext* context, + const base::FilePath& src_file_path, + const FileSystemURL& dest_url) = 0; + + // Deletes a single file. + // See header comments for AsyncFileUtil::DeleteFile() for more details. + virtual base::File::Error DeleteFile( + FileSystemOperationContext* context, + const FileSystemURL& url) = 0; + + // Deletes a single empty directory. + // See header comments for AsyncFileUtil::DeleteDirectory() for more details. + virtual base::File::Error DeleteDirectory( + FileSystemOperationContext* context, + const FileSystemURL& url) = 0; + + // Creates a local snapshot file for a given |url| and returns the + // metadata and platform path of the snapshot file via |callback|. + // + // See header comments for AsyncFileUtil::CreateSnapshotFile() for + // more details. + virtual storage::ScopedFile CreateSnapshotFile( + FileSystemOperationContext* context, + const FileSystemURL& url, + base::File::Error* error, + base::File::Info* file_info, + base::FilePath* platform_path) = 0; + + protected: + FileSystemFileUtil() {} + + private: + DISALLOW_COPY_AND_ASSIGN(FileSystemFileUtil); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_FILE_UTIL_H_ diff --git a/storage/browser/fileapi/file_system_operation.h b/storage/browser/fileapi/file_system_operation.h new file mode 100644 index 0000000..4b38da0 --- /dev/null +++ b/storage/browser/fileapi/file_system_operation.h @@ -0,0 +1,485 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_H_ + +#include <vector> + +#include "base/callback.h" +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/process/process.h" +#include "storage/browser/fileapi/file_system_operation_context.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/fileapi/directory_entry.h" + +namespace base { +class Time; +} + +namespace net { +class URLRequest; +} + +namespace storage { +class ShareableFileReference; +} + +class GURL; + +namespace storage { + +class FileSystemContext; +class FileSystemURL; +class FileWriterDelegate; + +// The interface class for FileSystemOperation implementations. +// +// This interface defines file system operations required to implement +// "File API: Directories and System" +// http://www.w3.org/TR/file-system-api/ +// +// DESIGN NOTES +// +// This class is designed to +// +// 1) Serve one-time file system operation per instance. Only one +// method(CreateFile, CreateDirectory, Copy, Move, DirectoryExists, +// GetMetadata, ReadDirectory and Remove) may be called during the +// lifetime of this object and it should be called no more than once. +// +// 2) Deliver the results of operations to the client via the callback function +// passed as the last parameter of the method. +// +// Note that it is valid to delete an operation while it is running. +// The callback will NOT be fired if the operation is deleted before +// it gets called. +class FileSystemOperation { + public: + STORAGE_EXPORT static FileSystemOperation* Create( + const FileSystemURL& url, + FileSystemContext* file_system_context, + scoped_ptr<FileSystemOperationContext> operation_context); + + virtual ~FileSystemOperation() {} + + // Used for CreateFile(), etc. |result| is the return code of the operation. + typedef base::Callback<void(base::File::Error result)> StatusCallback; + + // Used for GetMetadata(). |result| is the return code of the operation, + // |file_info| is the obtained file info. + typedef base::Callback< + void(base::File::Error result, + const base::File::Info& file_info)> GetMetadataCallback; + + // Used for OpenFile(). |on_close_callback| will be called after the file is + // closed in the child process. It can be null, if no operation is needed on + // closing a file. + typedef base::Callback< + void(base::File file, + const base::Closure& on_close_callback)> OpenFileCallback; + + // Used for ReadDirectoryCallback. + typedef std::vector<DirectoryEntry> FileEntryList; + + // Used for ReadDirectory(). |result| is the return code of the operation, + // |file_list| is the list of files read, and |has_more| is true if some files + // are yet to be read. + typedef base::Callback< + void(base::File::Error result, + const FileEntryList& file_list, + bool has_more)> ReadDirectoryCallback; + + // Used for CreateSnapshotFile(). (Please see the comment at + // CreateSnapshotFile() below for how the method is called) + // |result| is the return code of the operation. + // |file_info| is the metadata of the snapshot file created. + // |platform_path| is the path to the snapshot file created. + // + // The snapshot file could simply be of the local file pointed by the given + // filesystem URL in local filesystem cases; remote filesystems + // may want to download the file into a temporary snapshot file and then + // return the metadata of the temporary file. + // + // |file_ref| is used to manage the lifetime of the returned + // snapshot file. It can be set to let the chromium backend take + // care of the life time of the snapshot file. Otherwise (if the returned + // file does not require any handling) the implementation can just + // return NULL. In a more complex case, the implementaiton can manage + // the lifetime of the snapshot file on its own (e.g. by its cache system) + // but also can be notified via the reference when the file becomes no + // longer necessary in the javascript world. + // Please see the comment for ShareableFileReference for details. + // + typedef base::Callback< + void(base::File::Error result, + const base::File::Info& file_info, + const base::FilePath& platform_path, + const scoped_refptr<storage::ShareableFileReference>& file_ref)> + SnapshotFileCallback; + + // Used for progress update callback for Copy(). + // + // BEGIN_COPY_ENTRY is fired for each copy creation beginning (for both + // file and directory). + // The |source_url| is the URL of the source entry. |size| should not be + // used. + // + // END_COPY_ENTRY is fired for each copy creation finishing (for both + // file and directory). + // The |source_url| is the URL of the source entry. The |destination_url| is + // the URL of the destination entry. |size| should not be used. + // + // PROGRESS is fired periodically during file copying (not fired for + // directory copy). + // The |source_url| is the URL of the source file. |size| is the number + // of cumulative copied bytes for the currently copied file. + // Both at beginning and ending of file copying, PROGRESS event should be + // called. At beginning, |size| should be 0. At ending, |size| should be + // the size of the file. + // + // Here is an example callback sequence of recursive copy. Suppose + // there are a/b/c.txt (100 bytes) and a/b/d.txt (200 bytes), and trying to + // copy a to x recursively, then the progress update sequence will be: + // + // BEGIN_COPY_ENTRY a (starting create "a" directory in x/). + // END_COPY_ENTRY a x/a (creating "a" directory in x/ is finished). + // + // BEGIN_COPY_ENTRY a/b (starting create "b" directory in x/a). + // END_COPY_ENTRY a/b x/a/b (creating "b" directory in x/a/ is finished). + // + // BEGIN_COPY_ENTRY a/b/c.txt (starting to copy "c.txt" in x/a/b/). + // PROGRESS a/b/c.txt 0 (The first PROGRESS's |size| should be 0). + // PROGRESS a/b/c.txt 10 + // : + // PROGRESS a/b/c.txt 90 + // PROGRESS a/b/c.txt 100 (The last PROGRESS's |size| should be the size of + // the file). + // END_COPY_ENTRY a/b/c.txt x/a/b/c.txt (copying "c.txt" is finished). + // + // BEGIN_COPY_ENTRY a/b/d.txt (starting to copy "d.txt" in x/a/b). + // PROGRESS a/b/d.txt 0 (The first PROGRESS's |size| should be 0). + // PROGRESS a/b/d.txt 10 + // : + // PROGRESS a/b/d.txt 190 + // PROGRESS a/b/d.txt 200 (The last PROGRESS's |size| should be the size of + // the file). + // END_COPY_ENTRY a/b/d.txt x/a/b/d.txt (copy "d.txt" is finished). + // + // Note that event sequence of a/b/c.txt and a/b/d.txt can be interlaced, + // because they can be done in parallel. Also PROGRESS events are optional, + // so they may not be appeared. + // All the progress callback invocation should be done before StatusCallback + // given to the Copy is called. Especially if an error is found before first + // progres callback invocation, the progress callback may NOT invoked for the + // copy. + // + // Note for future extension. Currently this callback is only supported on + // Copy(). We can extend this to Move(), because Move() is sometimes + // implemented as "copy then delete." + // In more precise, Move() usually can be implemented either 1) by updating + // the metadata of resource (e.g. root of moving directory tree), or 2) by + // copying directory tree and them removing the source tree. + // For 1)'s case, we can simply add BEGIN_MOVE_ENTRY and END_MOVE_ENTRY + // for root directory. + // For 2)'s case, we can add BEGIN_DELETE_ENTRY and END_DELETE_ENTRY for each + // entry. + // For both cases, we probably won't need to use PROGRESS event because + // these operations should be done quickly (at least much faster than copying + // usually). + enum CopyProgressType { + BEGIN_COPY_ENTRY, + END_COPY_ENTRY, + PROGRESS, + }; + typedef base::Callback<void(CopyProgressType type, + const FileSystemURL& source_url, + const FileSystemURL& destination_url, + int64 size)> + CopyProgressCallback; + + // Used for CopyFileLocal() to report progress update. + // |size| is the cumulative copied bytes for the copy. + // At the beginning the progress callback should be called with |size| = 0, + // and also at the ending the progress callback should be called with |size| + // set to the copied file size. + typedef base::Callback<void(int64 size)> CopyFileProgressCallback; + + // The option for copy or move operation. + enum CopyOrMoveOption { + // No additional operation. + OPTION_NONE, + + // Preserves last modified time if possible. If the operation to update + // last modified time is not supported on the file system for the + // destination file, this option would be simply ignored (i.e. Copy would + // be successfully done without preserving last modified time). + OPTION_PRESERVE_LAST_MODIFIED, + }; + + // Used for Write(). + typedef base::Callback<void(base::File::Error result, + int64 bytes, + bool complete)> WriteCallback; + + // Creates a file at |path|. If |exclusive| is true, an error is raised + // in case a file is already present at the URL. + virtual void CreateFile(const FileSystemURL& path, + bool exclusive, + const StatusCallback& callback) = 0; + + // Creates a directory at |path|. If |exclusive| is true, an error is + // raised in case a directory is already present at the URL. If + // |recursive| is true, create parent directories as needed just like + // mkdir -p does. + virtual void CreateDirectory(const FileSystemURL& path, + bool exclusive, + bool recursive, + const StatusCallback& callback) = 0; + + // Copies a file or directory from |src_path| to |dest_path|. If + // |src_path| is a directory, the contents of |src_path| are copied to + // |dest_path| recursively. A new file or directory is created at + // |dest_path| as needed. + // |option| specifies the minor behavior of Copy(). See CopyOrMoveOption's + // comment for details. + // |progress_callback| is periodically called to report the progress + // update. See also the comment of CopyProgressCallback. This callback is + // optional. + // + // For recursive case this internally creates new FileSystemOperations and + // calls: + // - ReadDirectory, CopyFileLocal and CreateDirectory + // for same-filesystem case, or + // - ReadDirectory and CreateSnapshotFile on source filesystem and + // CopyInForeignFile and CreateDirectory on dest filesystem + // for cross-filesystem case. + // + virtual void Copy(const FileSystemURL& src_path, + const FileSystemURL& dest_path, + CopyOrMoveOption option, + const CopyProgressCallback& progress_callback, + const StatusCallback& callback) = 0; + + // Moves a file or directory from |src_path| to |dest_path|. A new file + // or directory is created at |dest_path| as needed. + // |option| specifies the minor behavior of Copy(). See CopyOrMoveOption's + // comment for details. + // + // For recursive case this internally creates new FileSystemOperations and + // calls: + // - ReadDirectory, MoveFileLocal, CreateDirectory and Remove + // for same-filesystem case, or + // - ReadDirectory, CreateSnapshotFile and Remove on source filesystem and + // CopyInForeignFile and CreateDirectory on dest filesystem + // for cross-filesystem case. + // + virtual void Move(const FileSystemURL& src_path, + const FileSystemURL& dest_path, + CopyOrMoveOption option, + const StatusCallback& callback) = 0; + + // Checks if a directory is present at |path|. + virtual void DirectoryExists(const FileSystemURL& path, + const StatusCallback& callback) = 0; + + // Checks if a file is present at |path|. + virtual void FileExists(const FileSystemURL& path, + const StatusCallback& callback) = 0; + + // Gets the metadata of a file or directory at |path|. + virtual void GetMetadata(const FileSystemURL& path, + const GetMetadataCallback& callback) = 0; + + // Reads contents of a directory at |path|. + virtual void ReadDirectory(const FileSystemURL& path, + const ReadDirectoryCallback& callback) = 0; + + // Removes a file or directory at |path|. If |recursive| is true, remove + // all files and directories under the directory at |path| recursively. + virtual void Remove(const FileSystemURL& path, bool recursive, + const StatusCallback& callback) = 0; + + // Writes the data read from |blob_request| using |writer_delegate|. + virtual void Write( + const FileSystemURL& url, + scoped_ptr<FileWriterDelegate> writer_delegate, + scoped_ptr<net::URLRequest> blob_request, + const WriteCallback& callback) = 0; + + // Truncates a file at |path| to |length|. If |length| is larger than + // the original file size, the file will be extended, and the extended + // part is filled with null bytes. + virtual void Truncate(const FileSystemURL& path, int64 length, + const StatusCallback& callback) = 0; + + // Tries to cancel the current operation [we support cancelling write or + // truncate only]. Reports failure for the current operation, then reports + // success for the cancel operation itself via the |cancel_dispatcher|. + // + // E.g. a typical cancel implementation would look like: + // + // virtual void SomeOperationImpl::Cancel( + // const StatusCallback& cancel_callback) { + // // Abort the current inflight operation first. + // ... + // + // // Dispatch ABORT error for the current operation by invoking + // // the callback function for the ongoing operation, + // operation_callback.Run(base::File::FILE_ERROR_ABORT, ...); + // + // // Dispatch 'success' for the cancel (or dispatch appropriate + // // error code with DidFail() if the cancel has somehow failed). + // cancel_callback.Run(base::File::FILE_OK); + // } + // + // Note that, for reporting failure, the callback function passed to a + // cancellable operations are kept around with the operation instance + // (as |operation_callback_| in the code example). + virtual void Cancel(const StatusCallback& cancel_callback) = 0; + + // Modifies timestamps of a file or directory at |path| with + // |last_access_time| and |last_modified_time|. The function DOES NOT + // create a file unlike 'touch' command on Linux. + // + // This function is used only by Pepper as of writing. + virtual void TouchFile(const FileSystemURL& path, + const base::Time& last_access_time, + const base::Time& last_modified_time, + const StatusCallback& callback) = 0; + + // Opens a file at |path| with |file_flags|, where flags are OR'ed + // values of base::File::Flags. + // + // This function is used only by Pepper as of writing. + virtual void OpenFile(const FileSystemURL& path, + int file_flags, + const OpenFileCallback& callback) = 0; + + // Creates a local snapshot file for a given |path| and returns the + // metadata and platform path of the snapshot file via |callback|. + // In local filesystem cases the implementation may simply return + // the metadata of the file itself (as well as GetMetadata does), + // while in remote filesystem case the backend may want to download the file + // into a temporary snapshot file and return the metadata of the + // temporary file. Or if the implementaiton already has the local cache + // data for |path| it can simply return the path to the cache. + virtual void CreateSnapshotFile(const FileSystemURL& path, + const SnapshotFileCallback& callback) = 0; + + // Copies in a single file from a different filesystem. + // + // This returns: + // - File::FILE_ERROR_NOT_FOUND if |src_file_path| + // or the parent directory of |dest_url| does not exist. + // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and + // is not a file. + // - File::FILE_ERROR_FAILED if |dest_url| does not exist and + // its parent path is a file. + // + virtual void CopyInForeignFile(const base::FilePath& src_local_disk_path, + const FileSystemURL& dest_url, + const StatusCallback& callback) = 0; + + // Removes a single file. + // + // This returns: + // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. + // - File::FILE_ERROR_NOT_A_FILE if |url| is not a file. + // + virtual void RemoveFile(const FileSystemURL& url, + const StatusCallback& callback) = 0; + + // Removes a single empty directory. + // + // This returns: + // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. + // - File::FILE_ERROR_NOT_A_DIRECTORY if |url| is not a directory. + // - File::FILE_ERROR_NOT_EMPTY if |url| is not empty. + // + virtual void RemoveDirectory(const FileSystemURL& url, + const StatusCallback& callback) = 0; + + // Copies a file from |src_url| to |dest_url|. + // This must be called for files that belong to the same filesystem + // (i.e. type() and origin() of the |src_url| and |dest_url| must match). + // |option| specifies the minor behavior of Copy(). See CopyOrMoveOption's + // comment for details. + // |progress_callback| is periodically called to report the progress + // update. See also the comment of CopyFileProgressCallback. This callback is + // optional. + // + // This returns: + // - File::FILE_ERROR_NOT_FOUND if |src_url| + // or the parent directory of |dest_url| does not exist. + // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. + // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and + // is not a file. + // - File::FILE_ERROR_FAILED if |dest_url| does not exist and + // its parent path is a file. + // + virtual void CopyFileLocal(const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + const CopyFileProgressCallback& progress_callback, + const StatusCallback& callback) = 0; + + // Moves a local file from |src_url| to |dest_url|. + // This must be called for files that belong to the same filesystem + // (i.e. type() and origin() of the |src_url| and |dest_url| must match). + // |option| specifies the minor behavior of Copy(). See CopyOrMoveOption's + // comment for details. + // + // This returns: + // - File::FILE_ERROR_NOT_FOUND if |src_url| + // or the parent directory of |dest_url| does not exist. + // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. + // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and + // is not a file. + // - File::FILE_ERROR_FAILED if |dest_url| does not exist and + // its parent path is a file. + // + virtual void MoveFileLocal(const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + const StatusCallback& callback) = 0; + + // Synchronously gets the platform path for the given |url|. + // This may fail if the given |url|'s filesystem type is neither + // temporary nor persistent. + // In such a case, base::File::FILE_ERROR_INVALID_OPERATION will be + // returned. + virtual base::File::Error SyncGetPlatformPath( + const FileSystemURL& url, + base::FilePath* platform_path) = 0; + + protected: + // Used only for internal assertions. + enum OperationType { + kOperationNone, + kOperationCreateFile, + kOperationCreateDirectory, + kOperationCreateSnapshotFile, + kOperationCopy, + kOperationCopyInForeignFile, + kOperationMove, + kOperationDirectoryExists, + kOperationFileExists, + kOperationGetMetadata, + kOperationReadDirectory, + kOperationRemove, + kOperationWrite, + kOperationTruncate, + kOperationTouchFile, + kOperationOpenFile, + kOperationCloseFile, + kOperationGetLocalPath, + kOperationCancel, + }; +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_H_ diff --git a/webkit/browser/fileapi/file_system_operation_context.cc b/storage/browser/fileapi/file_system_operation_context.cc index 1cd1f37..b392d7b 100644 --- a/webkit/browser/fileapi/file_system_operation_context.cc +++ b/storage/browser/fileapi/file_system_operation_context.cc @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/file_system_operation_context.h" +#include "storage/browser/fileapi/file_system_operation_context.h" #include "base/sequenced_task_runner.h" -#include "webkit/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_context.h" namespace storage { diff --git a/storage/browser/fileapi/file_system_operation_context.h b/storage/browser/fileapi/file_system_operation_context.h new file mode 100644 index 0000000..ceecec1 --- /dev/null +++ b/storage/browser/fileapi/file_system_operation_context.h @@ -0,0 +1,97 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_CONTEXT_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_CONTEXT_H_ + +#include "base/files/file_path.h" +#include "base/supports_user_data.h" +#include "base/threading/thread_checker.h" +#include "storage/browser/fileapi/task_runner_bound_observer_list.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/quota/quota_types.h" + +namespace base { +class SequencedTaskRunner; +} + +namespace storage { + +class FileSystemContext; + +// A context class which is carried around by FileSystemOperation and +// its delegated tasks. It is valid to reuse one context instance across +// multiple operations as far as those operations are supposed to share +// the same context (e.g. use the same task runner, share the quota etc). +// Note that the remaining quota bytes (allowed_bytes_growth) may be +// updated during the execution of write operations. +class STORAGE_EXPORT_PRIVATE FileSystemOperationContext + : public base::SupportsUserData { + public: + explicit FileSystemOperationContext(FileSystemContext* context); + + // Specifies |task_runner| which the operation is performed on. + // The backend of |task_runner| must outlive the IO thread. + FileSystemOperationContext(FileSystemContext* context, + base::SequencedTaskRunner* task_runner); + + virtual ~FileSystemOperationContext(); + + FileSystemContext* file_system_context() const { + return file_system_context_.get(); + } + + // Updates the current remaining quota. + // This can be called to update the remaining quota during the operation. + void set_allowed_bytes_growth(const int64& allowed_bytes_growth) { + allowed_bytes_growth_ = allowed_bytes_growth; + } + + // Returns the current remaining quota. + int64 allowed_bytes_growth() const { return allowed_bytes_growth_; } + storage::QuotaLimitType quota_limit_type() const { return quota_limit_type_; } + base::SequencedTaskRunner* task_runner() const { return task_runner_.get(); } + + ChangeObserverList* change_observers() { return &change_observers_; } + UpdateObserverList* update_observers() { return &update_observers_; } + + // Following setters should be called only on the same thread as the + // FileSystemOperationContext is created (i.e. are not supposed be updated + // after the context's passed onto other task runners). + void set_change_observers(const ChangeObserverList& list) { + DCHECK(setter_thread_checker_.CalledOnValidThread()); + change_observers_ = list; + } + void set_update_observers(const UpdateObserverList& list) { + DCHECK(setter_thread_checker_.CalledOnValidThread()); + update_observers_ = list; + } + void set_quota_limit_type(storage::QuotaLimitType limit_type) { + DCHECK(setter_thread_checker_.CalledOnValidThread()); + quota_limit_type_ = limit_type; + } + + private: + scoped_refptr<FileSystemContext> file_system_context_; + scoped_refptr<base::SequencedTaskRunner> task_runner_; + + // The current remaining quota, used by ObfuscatedFileUtil. + int64 allowed_bytes_growth_; + + // The current quota limit type, used by ObfuscatedFileUtil. + storage::QuotaLimitType quota_limit_type_; + + // Observers attached to this context. + ChangeObserverList change_observers_; + UpdateObserverList update_observers_; + + // Used to check its setters are not called on arbitrary thread. + base::ThreadChecker setter_thread_checker_; + + DISALLOW_COPY_AND_ASSIGN(FileSystemOperationContext); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_CONTEXT_H_ diff --git a/webkit/browser/fileapi/file_system_operation_impl.cc b/storage/browser/fileapi/file_system_operation_impl.cc index 286f19f..75985f4 100644 --- a/webkit/browser/fileapi/file_system_operation_impl.cc +++ b/storage/browser/fileapi/file_system_operation_impl.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/file_system_operation_impl.h" +#include "storage/browser/fileapi/file_system_operation_impl.h" #include "base/bind.h" #include "base/single_thread_task_runner.h" @@ -10,22 +10,22 @@ #include "base/time/time.h" #include "net/base/escape.h" #include "net/url_request/url_request.h" -#include "webkit/browser/fileapi/async_file_util.h" -#include "webkit/browser/fileapi/copy_or_move_operation_delegate.h" -#include "webkit/browser/fileapi/file_observers.h" -#include "webkit/browser/fileapi/file_system_backend.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_file_util.h" -#include "webkit/browser/fileapi/file_system_operation_context.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/fileapi/file_writer_delegate.h" -#include "webkit/browser/fileapi/remove_operation_delegate.h" -#include "webkit/browser/fileapi/sandbox_file_system_backend.h" -#include "webkit/browser/quota/quota_manager_proxy.h" -#include "webkit/common/blob/shareable_file_reference.h" -#include "webkit/common/fileapi/file_system_types.h" -#include "webkit/common/fileapi/file_system_util.h" -#include "webkit/common/quota/quota_types.h" +#include "storage/browser/fileapi/async_file_util.h" +#include "storage/browser/fileapi/copy_or_move_operation_delegate.h" +#include "storage/browser/fileapi/file_observers.h" +#include "storage/browser/fileapi/file_system_backend.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_file_util.h" +#include "storage/browser/fileapi/file_system_operation_context.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/file_writer_delegate.h" +#include "storage/browser/fileapi/remove_operation_delegate.h" +#include "storage/browser/fileapi/sandbox_file_system_backend.h" +#include "storage/browser/quota/quota_manager_proxy.h" +#include "storage/common/blob/shareable_file_reference.h" +#include "storage/common/fileapi/file_system_types.h" +#include "storage/common/fileapi/file_system_util.h" +#include "storage/common/quota/quota_types.h" using storage::ScopedFile; diff --git a/storage/browser/fileapi/file_system_operation_impl.h b/storage/browser/fileapi/file_system_operation_impl.h new file mode 100644 index 0000000..76cf436 --- /dev/null +++ b/storage/browser/fileapi/file_system_operation_impl.h @@ -0,0 +1,206 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_IMPL_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_IMPL_H_ + +#include <vector> + +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "storage/browser/fileapi/file_system_operation.h" +#include "storage/browser/fileapi/file_system_operation_context.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/file_writer_delegate.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/blob/scoped_file.h" +#include "storage/common/quota/quota_types.h" + +namespace storage { + +class AsyncFileUtil; +class FileSystemContext; +class RecursiveOperationDelegate; + +// The default implementation of FileSystemOperation for file systems. +class STORAGE_EXPORT FileSystemOperationImpl + : public NON_EXPORTED_BASE(FileSystemOperation) { + public: + virtual ~FileSystemOperationImpl(); + + // FileSystemOperation overrides. + virtual void CreateFile(const FileSystemURL& url, + bool exclusive, + const StatusCallback& callback) OVERRIDE; + virtual void CreateDirectory(const FileSystemURL& url, + bool exclusive, + bool recursive, + const StatusCallback& callback) OVERRIDE; + virtual void Copy(const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + const CopyProgressCallback& progress_callback, + const StatusCallback& callback) OVERRIDE; + virtual void Move(const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + const StatusCallback& callback) OVERRIDE; + virtual void DirectoryExists(const FileSystemURL& url, + const StatusCallback& callback) OVERRIDE; + virtual void FileExists(const FileSystemURL& url, + const StatusCallback& callback) OVERRIDE; + virtual void GetMetadata(const FileSystemURL& url, + const GetMetadataCallback& callback) OVERRIDE; + virtual void ReadDirectory(const FileSystemURL& url, + const ReadDirectoryCallback& callback) OVERRIDE; + virtual void Remove(const FileSystemURL& url, bool recursive, + const StatusCallback& callback) OVERRIDE; + virtual void Write(const FileSystemURL& url, + scoped_ptr<FileWriterDelegate> writer_delegate, + scoped_ptr<net::URLRequest> blob_request, + const WriteCallback& callback) OVERRIDE; + virtual void Truncate(const FileSystemURL& url, int64 length, + const StatusCallback& callback) OVERRIDE; + virtual void TouchFile(const FileSystemURL& url, + const base::Time& last_access_time, + const base::Time& last_modified_time, + const StatusCallback& callback) OVERRIDE; + virtual void OpenFile(const FileSystemURL& url, + int file_flags, + const OpenFileCallback& callback) OVERRIDE; + virtual void Cancel(const StatusCallback& cancel_callback) OVERRIDE; + virtual void CreateSnapshotFile( + const FileSystemURL& path, + const SnapshotFileCallback& callback) OVERRIDE; + virtual void CopyInForeignFile(const base::FilePath& src_local_disk_path, + const FileSystemURL& dest_url, + const StatusCallback& callback) OVERRIDE; + virtual void RemoveFile(const FileSystemURL& url, + const StatusCallback& callback) OVERRIDE; + virtual void RemoveDirectory(const FileSystemURL& url, + const StatusCallback& callback) OVERRIDE; + virtual void CopyFileLocal(const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + const CopyFileProgressCallback& progress_callback, + const StatusCallback& callback) OVERRIDE; + virtual void MoveFileLocal(const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + const StatusCallback& callback) OVERRIDE; + virtual base::File::Error SyncGetPlatformPath( + const FileSystemURL& url, + base::FilePath* platform_path) OVERRIDE; + + FileSystemContext* file_system_context() const { + return file_system_context_.get(); + } + + private: + friend class FileSystemOperation; + + FileSystemOperationImpl( + const FileSystemURL& url, + FileSystemContext* file_system_context, + scoped_ptr<FileSystemOperationContext> operation_context); + + // Queries the quota and usage and then runs the given |task|. + // If an error occurs during the quota query it runs |error_callback| instead. + void GetUsageAndQuotaThenRunTask( + const FileSystemURL& url, + const base::Closure& task, + const base::Closure& error_callback); + + // Called after the quota info is obtained from the quota manager + // (which is triggered by GetUsageAndQuotaThenRunTask). + // Sets the quota info in the operation_context_ and then runs the given + // |task| if the returned quota status is successful, otherwise runs + // |error_callback|. + void DidGetUsageAndQuotaAndRunTask(const base::Closure& task, + const base::Closure& error_callback, + storage::QuotaStatusCode status, + int64 usage, + int64 quota); + + // The 'body' methods that perform the actual work (i.e. posting the + // file task on proxy_) after the quota check. + void DoCreateFile(const FileSystemURL& url, + const StatusCallback& callback, bool exclusive); + void DoCreateDirectory(const FileSystemURL& url, + const StatusCallback& callback, + bool exclusive, + bool recursive); + void DoCopyFileLocal(const FileSystemURL& src, + const FileSystemURL& dest, + CopyOrMoveOption option, + const CopyFileProgressCallback& progress_callback, + const StatusCallback& callback); + void DoMoveFileLocal(const FileSystemURL& src, + const FileSystemURL& dest, + CopyOrMoveOption option, + const StatusCallback& callback); + void DoCopyInForeignFile(const base::FilePath& src_local_disk_file_path, + const FileSystemURL& dest, + const StatusCallback& callback); + void DoTruncate(const FileSystemURL& url, + const StatusCallback& callback, int64 length); + void DoOpenFile(const FileSystemURL& url, + const OpenFileCallback& callback, int file_flags); + + // Callback for CreateFile for |exclusive|=true cases. + void DidEnsureFileExistsExclusive(const StatusCallback& callback, + base::File::Error rv, + bool created); + + // Callback for CreateFile for |exclusive|=false cases. + void DidEnsureFileExistsNonExclusive(const StatusCallback& callback, + base::File::Error rv, + bool created); + + void DidFinishOperation(const StatusCallback& callback, + base::File::Error rv); + void DidDirectoryExists(const StatusCallback& callback, + base::File::Error rv, + const base::File::Info& file_info); + void DidFileExists(const StatusCallback& callback, + base::File::Error rv, + const base::File::Info& file_info); + void DidDeleteRecursively(const FileSystemURL& url, + const StatusCallback& callback, + base::File::Error rv); + void DidWrite(const FileSystemURL& url, + const WriteCallback& callback, + base::File::Error rv, + int64 bytes, + FileWriterDelegate::WriteProgressStatus write_status); + void DidOpenFile(const OpenFileCallback& callback, + base::File file, + const base::Closure& on_close_callback); + + // Used only for internal assertions. + // Returns false if there's another inflight pending operation. + bool SetPendingOperationType(OperationType type); + + scoped_refptr<FileSystemContext> file_system_context_; + + scoped_ptr<FileSystemOperationContext> operation_context_; + AsyncFileUtil* async_file_util_; // Not owned. + + scoped_ptr<FileWriterDelegate> file_writer_delegate_; + scoped_ptr<RecursiveOperationDelegate> recursive_operation_delegate_; + + StatusCallback cancel_callback_; + + // A flag to make sure we call operation only once per instance. + OperationType pending_operation_; + + base::WeakPtrFactory<FileSystemOperationImpl> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(FileSystemOperationImpl); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_IMPL_H_ diff --git a/webkit/browser/fileapi/file_system_operation_runner.cc b/storage/browser/fileapi/file_system_operation_runner.cc index 0644b2f..58ccb94 100644 --- a/webkit/browser/fileapi/file_system_operation_runner.cc +++ b/storage/browser/fileapi/file_system_operation_runner.cc @@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/file_system_operation_runner.h" +#include "storage/browser/fileapi/file_system_operation_runner.h" #include "base/bind.h" #include "base/message_loop/message_loop_proxy.h" #include "base/stl_util.h" #include "net/url_request/url_request_context.h" -#include "webkit/browser/blob/blob_url_request_job_factory.h" -#include "webkit/browser/fileapi/file_observers.h" -#include "webkit/browser/fileapi/file_stream_writer.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation.h" -#include "webkit/browser/fileapi/file_writer_delegate.h" -#include "webkit/common/blob/shareable_file_reference.h" +#include "storage/browser/blob/blob_url_request_job_factory.h" +#include "storage/browser/fileapi/file_observers.h" +#include "storage/browser/fileapi/file_stream_writer.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation.h" +#include "storage/browser/fileapi/file_writer_delegate.h" +#include "storage/common/blob/shareable_file_reference.h" namespace storage { diff --git a/storage/browser/fileapi/file_system_operation_runner.h b/storage/browser/fileapi/file_system_operation_runner.h new file mode 100644 index 0000000..deca413 --- /dev/null +++ b/storage/browser/fileapi/file_system_operation_runner.h @@ -0,0 +1,322 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_RUNNER_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_RUNNER_H_ + +#include <map> +#include <set> +#include <vector> + +#include "base/basictypes.h" +#include "base/id_map.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "storage/browser/blob/blob_data_handle.h" +#include "storage/browser/fileapi/file_system_operation.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/storage_browser_export.h" + +namespace net { +class URLRequestContext; +} + +namespace storage { + +class FileSystemURL; +class FileSystemContext; + +// A central interface for running FileSystem API operations. +// All operation methods take callback and returns OperationID, which is +// an integer value which can be used for cancelling an operation. +// All operation methods return kErrorOperationID if running (posting) an +// operation fails, in addition to dispatching the callback with an error +// code (therefore in most cases the caller does not need to check the +// returned operation ID). +class STORAGE_EXPORT FileSystemOperationRunner + : public base::SupportsWeakPtr<FileSystemOperationRunner> { + public: + typedef FileSystemOperation::GetMetadataCallback GetMetadataCallback; + typedef FileSystemOperation::ReadDirectoryCallback ReadDirectoryCallback; + typedef FileSystemOperation::SnapshotFileCallback SnapshotFileCallback; + typedef FileSystemOperation::StatusCallback StatusCallback; + typedef FileSystemOperation::WriteCallback WriteCallback; + typedef FileSystemOperation::OpenFileCallback OpenFileCallback; + typedef FileSystemOperation::CopyProgressCallback CopyProgressCallback; + typedef FileSystemOperation::CopyFileProgressCallback + CopyFileProgressCallback; + typedef FileSystemOperation::CopyOrMoveOption CopyOrMoveOption; + + typedef int OperationID; + + virtual ~FileSystemOperationRunner(); + + // Cancels all inflight operations. + void Shutdown(); + + // Creates a file at |url|. If |exclusive| is true, an error is raised + // in case a file is already present at the URL. + OperationID CreateFile(const FileSystemURL& url, + bool exclusive, + const StatusCallback& callback); + + OperationID CreateDirectory(const FileSystemURL& url, + bool exclusive, + bool recursive, + const StatusCallback& callback); + + // Copies a file or directory from |src_url| to |dest_url|. If + // |src_url| is a directory, the contents of |src_url| are copied to + // |dest_url| recursively. A new file or directory is created at + // |dest_url| as needed. + // For |option| and |progress_callback|, see file_system_operation.h for + // details. + OperationID Copy(const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + const CopyProgressCallback& progress_callback, + const StatusCallback& callback); + + // Moves a file or directory from |src_url| to |dest_url|. A new file + // or directory is created at |dest_url| as needed. + // For |option|, see file_system_operation.h for details. + OperationID Move(const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + const StatusCallback& callback); + + // Checks if a directory is present at |url|. + OperationID DirectoryExists(const FileSystemURL& url, + const StatusCallback& callback); + + // Checks if a file is present at |url|. + OperationID FileExists(const FileSystemURL& url, + const StatusCallback& callback); + + // Gets the metadata of a file or directory at |url|. + OperationID GetMetadata(const FileSystemURL& url, + const GetMetadataCallback& callback); + + // Reads contents of a directory at |url|. + OperationID ReadDirectory(const FileSystemURL& url, + const ReadDirectoryCallback& callback); + + // Removes a file or directory at |url|. If |recursive| is true, remove + // all files and directories under the directory at |url| recursively. + OperationID Remove(const FileSystemURL& url, bool recursive, + const StatusCallback& callback); + + // Writes contents of |blob_url| to |url| at |offset|. + // |url_request_context| is used to read contents in |blob|. + OperationID Write(const net::URLRequestContext* url_request_context, + const FileSystemURL& url, + scoped_ptr<storage::BlobDataHandle> blob, + int64 offset, + const WriteCallback& callback); + + // Truncates a file at |url| to |length|. If |length| is larger than + // the original file size, the file will be extended, and the extended + // part is filled with null bytes. + OperationID Truncate(const FileSystemURL& url, int64 length, + const StatusCallback& callback); + + // Tries to cancel the operation |id| [we support cancelling write or + // truncate only]. Reports failure for the current operation, then reports + // success for the cancel operation itself via the |callback|. + void Cancel(OperationID id, const StatusCallback& callback); + + // Modifies timestamps of a file or directory at |url| with + // |last_access_time| and |last_modified_time|. The function DOES NOT + // create a file unlike 'touch' command on Linux. + // + // This function is used only by Pepper as of writing. + OperationID TouchFile(const FileSystemURL& url, + const base::Time& last_access_time, + const base::Time& last_modified_time, + const StatusCallback& callback); + + // Opens a file at |url| with |file_flags|, where flags are OR'ed + // values of base::PlatformFileFlags. + // + // |peer_handle| is the process handle of a pepper plugin process, which + // is necessary for underlying IPC calls with Pepper plugins. + // + // This function is used only by Pepper as of writing. + OperationID OpenFile(const FileSystemURL& url, + int file_flags, + const OpenFileCallback& callback); + + // Creates a local snapshot file for a given |url| and returns the + // metadata and platform url of the snapshot file via |callback|. + // In local filesystem cases the implementation may simply return + // the metadata of the file itself (as well as GetMetadata does), + // while in remote filesystem case the backend may want to download the file + // into a temporary snapshot file and return the metadata of the + // temporary file. Or if the implementaiton already has the local cache + // data for |url| it can simply return the url to the cache. + OperationID CreateSnapshotFile(const FileSystemURL& url, + const SnapshotFileCallback& callback); + + // Copies in a single file from a different filesystem. + // + // This returns: + // - File::FILE_ERROR_NOT_FOUND if |src_file_path| + // or the parent directory of |dest_url| does not exist. + // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and + // is not a file. + // - File::FILE_ERROR_FAILED if |dest_url| does not exist and + // its parent path is a file. + // + OperationID CopyInForeignFile(const base::FilePath& src_local_disk_path, + const FileSystemURL& dest_url, + const StatusCallback& callback); + + // Removes a single file. + // + // This returns: + // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. + // - File::FILE_ERROR_NOT_A_FILE if |url| is not a file. + // + OperationID RemoveFile(const FileSystemURL& url, + const StatusCallback& callback); + + // Removes a single empty directory. + // + // This returns: + // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. + // - File::FILE_ERROR_NOT_A_DIRECTORY if |url| is not a directory. + // - File::FILE_ERROR_NOT_EMPTY if |url| is not empty. + // + OperationID RemoveDirectory(const FileSystemURL& url, + const StatusCallback& callback); + + // Copies a file from |src_url| to |dest_url|. + // This must be called for files that belong to the same filesystem + // (i.e. type() and origin() of the |src_url| and |dest_url| must match). + // For |option| and |progress_callback|, see file_system_operation.h for + // details. + // + // This returns: + // - File::FILE_ERROR_NOT_FOUND if |src_url| + // or the parent directory of |dest_url| does not exist. + // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. + // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and + // is not a file. + // - File::FILE_ERROR_FAILED if |dest_url| does not exist and + // its parent path is a file. + // + OperationID CopyFileLocal(const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + const CopyFileProgressCallback& progress_callback, + const StatusCallback& callback); + + // Moves a local file from |src_url| to |dest_url|. + // This must be called for files that belong to the same filesystem + // (i.e. type() and origin() of the |src_url| and |dest_url| must match). + // For |option|, see file_system_operation.h for details. + // + // This returns: + // - File::FILE_ERROR_NOT_FOUND if |src_url| + // or the parent directory of |dest_url| does not exist. + // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. + // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and + // is not a file. + // - File::FILE_ERROR_FAILED if |dest_url| does not exist and + // its parent path is a file. + // + OperationID MoveFileLocal(const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + const StatusCallback& callback); + + // This is called only by pepper plugin as of writing to synchronously get + // the underlying platform path to upload a file in the sandboxed filesystem + // (e.g. TEMPORARY or PERSISTENT). + base::File::Error SyncGetPlatformPath(const FileSystemURL& url, + base::FilePath* platform_path); + + private: + class BeginOperationScoper; + + struct OperationHandle { + OperationID id; + base::WeakPtr<BeginOperationScoper> scope; + + OperationHandle(); + ~OperationHandle(); + }; + + friend class FileSystemContext; + explicit FileSystemOperationRunner(FileSystemContext* file_system_context); + + void DidFinish(const OperationHandle& handle, + const StatusCallback& callback, + base::File::Error rv); + void DidGetMetadata(const OperationHandle& handle, + const GetMetadataCallback& callback, + base::File::Error rv, + const base::File::Info& file_info); + void DidReadDirectory(const OperationHandle& handle, + const ReadDirectoryCallback& callback, + base::File::Error rv, + const std::vector<DirectoryEntry>& entries, + bool has_more); + void DidWrite(const OperationHandle& handle, + const WriteCallback& callback, + base::File::Error rv, + int64 bytes, + bool complete); + void DidOpenFile( + const OperationHandle& handle, + const OpenFileCallback& callback, + base::File file, + const base::Closure& on_close_callback); + void DidCreateSnapshot( + const OperationHandle& handle, + const SnapshotFileCallback& callback, + base::File::Error rv, + const base::File::Info& file_info, + const base::FilePath& platform_path, + const scoped_refptr<storage::ShareableFileReference>& file_ref); + + void OnCopyProgress( + const OperationHandle& handle, + const CopyProgressCallback& callback, + FileSystemOperation::CopyProgressType type, + const FileSystemURL& source_url, + const FileSystemURL& dest_url, + int64 size); + + void PrepareForWrite(OperationID id, const FileSystemURL& url); + void PrepareForRead(OperationID id, const FileSystemURL& url); + + // These must be called at the beginning and end of any async operations. + OperationHandle BeginOperation(FileSystemOperation* operation, + base::WeakPtr<BeginOperationScoper> scope); + void FinishOperation(OperationID id); + + // Not owned; file_system_context owns this. + FileSystemContext* file_system_context_; + + // IDMap<FileSystemOperation, IDMapOwnPointer> operations_; + IDMap<FileSystemOperation, IDMapOwnPointer> operations_; + + // We keep track of the file to be modified by each operation so that + // we can notify observers when we're done. + typedef std::map<OperationID, FileSystemURLSet> OperationToURLSet; + OperationToURLSet write_target_urls_; + + // Operations that are finished but not yet fire their callbacks. + std::set<OperationID> finished_operations_; + + // Callbacks for stray cancels whose target operation is already finished. + std::map<OperationID, StatusCallback> stray_cancel_callbacks_; + + DISALLOW_COPY_AND_ASSIGN(FileSystemOperationRunner); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_RUNNER_H_ diff --git a/webkit/browser/fileapi/file_system_options.cc b/storage/browser/fileapi/file_system_options.cc index c1d6ff2..47fc3d0 100644 --- a/webkit/browser/fileapi/file_system_options.cc +++ b/storage/browser/fileapi/file_system_options.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/file_system_options.h" +#include "storage/browser/fileapi/file_system_options.h" namespace storage { diff --git a/storage/browser/fileapi/file_system_options.h b/storage/browser/fileapi/file_system_options.h new file mode 100644 index 0000000..6e15baf --- /dev/null +++ b/storage/browser/fileapi/file_system_options.h @@ -0,0 +1,62 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPTIONS_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPTIONS_H_ + +#include <string> +#include <vector> + +#include "storage/browser/storage_browser_export.h" + +namespace leveldb { +class Env; +} + +namespace storage { + +// Provides runtime options that may change FileSystem API behavior. +// This object is copyable. +class STORAGE_EXPORT FileSystemOptions { + public: + enum ProfileMode { + PROFILE_MODE_NORMAL = 0, + PROFILE_MODE_INCOGNITO + }; + + // |profile_mode| specifies if the profile (for this filesystem) + // is running in incognito mode (PROFILE_MODE_INCOGNITO) or no + // (PROFILE_MODE_NORMAL). + // |additional_allowed_schemes| specifies schemes that are allowed + // to access FileSystem API in addition to "http" and "https". + // Non-NULL |env_override| overrides internal LevelDB environment. + FileSystemOptions( + ProfileMode profile_mode, + const std::vector<std::string>& additional_allowed_schemes, + leveldb::Env* env_override); + + ~FileSystemOptions(); + + // Returns true if it is running in the incognito mode. + bool is_incognito() const { return profile_mode_ == PROFILE_MODE_INCOGNITO; } + + // Returns the schemes that must be allowed to access FileSystem API + // in addition to standard "http" and "https". + // (e.g. If the --allow-file-access-from-files option is given in chrome + // "file" scheme will also need to be allowed). + const std::vector<std::string>& additional_allowed_schemes() const { + return additional_allowed_schemes_; + } + + leveldb::Env* env_override() const { return env_override_; } + + private: + const ProfileMode profile_mode_; + const std::vector<std::string> additional_allowed_schemes_; + leveldb::Env* env_override_; +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPTIONS_H_ diff --git a/webkit/browser/fileapi/file_system_quota_client.cc b/storage/browser/fileapi/file_system_quota_client.cc index 8d2fd68..c8c79b3 100644 --- a/webkit/browser/fileapi/file_system_quota_client.cc +++ b/storage/browser/fileapi/file_system_quota_client.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/file_system_quota_client.h" +#include "storage/browser/fileapi/file_system_quota_client.h" #include <algorithm> #include <set> @@ -17,12 +17,12 @@ #include "base/single_thread_task_runner.h" #include "base/task_runner_util.h" #include "net/base/net_util.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_quota_util.h" +#include "storage/browser/fileapi/file_system_usage_cache.h" +#include "storage/browser/fileapi/sandbox_file_system_backend.h" +#include "storage/common/fileapi/file_system_util.h" #include "url/gurl.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_quota_util.h" -#include "webkit/browser/fileapi/file_system_usage_cache.h" -#include "webkit/browser/fileapi/sandbox_file_system_backend.h" -#include "webkit/common/fileapi/file_system_util.h" using storage::StorageType; diff --git a/storage/browser/fileapi/file_system_quota_client.h b/storage/browser/fileapi/file_system_quota_client.h new file mode 100644 index 0000000..e82a0ed --- /dev/null +++ b/storage/browser/fileapi/file_system_quota_client.h @@ -0,0 +1,70 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_QUOTA_CLIENT_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_QUOTA_CLIENT_H_ + +#include <set> +#include <string> +#include <utility> + +#include "base/basictypes.h" +#include "base/compiler_specific.h" +#include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "storage/browser/fileapi/file_system_quota_util.h" +#include "storage/browser/quota/quota_client.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/fileapi/file_system_types.h" + +namespace base { +class SequencedTaskRunner; +} + +namespace storage { + +class FileSystemContext; + +// An instance of this class is created per-profile. This class +// is self-destructed and will delete itself when OnQuotaManagerDestroyed +// is called. +// All of the public methods of this class are called by the quota manager +// (except for the constructor/destructor). +class STORAGE_EXPORT_PRIVATE FileSystemQuotaClient + : public NON_EXPORTED_BASE(storage::QuotaClient) { + public: + FileSystemQuotaClient( + FileSystemContext* file_system_context, + bool is_incognito); + virtual ~FileSystemQuotaClient(); + + // QuotaClient methods. + virtual storage::QuotaClient::ID id() const OVERRIDE; + virtual void OnQuotaManagerDestroyed() OVERRIDE; + virtual void GetOriginUsage(const GURL& origin_url, + storage::StorageType type, + const GetUsageCallback& callback) OVERRIDE; + virtual void GetOriginsForType(storage::StorageType type, + const GetOriginsCallback& callback) OVERRIDE; + virtual void GetOriginsForHost(storage::StorageType type, + const std::string& host, + const GetOriginsCallback& callback) OVERRIDE; + virtual void DeleteOriginData(const GURL& origin, + storage::StorageType type, + const DeletionCallback& callback) OVERRIDE; + virtual bool DoesSupport(storage::StorageType type) const OVERRIDE; + + private: + base::SequencedTaskRunner* file_task_runner() const; + + scoped_refptr<FileSystemContext> file_system_context_; + + bool is_incognito_; + + DISALLOW_COPY_AND_ASSIGN(FileSystemQuotaClient); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_QUOTA_CLIENT_H_ diff --git a/storage/browser/fileapi/file_system_quota_util.h b/storage/browser/fileapi/file_system_quota_util.h new file mode 100644 index 0000000..b5288ff --- /dev/null +++ b/storage/browser/fileapi/file_system_quota_util.h @@ -0,0 +1,91 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_QUOTA_UTIL_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_QUOTA_UTIL_H_ + +#include <set> +#include <string> + +#include "base/basictypes.h" +#include "base/files/file.h" +#include "storage/browser/fileapi/task_runner_bound_observer_list.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/fileapi/file_system_types.h" +#include "url/gurl.h" + +namespace base { +class SequencedTaskRunner; +} + +namespace storage { +class QuotaManagerProxy; +} + +namespace storage { + +class FileSystemContext; +class QuotaReservation; + +// An abstract interface that provides common quota-related utility functions +// for file_system_quota_client. +// All the methods of this class are synchronous and need to be called on +// the thread that the method name implies. +class STORAGE_EXPORT FileSystemQuotaUtil { + public: + virtual ~FileSystemQuotaUtil() {} + + // Deletes the data on the origin and reports the amount of deleted data + // to the quota manager via |proxy|. + virtual base::File::Error DeleteOriginDataOnFileTaskRunner( + FileSystemContext* context, + storage::QuotaManagerProxy* proxy, + const GURL& origin_url, + FileSystemType type) = 0; + + virtual void GetOriginsForTypeOnFileTaskRunner(storage::FileSystemType type, + std::set<GURL>* origins) = 0; + + virtual void GetOriginsForHostOnFileTaskRunner(storage::FileSystemType type, + const std::string& host, + std::set<GURL>* origins) = 0; + + // Returns the amount of data used for the origin for usage tracking. + virtual int64 GetOriginUsageOnFileTaskRunner( + storage::FileSystemContext* file_system_context, + const GURL& origin_url, + storage::FileSystemType type) = 0; + + // Creates new reservation object for the origin and the type. + virtual scoped_refptr<QuotaReservation> + CreateQuotaReservationOnFileTaskRunner( + const GURL& origin_url, + FileSystemType type) = 0; + + virtual void AddFileUpdateObserver( + FileSystemType type, + FileUpdateObserver* observer, + base::SequencedTaskRunner* task_runner) = 0; + virtual void AddFileChangeObserver( + FileSystemType type, + FileChangeObserver* observer, + base::SequencedTaskRunner* task_runner) = 0; + virtual void AddFileAccessObserver( + FileSystemType type, + FileAccessObserver* observer, + base::SequencedTaskRunner* task_runner) = 0; + + // Returns the observer list for |type|, or returns NULL if any observers + // have not been registered on |type|. + virtual const UpdateObserverList* GetUpdateObservers( + FileSystemType type) const = 0; + virtual const ChangeObserverList* GetChangeObservers( + FileSystemType type) const = 0; + virtual const AccessObserverList* GetAccessObservers( + FileSystemType type) const = 0; +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_QUOTA_UTIL_H_ diff --git a/webkit/browser/fileapi/file_system_url.cc b/storage/browser/fileapi/file_system_url.cc index 29b2b3fb..26d0a97c 100644 --- a/webkit/browser/fileapi/file_system_url.cc +++ b/storage/browser/fileapi/file_system_url.cc @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/file_system_url.h" #include <sstream> #include "base/logging.h" #include "base/strings/string_util.h" #include "net/base/escape.h" -#include "webkit/common/fileapi/file_system_types.h" -#include "webkit/common/fileapi/file_system_util.h" +#include "storage/common/fileapi/file_system_types.h" +#include "storage/common/fileapi/file_system_util.h" namespace storage { diff --git a/storage/browser/fileapi/file_system_url.h b/storage/browser/fileapi/file_system_url.h new file mode 100644 index 0000000..7b0e97d --- /dev/null +++ b/storage/browser/fileapi/file_system_url.h @@ -0,0 +1,180 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_URL_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_URL_H_ + +#include <set> +#include <string> + +#include "base/files/file_path.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/fileapi/file_system_mount_option.h" +#include "storage/common/fileapi/file_system_types.h" +#include "url/gurl.h" + +namespace storage { + +// A class representing a filesystem URL which consists of origin URL, +// type and an internal path used inside the filesystem. +// +// When a FileSystemURL instance is created for a GURL (for filesystem: scheme), +// each accessor method would return following values: +// +// Example: For a URL 'filesystem:http://foo.com/temporary/foo/bar': +// origin() returns 'http://foo.com', +// mount_type() returns kFileSystemTypeTemporary, +// virtual_path() returns 'foo/bar', +// type() returns the same value as mount_type(), +// path() returns the same value as virtual_path(), +// +// All other accessors return empty or invalid value. +// +// FileSystemURL can also be created to represent a 'cracked' filesystem URL if +// the original URL's type/path is pointing to a mount point which can be +// further resolved to a lower filesystem type/path. +// +// Example: Assume a path '/media/removable' is mounted at mount name +// 'mount_name' with type kFileSystemTypeFoo as an external file system. +// +// The original URL would look like: +// 'filesystem:http://bar.com/external/mount_name/foo/bar': +// +// FileSystemURL('http://bar.com', +// kFileSystemTypeExternal, +// 'mount_name/foo/bar' +// 'mount_name', +// kFileSystemTypeFoo, +// '/media/removable/foo/bar'); +// would create a FileSystemURL whose accessors return: +// +// origin() returns 'http://bar.com', +// mount_type() returns kFileSystemTypeExternal, +// virtual_path() returns 'mount_name/foo/bar', +// type() returns the kFileSystemTypeFoo, +// path() returns '/media/removable/foo/bar', +// +// Note that in either case virtual_path() always returns the path part after +// 'type' part in the original URL, and mount_type() always returns the 'type' +// part in the original URL. +// +// Additionally, following accessors would return valid values: +// filesystem_id() returns 'mount_name'. +// +// It is impossible to directly create a valid FileSystemURL instance (except by +// using CreatedForTest methods, which should not be used in production code). +// To get a valid FileSystemURL, one of the following methods can be used: +// <Friend>::CrackURL, <Friend>::CreateCrackedFileSystemURL, where <Friend> is +// one of the friended classes. +// +// TODO(ericu): Look into making virtual_path() [and all FileSystem API virtual +// paths] just an std::string, to prevent platform-specific base::FilePath +// behavior from getting invoked by accident. Currently the base::FilePath +// returned here needs special treatment, as it may contain paths that are +// illegal on the current platform. +// To avoid problems, use VirtualPath::BaseName and +// VirtualPath::GetComponents instead of the base::FilePath methods. +class STORAGE_EXPORT FileSystemURL { + public: + FileSystemURL(); + ~FileSystemURL(); + + // Methods for creating FileSystemURL without attempting to crack them. + // Should be used only in tests. + static FileSystemURL CreateForTest(const GURL& url); + static FileSystemURL CreateForTest(const GURL& origin, + FileSystemType mount_type, + const base::FilePath& virtual_path); + + // Returns true if this instance represents a valid FileSystem URL. + bool is_valid() const { return is_valid_; } + + // Returns the origin part of this URL. See the class comment for details. + const GURL& origin() const { return origin_; } + + // Returns the type part of this URL. See the class comment for details. + FileSystemType type() const { return type_; } + + // Returns the cracked path of this URL. See the class comment for details. + const base::FilePath& path() const { return path_; } + + // Returns the original path part of this URL. + // See the class comment for details. + // TODO(kinuko): this must return std::string. + const base::FilePath& virtual_path() const { return virtual_path_; } + + // Returns the filesystem ID/mount name for isolated/external filesystem URLs. + // See the class comment for details. + const std::string& filesystem_id() const { return filesystem_id_; } + const std::string& mount_filesystem_id() const { + return mount_filesystem_id_; + } + + FileSystemType mount_type() const { return mount_type_; } + + const FileSystemMountOption& mount_option() const { return mount_option_; } + + // Returns the formatted URL of this instance. + GURL ToGURL() const; + + std::string DebugString() const; + + // Returns true if this URL is a strict parent of the |child|. + bool IsParent(const FileSystemURL& child) const; + + bool IsInSameFileSystem(const FileSystemURL& other) const; + + bool operator==(const FileSystemURL& that) const; + + bool operator!=(const FileSystemURL& that) const { + return !(*this == that); + } + + struct STORAGE_EXPORT Comparator { + bool operator() (const FileSystemURL& lhs, const FileSystemURL& rhs) const; + }; + + private: + friend class FileSystemContext; + friend class ExternalMountPoints; + friend class IsolatedContext; + + explicit FileSystemURL(const GURL& filesystem_url); + FileSystemURL(const GURL& origin, + FileSystemType mount_type, + const base::FilePath& virtual_path); + // Creates a cracked FileSystemURL. + FileSystemURL(const GURL& origin, + FileSystemType mount_type, + const base::FilePath& virtual_path, + const std::string& mount_filesystem_id, + FileSystemType cracked_type, + const base::FilePath& cracked_path, + const std::string& filesystem_id, + const FileSystemMountOption& mount_option); + + bool is_valid_; + + // Values parsed from the original URL. + GURL origin_; + FileSystemType mount_type_; + base::FilePath virtual_path_; + + // Values obtained by cracking URLs. + // |mount_filesystem_id_| is retrieved from the first round of cracking, + // and the rest of the fields are from recursive cracking. Permission + // checking on the top-level mount information should be done with the former, + // and the low-level file operation should be implemented with the latter. + std::string mount_filesystem_id_; + FileSystemType type_; + base::FilePath path_; + std::string filesystem_id_; + FileSystemMountOption mount_option_; +}; + +typedef std::set<FileSystemURL, FileSystemURL::Comparator> FileSystemURLSet; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_URL_H_ diff --git a/webkit/browser/fileapi/file_system_url_request_job.cc b/storage/browser/fileapi/file_system_url_request_job.cc index bdfd931..8c3e832 100644 --- a/webkit/browser/fileapi/file_system_url_request_job.cc +++ b/storage/browser/fileapi/file_system_url_request_job.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/file_system_url_request_job.h" +#include "storage/browser/fileapi/file_system_url_request_job.h" #include <vector> @@ -24,11 +24,11 @@ #include "net/http/http_response_info.h" #include "net/http/http_util.h" #include "net/url_request/url_request.h" +#include "storage/browser/blob/file_stream_reader.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation_runner.h" +#include "storage/common/fileapi/file_system_util.h" #include "url/gurl.h" -#include "webkit/browser/blob/file_stream_reader.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation_runner.h" -#include "webkit/common/fileapi/file_system_util.h" using net::NetworkDelegate; using net::URLRequest; diff --git a/storage/browser/fileapi/file_system_url_request_job.h b/storage/browser/fileapi/file_system_url_request_job.h new file mode 100644 index 0000000..9910e5d --- /dev/null +++ b/storage/browser/fileapi/file_system_url_request_job.h @@ -0,0 +1,85 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_URL_REQUEST_JOB_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_URL_REQUEST_JOB_H_ + +#include <string> + +#include "base/files/file.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "net/http/http_byte_range.h" +#include "net/url_request/url_request_job.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/storage_browser_export.h" + +class GURL; + +namespace base { +class FilePath; +} + +namespace storage { +class FileStreamReader; +} + +namespace storage { +class FileSystemContext; + +// A request job that handles reading filesystem: URLs +class STORAGE_EXPORT_PRIVATE FileSystemURLRequestJob + : public net::URLRequestJob { + public: + FileSystemURLRequestJob( + net::URLRequest* request, + net::NetworkDelegate* network_delegate, + const std::string& storage_domain, + FileSystemContext* file_system_context); + + // URLRequestJob methods: + virtual void Start() OVERRIDE; + virtual void Kill() OVERRIDE; + virtual bool ReadRawData(net::IOBuffer* buf, + int buf_size, + int* bytes_read) OVERRIDE; + virtual bool IsRedirectResponse(GURL* location, + int* http_status_code) OVERRIDE; + virtual void SetExtraRequestHeaders( + const net::HttpRequestHeaders& headers) OVERRIDE; + virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE; + virtual int GetResponseCode() const OVERRIDE; + + // FilterContext methods (via URLRequestJob): + virtual bool GetMimeType(std::string* mime_type) const OVERRIDE; + + private: + class CallbackDispatcher; + + virtual ~FileSystemURLRequestJob(); + + void StartAsync(); + void DidAttemptAutoMount(base::File::Error result); + void DidGetMetadata(base::File::Error error_code, + const base::File::Info& file_info); + void DidRead(int result); + void NotifyFailed(int rv); + + const std::string storage_domain_; + FileSystemContext* file_system_context_; + scoped_ptr<storage::FileStreamReader> reader_; + FileSystemURL url_; + bool is_directory_; + scoped_ptr<net::HttpResponseInfo> response_info_; + int64 remaining_bytes_; + net::HttpByteRange byte_range_; + base::WeakPtrFactory<FileSystemURLRequestJob> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(FileSystemURLRequestJob); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_URL_REQUEST_JOB_H_ diff --git a/webkit/browser/fileapi/file_system_url_request_job_factory.cc b/storage/browser/fileapi/file_system_url_request_job_factory.cc index 6cc3ad0..68150e4 100644 --- a/webkit/browser/fileapi/file_system_url_request_job_factory.cc +++ b/storage/browser/fileapi/file_system_url_request_job_factory.cc @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/file_system_url_request_job_factory.h" +#include "storage/browser/fileapi/file_system_url_request_job_factory.h" #include <string> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "net/url_request/url_request.h" -#include "webkit/browser/fileapi/file_system_dir_url_request_job.h" -#include "webkit/browser/fileapi/file_system_url_request_job.h" +#include "storage/browser/fileapi/file_system_dir_url_request_job.h" +#include "storage/browser/fileapi/file_system_url_request_job.h" namespace storage { diff --git a/storage/browser/fileapi/file_system_url_request_job_factory.h b/storage/browser/fileapi/file_system_url_request_job_factory.h new file mode 100644 index 0000000..921b5e3 --- /dev/null +++ b/storage/browser/fileapi/file_system_url_request_job_factory.h @@ -0,0 +1,31 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_URL_REQUEST_JOB_FACTORY_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_URL_REQUEST_JOB_FACTORY_H_ + +#include <string> + +#include "net/url_request/url_request_job_factory.h" + +#include "storage/browser/storage_browser_export.h" + +namespace base { +class MessageLoopProxy; +} // namespace base + +namespace storage { + +class FileSystemContext; + +// |context|'s lifetime should exceed the lifetime of the ProtocolHandler. +// Currently, this is only used by ProfileIOData which owns |context| and the +// ProtocolHandler. +STORAGE_EXPORT net::URLRequestJobFactory::ProtocolHandler* + CreateFileSystemProtocolHandler(const std::string& storage_domain, + FileSystemContext* context); + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_URL_REQUEST_JOB_FACTORY_H_ diff --git a/webkit/browser/fileapi/file_system_usage_cache.cc b/storage/browser/fileapi/file_system_usage_cache.cc index 039ee90..0cfbfd8 100644 --- a/webkit/browser/fileapi/file_system_usage_cache.cc +++ b/storage/browser/fileapi/file_system_usage_cache.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/file_system_usage_cache.h" +#include "storage/browser/fileapi/file_system_usage_cache.h" #include <utility> @@ -12,7 +12,7 @@ #include "base/files/file_util.h" #include "base/pickle.h" #include "base/stl_util.h" -#include "webkit/browser/fileapi/timed_task_helper.h" +#include "storage/browser/fileapi/timed_task_helper.h" namespace storage { diff --git a/storage/browser/fileapi/file_system_usage_cache.h b/storage/browser/fileapi/file_system_usage_cache.h new file mode 100644 index 0000000..c2b2aef --- /dev/null +++ b/storage/browser/fileapi/file_system_usage_cache.h @@ -0,0 +1,105 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_USAGE_CACHE_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_USAGE_CACHE_H_ + +#include <map> + +#include "base/basictypes.h" +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "base/sequenced_task_runner.h" +#include "storage/browser/storage_browser_export.h" + +namespace storage { + +class TimedTaskHelper; + +class STORAGE_EXPORT_PRIVATE FileSystemUsageCache { + public: + explicit FileSystemUsageCache(base::SequencedTaskRunner* task_runner); + ~FileSystemUsageCache(); + + // Gets the size described in the .usage file even if dirty > 0 or + // is_valid == false. Returns true if the .usage file is available. + bool GetUsage(const base::FilePath& usage_file_path, int64* usage); + + // Gets the dirty count in the .usage file. + // Returns true if the .usage file is available. + bool GetDirty(const base::FilePath& usage_file_path, uint32* dirty); + + // Increments or decrements the "dirty" entry in the .usage file. + // Returns false if no .usage is available. + bool IncrementDirty(const base::FilePath& usage_file_path); + bool DecrementDirty(const base::FilePath& usage_file_path); + + // Notifies quota system that it needs to recalculate the usage cache of the + // origin. Returns false if no .usage is available. + bool Invalidate(const base::FilePath& usage_file_path); + bool IsValid(const base::FilePath& usage_file_path); + + // Updates the size described in the .usage file. + bool UpdateUsage(const base::FilePath& usage_file_path, int64 fs_usage); + + // Updates the size described in the .usage file by delta with keeping dirty + // even if dirty > 0. + bool AtomicUpdateUsageByDelta(const base::FilePath& usage_file_path, + int64 delta); + + bool Exists(const base::FilePath& usage_file_path); + bool Delete(const base::FilePath& usage_file_path); + + void CloseCacheFiles(); + + static const base::FilePath::CharType kUsageFileName[]; + static const char kUsageFileHeader[]; + static const int kUsageFileSize; + static const int kUsageFileHeaderSize; + + private: + typedef std::map<base::FilePath, base::File*> CacheFiles; + + // Read the size, validity and the "dirty" entry described in the .usage file. + // Returns less than zero if no .usage file is available. + bool Read(const base::FilePath& usage_file_path, + bool* is_valid, + uint32* dirty, + int64* usage); + + bool Write(const base::FilePath& usage_file_path, + bool is_valid, + int32 dirty, + int64 fs_usage); + + base::File* GetFile(const base::FilePath& file_path); + + bool ReadBytes(const base::FilePath& file_path, + char* buffer, + int64 buffer_size); + bool WriteBytes(const base::FilePath& file_path, + const char* buffer, + int64 buffer_size); + bool FlushFile(const base::FilePath& file_path); + void ScheduleCloseTimer(); + + bool HasCacheFileHandle(const base::FilePath& file_path); + + bool CalledOnValidThread(); + + scoped_ptr<TimedTaskHelper> timer_; + CacheFiles cache_files_; + + scoped_refptr<base::SequencedTaskRunner> task_runner_; + + base::WeakPtrFactory<FileSystemUsageCache> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(FileSystemUsageCache); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_USAGE_CACHE_H_ diff --git a/webkit/browser/fileapi/file_writer_delegate.cc b/storage/browser/fileapi/file_writer_delegate.cc index 976debe..fc533eb 100644 --- a/webkit/browser/fileapi/file_writer_delegate.cc +++ b/storage/browser/fileapi/file_writer_delegate.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/file_writer_delegate.h" +#include "storage/browser/fileapi/file_writer_delegate.h" #include "base/bind.h" #include "base/callback.h" @@ -12,9 +12,9 @@ #include "base/sequenced_task_runner.h" #include "base/threading/thread_restrictions.h" #include "net/base/net_errors.h" -#include "webkit/browser/fileapi/file_stream_writer.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/common/fileapi/file_system_util.h" +#include "storage/browser/fileapi/file_stream_writer.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/common/fileapi/file_system_util.h" namespace storage { diff --git a/storage/browser/fileapi/file_writer_delegate.h b/storage/browser/fileapi/file_writer_delegate.h new file mode 100644 index 0000000..eefad4c --- /dev/null +++ b/storage/browser/fileapi/file_writer_delegate.h @@ -0,0 +1,110 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_WRITER_DELEGATE_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_WRITER_DELEGATE_H_ + +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "base/time/time.h" +#include "net/base/file_stream.h" +#include "net/base/io_buffer.h" +#include "net/url_request/url_request.h" +#include "storage/browser/storage_browser_export.h" + +namespace storage { + +class FileStreamWriter; + +class STORAGE_EXPORT_PRIVATE FileWriterDelegate + : public net::URLRequest::Delegate { + public: + enum FlushPolicy { + FLUSH_ON_COMPLETION, + NO_FLUSH_ON_COMPLETION, + }; + + enum WriteProgressStatus { + SUCCESS_IO_PENDING, + SUCCESS_COMPLETED, + ERROR_WRITE_STARTED, + ERROR_WRITE_NOT_STARTED, + }; + + typedef base::Callback<void(base::File::Error result, + int64 bytes, + WriteProgressStatus write_status)> + DelegateWriteCallback; + + FileWriterDelegate(scoped_ptr<FileStreamWriter> file_writer, + FlushPolicy flush_policy); + virtual ~FileWriterDelegate(); + + void Start(scoped_ptr<net::URLRequest> request, + const DelegateWriteCallback& write_callback); + + // Cancels the current write operation. This will synchronously or + // asynchronously call the given write callback (which may result in + // deleting this). + void Cancel(); + + virtual void OnReceivedRedirect(net::URLRequest* request, + const net::RedirectInfo& redirect_info, + bool* defer_redirect) OVERRIDE; + virtual void OnAuthRequired(net::URLRequest* request, + net::AuthChallengeInfo* auth_info) OVERRIDE; + virtual void OnCertificateRequested( + net::URLRequest* request, + net::SSLCertRequestInfo* cert_request_info) OVERRIDE; + virtual void OnSSLCertificateError(net::URLRequest* request, + const net::SSLInfo& ssl_info, + bool fatal) OVERRIDE; + virtual void OnResponseStarted(net::URLRequest* request) OVERRIDE; + virtual void OnReadCompleted(net::URLRequest* request, + int bytes_read) OVERRIDE; + + private: + void OnGetFileInfoAndStartRequest( + scoped_ptr<net::URLRequest> request, + base::File::Error error, + const base::File::Info& file_info); + void Read(); + void OnDataReceived(int bytes_read); + void Write(); + void OnDataWritten(int write_response); + void OnError(base::File::Error error); + void OnProgress(int bytes_read, bool done); + void OnWriteCancelled(int status); + void MaybeFlushForCompletion(base::File::Error error, + int bytes_written, + WriteProgressStatus progress_status); + void OnFlushed(base::File::Error error, + int bytes_written, + WriteProgressStatus progress_status, + int flush_error); + + WriteProgressStatus GetCompletionStatusOnError() const; + + DelegateWriteCallback write_callback_; + scoped_ptr<FileStreamWriter> file_stream_writer_; + base::Time last_progress_event_time_; + bool writing_started_; + FlushPolicy flush_policy_; + int bytes_written_backlog_; + int bytes_written_; + int bytes_read_; + scoped_refptr<net::IOBufferWithSize> io_buffer_; + scoped_refptr<net::DrainableIOBuffer> cursor_; + scoped_ptr<net::URLRequest> request_; + + base::WeakPtrFactory<FileWriterDelegate> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(FileWriterDelegate); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_WRITER_DELEGATE_H_ diff --git a/webkit/browser/fileapi/isolated_context.cc b/storage/browser/fileapi/isolated_context.cc index 147e588..20e28c1 100644 --- a/webkit/browser/fileapi/isolated_context.cc +++ b/storage/browser/fileapi/isolated_context.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/isolated_context.h" +#include "storage/browser/fileapi/isolated_context.h" #include "base/basictypes.h" #include "base/files/file_path.h" @@ -12,7 +12,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" -#include "webkit/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/file_system_url.h" namespace storage { diff --git a/storage/browser/fileapi/isolated_context.h b/storage/browser/fileapi/isolated_context.h new file mode 100644 index 0000000..aa18e9b --- /dev/null +++ b/storage/browser/fileapi/isolated_context.h @@ -0,0 +1,201 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_ISOLATED_CONTEXT_H_ +#define STORAGE_BROWSER_FILEAPI_ISOLATED_CONTEXT_H_ + +#include <map> +#include <set> +#include <string> +#include <vector> + +#include "base/basictypes.h" +#include "base/files/file_path.h" +#include "base/lazy_instance.h" +#include "base/memory/singleton.h" +#include "base/synchronization/lock.h" +#include "storage/browser/fileapi/mount_points.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/fileapi/file_system_types.h" + +namespace storage { +class FileSystemURL; +} + +namespace storage { + +// Manages isolated filesystem mount points which have no well-known names +// and are identified by a string 'filesystem ID', which usually just looks +// like random value. +// This type of filesystem can be created on the fly and may go away when it has +// no references from renderers. +// Files in an isolated filesystem are registered with corresponding names and +// identified by a filesystem URL like: +// +// filesystem:<origin>/isolated/<filesystem_id>/<name>/relative/path +// +// Some methods of this class are virtual just for mocking. +// +class STORAGE_EXPORT IsolatedContext : public MountPoints { + public: + class STORAGE_EXPORT FileInfoSet { + public: + FileInfoSet(); + ~FileInfoSet(); + + // Add the given |path| to the set and populates |registered_name| with + // the registered name assigned for the path. |path| needs to be + // absolute and should not contain parent references. + // Return false if the |path| is not valid and could not be added. + bool AddPath(const base::FilePath& path, std::string* registered_name); + + // Add the given |path| with the |name|. + // Return false if the |name| is already registered in the set or + // is not valid and could not be added. + bool AddPathWithName(const base::FilePath& path, const std::string& name); + + const std::set<MountPointInfo>& fileset() const { return fileset_; } + + private: + std::set<MountPointInfo> fileset_; + }; + + // The instance is lazily created per browser process. + static IsolatedContext* GetInstance(); + + // Returns true if the given filesystem type is managed by IsolatedContext + // (i.e. if the given |type| is Isolated or External). + // TODO(kinuko): needs a better function name. + static bool IsIsolatedType(FileSystemType type); + + // Registers a new isolated filesystem with the given FileInfoSet |files| + // and returns the new filesystem_id. The files are registered with their + // register_name as their keys so that later we can resolve the full paths + // for the given name. We only expose the name and the ID for the + // newly created filesystem to the renderer for the sake of security. + // + // The renderer will be sending filesystem requests with a virtual path like + // '/<filesystem_id>/<registered_name>/<relative_path_from_the_dropped_path>' + // for which we could crack in the browser process by calling + // CrackIsolatedPath to get the full path. + // + // For example: if a dropped file has a path like '/a/b/foo' and we register + // the path with the name 'foo' in the newly created filesystem. + // Later if the context is asked to crack a virtual path like '/<fsid>/foo' + // it can properly return the original path '/a/b/foo' by looking up the + // internal mapping. Similarly if a dropped entry is a directory and its + // path is like '/a/b/dir' a virtual path like '/<fsid>/dir/foo' can be + // cracked into '/a/b/dir/foo'. + // + // Note that the path in |fileset| that contains '..' or is not an + // absolute path is skipped and is not registered. + std::string RegisterDraggedFileSystem(const FileInfoSet& files); + + // Registers a new isolated filesystem for a given |path| of filesystem + // |type| filesystem with |filesystem_id| and returns a new filesystem ID. + // |path| must be an absolute path which has no parent references ('..'). + // If |register_name| is non-null and has non-empty string the path is + // registered as the given |register_name|, otherwise it is populated + // with the name internally assigned to the path. + std::string RegisterFileSystemForPath(FileSystemType type, + const std::string& filesystem_id, + const base::FilePath& path, + std::string* register_name); + + // Registers a virtual filesystem. This is different from + // RegisterFileSystemForPath because register_name is required, and + // cracked_path_prefix is allowed to be non-absolute. + // |register_name| is required, since we cannot infer one from the path. + // |cracked_path_prefix| has no parent references, but can be relative. + std::string RegisterFileSystemForVirtualPath( + FileSystemType type, + const std::string& register_name, + const base::FilePath& cracked_path_prefix); + + // Revokes all filesystem(s) registered for the given path. + // This is assumed to be called when the registered path becomes + // globally invalid, e.g. when a device for the path is detached. + // + // Note that this revokes the filesystem no matter how many references it has. + // It is ok to call this for the path that has no associated filesystems. + // Note that this only works for the filesystems registered by + // |RegisterFileSystemForPath|. + void RevokeFileSystemByPath(const base::FilePath& path); + + // Adds a reference to a filesystem specified by the given filesystem_id. + void AddReference(const std::string& filesystem_id); + + // Removes a reference to a filesystem specified by the given filesystem_id. + // If the reference count reaches 0 the isolated context gets destroyed. + // It is OK to call this on the filesystem that has been already deleted + // (e.g. by RevokeFileSystemByPath). + void RemoveReference(const std::string& filesystem_id); + + // Returns a set of dragged MountPointInfos registered for the + // |filesystem_id|. + // The filesystem_id must be pointing to a dragged file system + // (i.e. must be the one registered by RegisterDraggedFileSystem). + // Returns false if the |filesystem_id| is not valid. + bool GetDraggedFileInfo(const std::string& filesystem_id, + std::vector<MountPointInfo>* files) const; + + // MountPoints overrides. + virtual bool HandlesFileSystemMountType(FileSystemType type) const OVERRIDE; + virtual bool RevokeFileSystem(const std::string& filesystem_id) OVERRIDE; + virtual bool GetRegisteredPath(const std::string& filesystem_id, + base::FilePath* path) const OVERRIDE; + virtual bool CrackVirtualPath( + const base::FilePath& virtual_path, + std::string* filesystem_id, + FileSystemType* type, + std::string* cracked_id, + base::FilePath* path, + FileSystemMountOption* mount_option) const OVERRIDE; + virtual FileSystemURL CrackURL(const GURL& url) const OVERRIDE; + virtual FileSystemURL CreateCrackedFileSystemURL( + const GURL& origin, + FileSystemType type, + const base::FilePath& path) const OVERRIDE; + + // Returns the virtual root path that looks like /<filesystem_id>. + base::FilePath CreateVirtualRootPath(const std::string& filesystem_id) const; + + private: + friend struct base::DefaultLazyInstanceTraits<IsolatedContext>; + + // Represents each file system instance (defined in the .cc). + class Instance; + + typedef std::map<std::string, Instance*> IDToInstance; + + // Reverse map from registered path to IDs. + typedef std::map<base::FilePath, std::set<std::string> > PathToID; + + // Obtain an instance of this class via GetInstance(). + IsolatedContext(); + virtual ~IsolatedContext(); + + // MountPoints overrides. + virtual FileSystemURL CrackFileSystemURL( + const FileSystemURL& url) const OVERRIDE; + + // Unregisters a file system of given |filesystem_id|. Must be called with + // lock_ held. Returns true if the file system is unregistered. + bool UnregisterFileSystem(const std::string& filesystem_id); + + // Returns a new filesystem_id. Called with lock. + std::string GetNewFileSystemId() const; + + // This lock needs to be obtained when accessing the instance_map_. + mutable base::Lock lock_; + + IDToInstance instance_map_; + PathToID path_to_id_map_; + + DISALLOW_COPY_AND_ASSIGN(IsolatedContext); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_ISOLATED_CONTEXT_H_ diff --git a/webkit/browser/fileapi/isolated_file_system_backend.cc b/storage/browser/fileapi/isolated_file_system_backend.cc index 1b5f346..90a0ce8 100644 --- a/webkit/browser/fileapi/isolated_file_system_backend.cc +++ b/storage/browser/fileapi/isolated_file_system_backend.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/isolated_file_system_backend.h" +#include "storage/browser/fileapi/isolated_file_system_backend.h" #include <string> @@ -12,20 +12,20 @@ #include "base/logging.h" #include "base/message_loop/message_loop_proxy.h" #include "base/sequenced_task_runner.h" -#include "webkit/browser/blob/file_stream_reader.h" -#include "webkit/browser/fileapi/async_file_util_adapter.h" -#include "webkit/browser/fileapi/copy_or_move_file_validator.h" -#include "webkit/browser/fileapi/dragged_file_util.h" -#include "webkit/browser/fileapi/file_stream_writer.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation.h" -#include "webkit/browser/fileapi/file_system_operation_context.h" -#include "webkit/browser/fileapi/isolated_context.h" -#include "webkit/browser/fileapi/native_file_util.h" -#include "webkit/browser/fileapi/transient_file_util.h" -#include "webkit/browser/fileapi/watcher_manager.h" -#include "webkit/common/fileapi/file_system_types.h" -#include "webkit/common/fileapi/file_system_util.h" +#include "storage/browser/blob/file_stream_reader.h" +#include "storage/browser/fileapi/async_file_util_adapter.h" +#include "storage/browser/fileapi/copy_or_move_file_validator.h" +#include "storage/browser/fileapi/dragged_file_util.h" +#include "storage/browser/fileapi/file_stream_writer.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation.h" +#include "storage/browser/fileapi/file_system_operation_context.h" +#include "storage/browser/fileapi/isolated_context.h" +#include "storage/browser/fileapi/native_file_util.h" +#include "storage/browser/fileapi/transient_file_util.h" +#include "storage/browser/fileapi/watcher_manager.h" +#include "storage/common/fileapi/file_system_types.h" +#include "storage/common/fileapi/file_system_util.h" namespace storage { diff --git a/storage/browser/fileapi/isolated_file_system_backend.h b/storage/browser/fileapi/isolated_file_system_backend.h new file mode 100644 index 0000000..3894ff4 --- /dev/null +++ b/storage/browser/fileapi/isolated_file_system_backend.h @@ -0,0 +1,57 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_ISOLATED_FILE_SYSTEM_BACKEND_H_ +#define STORAGE_BROWSER_FILEAPI_ISOLATED_FILE_SYSTEM_BACKEND_H_ + +#include "base/memory/scoped_ptr.h" +#include "storage/browser/fileapi/file_system_backend.h" + +namespace storage { + +class AsyncFileUtilAdapter; + +class IsolatedFileSystemBackend : public FileSystemBackend { + public: + IsolatedFileSystemBackend(); + virtual ~IsolatedFileSystemBackend(); + + // FileSystemBackend implementation. + virtual bool CanHandleType(FileSystemType type) const OVERRIDE; + virtual void Initialize(FileSystemContext* context) OVERRIDE; + virtual void ResolveURL(const FileSystemURL& url, + OpenFileSystemMode mode, + const OpenFileSystemCallback& callback) OVERRIDE; + virtual AsyncFileUtil* GetAsyncFileUtil(FileSystemType type) OVERRIDE; + virtual WatcherManager* GetWatcherManager(FileSystemType type) OVERRIDE; + virtual CopyOrMoveFileValidatorFactory* GetCopyOrMoveFileValidatorFactory( + FileSystemType type, + base::File::Error* error_code) OVERRIDE; + virtual FileSystemOperation* CreateFileSystemOperation( + const FileSystemURL& url, + FileSystemContext* context, + base::File::Error* error_code) const OVERRIDE; + virtual bool SupportsStreaming(const FileSystemURL& url) const OVERRIDE; + virtual bool HasInplaceCopyImplementation( + storage::FileSystemType type) const OVERRIDE; + virtual scoped_ptr<storage::FileStreamReader> CreateFileStreamReader( + const FileSystemURL& url, + int64 offset, + const base::Time& expected_modification_time, + FileSystemContext* context) const OVERRIDE; + virtual scoped_ptr<FileStreamWriter> CreateFileStreamWriter( + const FileSystemURL& url, + int64 offset, + FileSystemContext* context) const OVERRIDE; + virtual FileSystemQuotaUtil* GetQuotaUtil() OVERRIDE; + + private: + scoped_ptr<AsyncFileUtilAdapter> isolated_file_util_; + scoped_ptr<AsyncFileUtilAdapter> dragged_file_util_; + scoped_ptr<AsyncFileUtilAdapter> transient_file_util_; +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_ISOLATED_FILE_SYSTEM_BACKEND_H_ diff --git a/webkit/browser/fileapi/local_file_stream_writer.cc b/storage/browser/fileapi/local_file_stream_writer.cc index 6f58ffa..0eb555f 100644 --- a/webkit/browser/fileapi/local_file_stream_writer.cc +++ b/storage/browser/fileapi/local_file_stream_writer.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/local_file_stream_writer.h" +#include "storage/browser/fileapi/local_file_stream_writer.h" #include "base/callback.h" #include "base/message_loop/message_loop.h" diff --git a/storage/browser/fileapi/local_file_stream_writer.h b/storage/browser/fileapi/local_file_stream_writer.h new file mode 100644 index 0000000..17417d0 --- /dev/null +++ b/storage/browser/fileapi/local_file_stream_writer.h @@ -0,0 +1,100 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_LOCAL_FILE_STREAM_WRITER_H_ +#define STORAGE_BROWSER_FILEAPI_LOCAL_FILE_STREAM_WRITER_H_ + +#include <utility> + +#include "base/callback.h" +#include "base/compiler_specific.h" +#include "base/files/file_path.h" +#include "base/gtest_prod_util.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "base/task_runner.h" +#include "storage/browser/fileapi/file_stream_writer.h" +#include "storage/browser/storage_browser_export.h" + +namespace content { +class LocalFileStreamWriterTest; +} + +namespace net { +class FileStream; +} + +namespace storage { + +// This class is a thin wrapper around net::FileStream for writing local files. +class STORAGE_EXPORT LocalFileStreamWriter + : public NON_EXPORTED_BASE(FileStreamWriter) { + public: + virtual ~LocalFileStreamWriter(); + + // FileStreamWriter overrides. + virtual int Write(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback) OVERRIDE; + virtual int Cancel(const net::CompletionCallback& callback) OVERRIDE; + virtual int Flush(const net::CompletionCallback& callback) OVERRIDE; + + private: + friend class content::LocalFileStreamWriterTest; + friend class FileStreamWriter; + LocalFileStreamWriter(base::TaskRunner* task_runner, + const base::FilePath& file_path, + int64 initial_offset, + OpenOrCreate open_or_create); + + // Opens |file_path_| and if it succeeds, proceeds to InitiateSeek(). + // If failed, the error code is returned by calling |error_callback|. + int InitiateOpen(const net::CompletionCallback& error_callback, + const base::Closure& main_operation); + void DidOpen(const net::CompletionCallback& error_callback, + const base::Closure& main_operation, + int result); + + // Seeks to |initial_offset_| and proceeds to |main_operation| if it succeeds. + // If failed, the error code is returned by calling |error_callback|. + void InitiateSeek(const net::CompletionCallback& error_callback, + const base::Closure& main_operation); + void DidSeek(const net::CompletionCallback& error_callback, + const base::Closure& main_operation, + int64 result); + + // Passed as the |main_operation| of InitiateOpen() function. + void ReadyToWrite(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback); + + // Writes asynchronously to the file. + int InitiateWrite(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback); + void DidWrite(const net::CompletionCallback& callback, int result); + + // Flushes asynchronously to the file. + int InitiateFlush(const net::CompletionCallback& callback); + void DidFlush(const net::CompletionCallback& callback, int result); + + // Stops the in-flight operation and calls |cancel_callback_| if it has been + // set by Cancel() for the current operation. + bool CancelIfRequested(); + + // Initialization parameters. + const base::FilePath file_path_; + OpenOrCreate open_or_create_; + const int64 initial_offset_; + scoped_refptr<base::TaskRunner> task_runner_; + + // Current states of the operation. + bool has_pending_operation_; + scoped_ptr<net::FileStream> stream_impl_; + net::CompletionCallback cancel_callback_; + + base::WeakPtrFactory<LocalFileStreamWriter> weak_factory_; + DISALLOW_COPY_AND_ASSIGN(LocalFileStreamWriter); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_LOCAL_FILE_STREAM_WRITER_H_ diff --git a/webkit/browser/fileapi/local_file_util.cc b/storage/browser/fileapi/local_file_util.cc index a33afdc..19ce59e 100644 --- a/webkit/browser/fileapi/local_file_util.cc +++ b/storage/browser/fileapi/local_file_util.cc @@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/local_file_util.h" +#include "storage/browser/fileapi/local_file_util.h" #include "base/files/file_enumerator.h" #include "base/files/file_util.h" #include "base/files/file_util_proxy.h" +#include "storage/browser/fileapi/async_file_util_adapter.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation_context.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/native_file_util.h" +#include "storage/common/fileapi/file_system_types.h" +#include "storage/common/fileapi/file_system_util.h" #include "url/gurl.h" -#include "webkit/browser/fileapi/async_file_util_adapter.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation_context.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/fileapi/native_file_util.h" -#include "webkit/common/fileapi/file_system_types.h" -#include "webkit/common/fileapi/file_system_util.h" namespace storage { diff --git a/storage/browser/fileapi/local_file_util.h b/storage/browser/fileapi/local_file_util.h new file mode 100644 index 0000000..dbbdef0 --- /dev/null +++ b/storage/browser/fileapi/local_file_util.h @@ -0,0 +1,94 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_LOCAL_FILE_UTIL_H_ +#define STORAGE_BROWSER_FILEAPI_LOCAL_FILE_UTIL_H_ + +#include "base/compiler_specific.h" +#include "base/files/file_path.h" +#include "base/memory/scoped_ptr.h" +#include "storage/browser/fileapi/file_system_file_util.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class Time; +} + +class GURL; + +namespace storage { + +class FileSystemOperationContext; +class FileSystemURL; + +// An instance of this class is created and owned by *FileSystemBackend. +class STORAGE_EXPORT LocalFileUtil + : public FileSystemFileUtil { + public: + LocalFileUtil(); + virtual ~LocalFileUtil(); + + virtual base::File CreateOrOpen( + FileSystemOperationContext* context, + const FileSystemURL& url, + int file_flags) OVERRIDE; + virtual base::File::Error EnsureFileExists( + FileSystemOperationContext* context, + const FileSystemURL& url, bool* created) OVERRIDE; + virtual base::File::Error CreateDirectory( + FileSystemOperationContext* context, + const FileSystemURL& url, + bool exclusive, + bool recursive) OVERRIDE; + virtual base::File::Error GetFileInfo( + FileSystemOperationContext* context, + const FileSystemURL& url, + base::File::Info* file_info, + base::FilePath* platform_file) OVERRIDE; + virtual scoped_ptr<AbstractFileEnumerator> CreateFileEnumerator( + FileSystemOperationContext* context, + const FileSystemURL& root_url) OVERRIDE; + virtual base::File::Error GetLocalFilePath( + FileSystemOperationContext* context, + const FileSystemURL& file_system_url, + base::FilePath* local_file_path) OVERRIDE; + virtual base::File::Error Touch( + FileSystemOperationContext* context, + const FileSystemURL& url, + const base::Time& last_access_time, + const base::Time& last_modified_time) OVERRIDE; + virtual base::File::Error Truncate( + FileSystemOperationContext* context, + const FileSystemURL& url, + int64 length) OVERRIDE; + virtual base::File::Error CopyOrMoveFile( + FileSystemOperationContext* context, + const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + bool copy) OVERRIDE; + virtual base::File::Error CopyInForeignFile( + FileSystemOperationContext* context, + const base::FilePath& src_file_path, + const FileSystemURL& dest_url) OVERRIDE; + virtual base::File::Error DeleteFile( + FileSystemOperationContext* context, + const FileSystemURL& url) OVERRIDE; + virtual base::File::Error DeleteDirectory( + FileSystemOperationContext* context, + const FileSystemURL& url) OVERRIDE; + virtual storage::ScopedFile CreateSnapshotFile( + FileSystemOperationContext* context, + const FileSystemURL& url, + base::File::Error* error, + base::File::Info* file_info, + base::FilePath* platform_path) OVERRIDE; + + private: + DISALLOW_COPY_AND_ASSIGN(LocalFileUtil); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_LOCAL_FILE_UTIL_H_ diff --git a/webkit/browser/fileapi/mount_points.cc b/storage/browser/fileapi/mount_points.cc index 9523071..bc0bf84 100644 --- a/webkit/browser/fileapi/mount_points.cc +++ b/storage/browser/fileapi/mount_points.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/mount_points.h" +#include "storage/browser/fileapi/mount_points.h" namespace storage { diff --git a/storage/browser/fileapi/mount_points.h b/storage/browser/fileapi/mount_points.h new file mode 100644 index 0000000..61da5fa --- /dev/null +++ b/storage/browser/fileapi/mount_points.h @@ -0,0 +1,108 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_MOUNT_POINTS_H_ +#define STORAGE_BROWSER_FILEAPI_MOUNT_POINTS_H_ + +#include <string> +#include <vector> + +#include "base/basictypes.h" +#include "base/files/file_path.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/fileapi/file_system_util.h" + +class GURL; + +namespace storage { +class FileSystemMountOption; +class FileSystemURL; +} + +namespace storage { + +// Represents a set of mount points for File API. +class STORAGE_EXPORT MountPoints { + public: + struct STORAGE_EXPORT MountPointInfo { + MountPointInfo(); + MountPointInfo(const std::string& name, const base::FilePath& path); + + // The name to be used to register the path. The registered file can + // be referred by a virtual path /<filesystem_id>/<name>. + // The name should NOT contain a path separator '/'. + std::string name; + + // The path of the file. + base::FilePath path; + + // For STL operation. + bool operator<(const MountPointInfo& that) const { + return name < that.name; + } + }; + + MountPoints() {} + virtual ~MountPoints() {} + + // Revokes a mount point identified by |mount_name|. + // Returns false if the |mount_name| is not (no longer) registered. + // TODO(kinuko): Probably this should be rather named RevokeMountPoint. + virtual bool RevokeFileSystem(const std::string& mount_name) = 0; + + // Returns true if the MountPoints implementation handles filesystems with + // the given mount type. + virtual bool HandlesFileSystemMountType(FileSystemType type) const = 0; + + // Same as CreateCrackedFileSystemURL, but cracks FileSystemURL created + // from |url|. + virtual FileSystemURL CrackURL(const GURL& url) const = 0; + + // Creates a FileSystemURL with the given origin, type and path and tries to + // crack it as a part of one of the registered mount points. + // If the the URL is not valid or does not belong to any of the mount points + // registered in this context, returns empty, invalid FileSystemURL. + virtual FileSystemURL CreateCrackedFileSystemURL( + const GURL& origin, + storage::FileSystemType type, + const base::FilePath& path) const = 0; + + // Returns the mount point root path registered for a given |mount_name|. + // Returns false if the given |mount_name| is not valid. + virtual bool GetRegisteredPath(const std::string& mount_name, + base::FilePath* path) const = 0; + + // Cracks the given |virtual_path| (which is the path part of a filesystem URL + // without '/external' or '/isolated' prefix part) and populates the + // |mount_name|, |type|, and |path| if the <mount_name> part embedded in + // the |virtual_path| (i.e. the first component of the |virtual_path|) is a + // valid registered filesystem ID or mount name for an existing mount point. + // + // Returns false if the given virtual_path cannot be cracked. + // + // Note that |path| is set to empty paths if the filesystem type is isolated + // and |virtual_path| has no <relative_path> part (i.e. pointing to the + // virtual root). + virtual bool CrackVirtualPath(const base::FilePath& virtual_path, + std::string* mount_name, + FileSystemType* type, + std::string* cracked_id, + base::FilePath* path, + FileSystemMountOption* mount_option) const = 0; + + protected: + friend class FileSystemContext; + + // Same as CrackURL and CreateCrackedFileSystemURL, but cracks the url already + // instantiated as the FileSystemURL class. This is internally used for nested + // URL cracking in FileSystemContext. + virtual FileSystemURL CrackFileSystemURL(const FileSystemURL& url) const = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(MountPoints); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_MOUNT_POINTS_H_ diff --git a/webkit/browser/fileapi/native_file_util.cc b/storage/browser/fileapi/native_file_util.cc index fbfb6e4..b44179c 100644 --- a/webkit/browser/fileapi/native_file_util.cc +++ b/storage/browser/fileapi/native_file_util.cc @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/native_file_util.h" +#include "storage/browser/fileapi/native_file_util.h" #include "base/files/file.h" #include "base/files/file_enumerator.h" #include "base/files/file_util.h" #include "base/memory/scoped_ptr.h" -#include "webkit/browser/fileapi/file_system_operation_context.h" -#include "webkit/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/file_system_operation_context.h" +#include "storage/browser/fileapi/file_system_url.h" namespace storage { diff --git a/storage/browser/fileapi/native_file_util.h b/storage/browser/fileapi/native_file_util.h new file mode 100644 index 0000000..b8c180e --- /dev/null +++ b/storage/browser/fileapi/native_file_util.h @@ -0,0 +1,73 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_NATIVE_FILE_UTIL_H_ +#define STORAGE_BROWSER_FILEAPI_NATIVE_FILE_UTIL_H_ + +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/files/file_util_proxy.h" +#include "base/memory/scoped_ptr.h" +#include "storage/browser/fileapi/file_system_file_util.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class Time; +} + +namespace storage { + +// A thin wrapper class for accessing the OS native filesystem. +// This performs common error checks necessary to implement FileUtil family +// in addition to perform native filesystem operations. +// +// For the error checks it performs please see the comment for +// FileSystemFileUtil interface +// (webkit/browser/fileapi/file_system_file_util.h). +// +// Note that all the methods of this class are static and this does NOT +// inherit from FileSystemFileUtil. +class STORAGE_EXPORT_PRIVATE NativeFileUtil { + public: + enum CopyOrMoveMode { + COPY_NOSYNC, + COPY_SYNC, + MOVE + }; + static CopyOrMoveMode CopyOrMoveModeForDestination( + const FileSystemURL& dest_url, bool copy); + + static base::File CreateOrOpen(const base::FilePath& path, int file_flags); + static base::File::Error EnsureFileExists(const base::FilePath& path, + bool* created); + static base::File::Error CreateDirectory(const base::FilePath& path, + bool exclusive, + bool recursive); + static base::File::Error GetFileInfo(const base::FilePath& path, + base::File::Info* file_info); + static scoped_ptr<FileSystemFileUtil::AbstractFileEnumerator> + CreateFileEnumerator(const base::FilePath& root_path, + bool recursive); + static base::File::Error Touch(const base::FilePath& path, + const base::Time& last_access_time, + const base::Time& last_modified_time); + static base::File::Error Truncate(const base::FilePath& path, + int64 length); + static bool PathExists(const base::FilePath& path); + static bool DirectoryExists(const base::FilePath& path); + static base::File::Error CopyOrMoveFile( + const base::FilePath& src_path, + const base::FilePath& dest_path, + FileSystemOperation::CopyOrMoveOption option, + CopyOrMoveMode mode); + static base::File::Error DeleteFile(const base::FilePath& path); + static base::File::Error DeleteDirectory(const base::FilePath& path); + + private: + DISALLOW_IMPLICIT_CONSTRUCTORS(NativeFileUtil); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_NATIVE_FILE_UTIL_H_ diff --git a/webkit/browser/fileapi/obfuscated_file_util.cc b/storage/browser/fileapi/obfuscated_file_util.cc index 42ee7d3..8c02dd1 100644 --- a/webkit/browser/fileapi/obfuscated_file_util.cc +++ b/storage/browser/fileapi/obfuscated_file_util.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/obfuscated_file_util.h" +#include "storage/browser/fileapi/obfuscated_file_util.h" #include <queue> #include <string> @@ -19,20 +19,20 @@ #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" +#include "storage/browser/fileapi/file_observers.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation_context.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/native_file_util.h" +#include "storage/browser/fileapi/sandbox_file_system_backend.h" +#include "storage/browser/fileapi/sandbox_isolated_origin_database.h" +#include "storage/browser/fileapi/sandbox_origin_database.h" +#include "storage/browser/fileapi/sandbox_prioritized_origin_database.h" +#include "storage/browser/fileapi/timed_task_helper.h" +#include "storage/browser/quota/quota_manager.h" +#include "storage/common/database/database_identifier.h" +#include "storage/common/fileapi/file_system_util.h" #include "url/gurl.h" -#include "webkit/browser/fileapi/file_observers.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation_context.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/fileapi/native_file_util.h" -#include "webkit/browser/fileapi/sandbox_file_system_backend.h" -#include "webkit/browser/fileapi/sandbox_isolated_origin_database.h" -#include "webkit/browser/fileapi/sandbox_origin_database.h" -#include "webkit/browser/fileapi/sandbox_prioritized_origin_database.h" -#include "webkit/browser/fileapi/timed_task_helper.h" -#include "webkit/browser/quota/quota_manager.h" -#include "webkit/common/database/database_identifier.h" -#include "webkit/common/fileapi/file_system_util.h" // Example of various paths: // void ObfuscatedFileUtil::DoSomething(const FileSystemURL& url) { diff --git a/storage/browser/fileapi/obfuscated_file_util.h b/storage/browser/fileapi/obfuscated_file_util.h new file mode 100644 index 0000000..822a85d --- /dev/null +++ b/storage/browser/fileapi/obfuscated_file_util.h @@ -0,0 +1,359 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_OBFUSCATED_FILE_UTIL_H_ +#define STORAGE_BROWSER_FILEAPI_OBFUSCATED_FILE_UTIL_H_ + +#include <map> +#include <set> +#include <string> +#include <vector> + +#include "base/callback_forward.h" +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/files/file_util_proxy.h" +#include "base/gtest_prod_util.h" +#include "base/memory/scoped_ptr.h" +#include "storage/browser/fileapi/file_system_file_util.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/sandbox_directory_database.h" +#include "storage/browser/fileapi/sandbox_file_system_backend_delegate.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/blob/shareable_file_reference.h" +#include "storage/common/fileapi/file_system_types.h" + +namespace base { +class SequencedTaskRunner; +class TimeTicks; +} + +namespace content { +class ObfuscatedFileUtilTest; +class QuotaBackendImplTest; +} + +namespace storage { +class SpecialStoragePolicy; +} + +class GURL; + +namespace storage { + +class FileSystemOperationContext; +class SandboxOriginDatabaseInterface; +class TimedTaskHelper; + +// This file util stores directory information in LevelDB to obfuscate +// and to neutralize virtual file paths given by arbitrary apps. +// Files are stored with two-level isolation: per-origin and per-type. +// The isolation is done by storing data in separate directory partitions. +// For example, a file in Temporary file system for origin 'www.example.com' +// is stored in a different partition for a file in Persistent file system +// for the same origin, or for Temporary file system for another origin. +// +// * Per-origin directory name information is stored in a separate LevelDB, +// which is maintained by SandboxOriginDatabase. +// * Per-type directory name information is given by +// GetTypeStringForURLCallback that is given in CTOR. +// We use a small static mapping (e.g. 't' for Temporary type) for +// regular sandbox filesystems. +// +// The overall implementation philosophy of this class is that partial failures +// should leave us with an intact database; we'd prefer to leak the occasional +// backing file than have a database entry whose backing file is missing. When +// doing FSCK operations, if you find a loose backing file with no reference, +// you may safely delete it. +// +// This class must be deleted on the FILE thread, because that's where +// DropDatabases needs to be called. +class STORAGE_EXPORT_PRIVATE ObfuscatedFileUtil + : public FileSystemFileUtil { + public: + // Origin enumerator interface. + // An instance of this interface is assumed to be called on the file thread. + class AbstractOriginEnumerator { + public: + virtual ~AbstractOriginEnumerator() {} + + // Returns the next origin. Returns empty if there are no more origins. + virtual GURL Next() = 0; + + // Returns the current origin's information. + // |type_string| must be ascii string. + virtual bool HasTypeDirectory(const std::string& type_string) const = 0; + }; + + typedef base::Callback<std::string(const FileSystemURL&)> + GetTypeStringForURLCallback; + + // |get_type_string_for_url| is user-defined callback that should return + // a type string for the given FileSystemURL. The type string is used + // to provide per-type isolation in the sandboxed filesystem directory. + // Note that this method is called on file_task_runner. + // + // |known_type_strings| are known type string names that this file system + // should care about. + // This info is used to determine whether we could delete the entire + // origin directory or not in DeleteDirectoryForOriginAndType. If no directory + // for any known type exists the origin directory may get deleted when + // one origin/type pair is deleted. + // + ObfuscatedFileUtil(storage::SpecialStoragePolicy* special_storage_policy, + const base::FilePath& file_system_directory, + leveldb::Env* env_override, + base::SequencedTaskRunner* file_task_runner, + const GetTypeStringForURLCallback& get_type_string_for_url, + const std::set<std::string>& known_type_strings, + SandboxFileSystemBackendDelegate* sandbox_delegate); + virtual ~ObfuscatedFileUtil(); + + // FileSystemFileUtil overrides. + virtual base::File CreateOrOpen( + FileSystemOperationContext* context, + const FileSystemURL& url, + int file_flags) OVERRIDE; + virtual base::File::Error EnsureFileExists( + FileSystemOperationContext* context, + const FileSystemURL& url, bool* created) OVERRIDE; + virtual base::File::Error CreateDirectory( + FileSystemOperationContext* context, + const FileSystemURL& url, + bool exclusive, + bool recursive) OVERRIDE; + virtual base::File::Error GetFileInfo( + FileSystemOperationContext* context, + const FileSystemURL& url, + base::File::Info* file_info, + base::FilePath* platform_file) OVERRIDE; + virtual scoped_ptr<AbstractFileEnumerator> CreateFileEnumerator( + FileSystemOperationContext* context, + const FileSystemURL& root_url) OVERRIDE; + virtual base::File::Error GetLocalFilePath( + FileSystemOperationContext* context, + const FileSystemURL& file_system_url, + base::FilePath* local_path) OVERRIDE; + virtual base::File::Error Touch( + FileSystemOperationContext* context, + const FileSystemURL& url, + const base::Time& last_access_time, + const base::Time& last_modified_time) OVERRIDE; + virtual base::File::Error Truncate( + FileSystemOperationContext* context, + const FileSystemURL& url, + int64 length) OVERRIDE; + virtual base::File::Error CopyOrMoveFile( + FileSystemOperationContext* context, + const FileSystemURL& src_url, + const FileSystemURL& dest_url, + CopyOrMoveOption option, + bool copy) OVERRIDE; + virtual base::File::Error CopyInForeignFile( + FileSystemOperationContext* context, + const base::FilePath& src_file_path, + const FileSystemURL& dest_url) OVERRIDE; + virtual base::File::Error DeleteFile( + FileSystemOperationContext* context, + const FileSystemURL& url) OVERRIDE; + virtual base::File::Error DeleteDirectory( + FileSystemOperationContext* context, + const FileSystemURL& url) OVERRIDE; + virtual storage::ScopedFile CreateSnapshotFile( + FileSystemOperationContext* context, + const FileSystemURL& url, + base::File::Error* error, + base::File::Info* file_info, + base::FilePath* platform_path) OVERRIDE; + + // Same as the other CreateFileEnumerator, but with recursive support. + scoped_ptr<AbstractFileEnumerator> CreateFileEnumerator( + FileSystemOperationContext* context, + const FileSystemURL& root_url, + bool recursive); + + // Returns true if the directory |url| is empty. + bool IsDirectoryEmpty( + FileSystemOperationContext* context, + const FileSystemURL& url); + + // Gets the topmost directory specific to this origin and type. This will + // contain both the directory database's files and all the backing file + // subdirectories. + // Returns the topmost origin directory if |type_string| is empty. + // Returns an empty path if the directory is undefined. + // If the directory is defined, it will be returned, even if + // there is a file system error (e.g. the directory doesn't exist on disk and + // |create| is false). Callers should always check |error_code| to make sure + // the returned path is usable. + base::FilePath GetDirectoryForOriginAndType( + const GURL& origin, + const std::string& type_string, + bool create, + base::File::Error* error_code); + + // Deletes the topmost directory specific to this origin and type. This will + // delete its directory database. + // Deletes the topmost origin directory if |type_string| is empty. + bool DeleteDirectoryForOriginAndType( + const GURL& origin, + const std::string& type_string); + + // This method and all methods of its returned class must be called only on + // the FILE thread. The caller is responsible for deleting the returned + // object. + AbstractOriginEnumerator* CreateOriginEnumerator(); + + // Deletes a directory database from the database list in the ObfuscatedFSFU + // and destroys the database on the disk. + bool DestroyDirectoryDatabase(const GURL& origin, + const std::string& type_string); + + // Computes a cost for storing a given file in the obfuscated FSFU. + // As the cost of a file is independent of the cost of its parent directories, + // this ignores all but the BaseName of the supplied path. In order to + // compute the cost of adding a multi-segment directory recursively, call this + // on each path segment and add the results. + static int64 ComputeFilePathCost(const base::FilePath& path); + + // Tries to prepopulate directory database for the given type strings. + // This tries from the first one in the given type_strings and stops + // once it succeeds to do so for one database (i.e. it prepopulates + // at most one database). + void MaybePrepopulateDatabase( + const std::vector<std::string>& type_strings_to_prepopulate); + + private: + typedef SandboxDirectoryDatabase::FileId FileId; + typedef SandboxDirectoryDatabase::FileInfo FileInfo; + + friend class ObfuscatedFileEnumerator; + friend class content::ObfuscatedFileUtilTest; + friend class content::QuotaBackendImplTest; + + // Helper method to create an obfuscated file util for regular + // (temporary, persistent) file systems. Used only for testing. + // Note: this is implemented in sandbox_file_system_backend_delegate.cc. + static ObfuscatedFileUtil* CreateForTesting( + storage::SpecialStoragePolicy* special_storage_policy, + const base::FilePath& file_system_directory, + leveldb::Env* env_override, + base::SequencedTaskRunner* file_task_runner); + + base::FilePath GetDirectoryForURL( + const FileSystemURL& url, + bool create, + base::File::Error* error_code); + + // This just calls get_type_string_for_url_ callback that is given in ctor. + std::string CallGetTypeStringForURL(const FileSystemURL& url); + + base::File::Error GetFileInfoInternal( + SandboxDirectoryDatabase* db, + FileSystemOperationContext* context, + const FileSystemURL& url, + FileId file_id, + FileInfo* local_info, + base::File::Info* file_info, + base::FilePath* platform_file_path); + + // Creates a new file, both the underlying backing file and the entry in the + // database. |dest_file_info| is an in-out parameter. Supply the name and + // parent_id; data_path is ignored. On success, data_path will + // always be set to the relative path [from the root of the type-specific + // filesystem directory] of a NEW backing file. Returns the new file. + base::File CreateAndOpenFile( + FileSystemOperationContext* context, + const FileSystemURL& dest_url, + FileInfo* dest_file_info, + int file_flags); + + // The same as CreateAndOpenFile except that a file is not returned and if a + // path is provided in |source_path|, it will be used as a source from which + // to COPY data. + base::File::Error CreateFile( + FileSystemOperationContext* context, + const base::FilePath& source_file_path, + const FileSystemURL& dest_url, + FileInfo* dest_file_info); + + // Updates |db| and |dest_file_info| at the end of creating a new file. + base::File::Error CommitCreateFile( + const base::FilePath& root, + const base::FilePath& local_path, + SandboxDirectoryDatabase* db, + FileInfo* dest_file_info); + + // This converts from a relative path [as is stored in the FileInfo.data_path + // field] to an absolute platform path that can be given to the native + // filesystem. + base::FilePath DataPathToLocalPath( + const FileSystemURL& url, + const base::FilePath& data_file_path); + + std::string GetDirectoryDatabaseKey(const GURL& origin, + const std::string& type_string); + + // This returns NULL if |create| flag is false and a filesystem does not + // exist for the given |url|. + // For read operations |create| should be false. + SandboxDirectoryDatabase* GetDirectoryDatabase(const FileSystemURL& url, + bool create); + + // Gets the topmost directory specific to this origin. This will + // contain both the filesystem type subdirectories. + base::FilePath GetDirectoryForOrigin(const GURL& origin, + bool create, + base::File::Error* error_code); + + void InvalidateUsageCache(FileSystemOperationContext* context, + const GURL& origin, + FileSystemType type); + + void MarkUsed(); + void DropDatabases(); + + // Initializes the origin database. |origin_hint| may be used as a hint + // for initializing database if it's not empty. + bool InitOriginDatabase(const GURL& origin_hint, bool create); + + base::File::Error GenerateNewLocalPath( + SandboxDirectoryDatabase* db, + FileSystemOperationContext* context, + const FileSystemURL& url, + base::FilePath* root, + base::FilePath* local_path); + + base::File CreateOrOpenInternal( + FileSystemOperationContext* context, + const FileSystemURL& url, + int file_flags); + + bool HasIsolatedStorage(const GURL& origin); + + typedef std::map<std::string, SandboxDirectoryDatabase*> DirectoryMap; + DirectoryMap directories_; + scoped_ptr<SandboxOriginDatabaseInterface> origin_database_; + scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy_; + base::FilePath file_system_directory_; + leveldb::Env* env_override_; + + // Used to delete database after a certain period of inactivity. + int64 db_flush_delay_seconds_; + + scoped_refptr<base::SequencedTaskRunner> file_task_runner_; + scoped_ptr<TimedTaskHelper> timer_; + + GetTypeStringForURLCallback get_type_string_for_url_; + std::set<std::string> known_type_strings_; + + // Not owned. + SandboxFileSystemBackendDelegate* sandbox_delegate_; + + DISALLOW_COPY_AND_ASSIGN(ObfuscatedFileUtil); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_OBFUSCATED_FILE_UTIL_H_ diff --git a/storage/browser/fileapi/open_file_system_mode.h b/storage/browser/fileapi/open_file_system_mode.h new file mode 100644 index 0000000..03943fd --- /dev/null +++ b/storage/browser/fileapi/open_file_system_mode.h @@ -0,0 +1,22 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_OPEN_FILE_SYSTEM_MODE_H_ +#define STORAGE_BROWSER_FILEAPI_OPEN_FILE_SYSTEM_MODE_H_ + +namespace storage { + +// Determines the behavior on OpenFileSystem when a specified +// FileSystem does not exist. +// Specifying CREATE_IF_NONEXISTENT may make actual modification on +// disk (e.g. creating a root directory, setting up a metadata database etc) +// if the filesystem hasn't been initialized. +enum OpenFileSystemMode { + OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, + OPEN_FILE_SYSTEM_FAIL_IF_NONEXISTENT, +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_OPEN_FILE_SYSTEM_MODE_H_ diff --git a/webkit/browser/fileapi/plugin_private_file_system_backend.cc b/storage/browser/fileapi/plugin_private_file_system_backend.cc index 0a3cbf9..6906986 100644 --- a/webkit/browser/fileapi/plugin_private_file_system_backend.cc +++ b/storage/browser/fileapi/plugin_private_file_system_backend.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/plugin_private_file_system_backend.h" +#include "storage/browser/fileapi/plugin_private_file_system_backend.h" #include <map> @@ -10,17 +10,17 @@ #include "base/synchronization/lock.h" #include "base/task_runner_util.h" #include "net/base/net_util.h" -#include "webkit/browser/blob/file_stream_reader.h" -#include "webkit/browser/fileapi/async_file_util_adapter.h" -#include "webkit/browser/fileapi/file_stream_writer.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation.h" -#include "webkit/browser/fileapi/file_system_operation_context.h" -#include "webkit/browser/fileapi/file_system_options.h" -#include "webkit/browser/fileapi/isolated_context.h" -#include "webkit/browser/fileapi/obfuscated_file_util.h" -#include "webkit/browser/fileapi/quota/quota_reservation.h" -#include "webkit/common/fileapi/file_system_util.h" +#include "storage/browser/blob/file_stream_reader.h" +#include "storage/browser/fileapi/async_file_util_adapter.h" +#include "storage/browser/fileapi/file_stream_writer.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation.h" +#include "storage/browser/fileapi/file_system_operation_context.h" +#include "storage/browser/fileapi/file_system_options.h" +#include "storage/browser/fileapi/isolated_context.h" +#include "storage/browser/fileapi/obfuscated_file_util.h" +#include "storage/browser/fileapi/quota/quota_reservation.h" +#include "storage/common/fileapi/file_system_util.h" namespace storage { diff --git a/storage/browser/fileapi/plugin_private_file_system_backend.h b/storage/browser/fileapi/plugin_private_file_system_backend.h new file mode 100644 index 0000000..a49e07d --- /dev/null +++ b/storage/browser/fileapi/plugin_private_file_system_backend.h @@ -0,0 +1,149 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_PLUGIN_PRIVATE_FILE_SYSTEM_BACKEND_H_ +#define STORAGE_BROWSER_FILEAPI_PLUGIN_PRIVATE_FILE_SYSTEM_BACKEND_H_ + +#include <set> +#include <string> + +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "storage/browser/fileapi/file_system_backend.h" +#include "storage/browser/fileapi/file_system_options.h" +#include "storage/browser/fileapi/file_system_quota_util.h" + +namespace base { +class SequencedTaskRunner; +} + +namespace content { +class PluginPrivateFileSystemBackendTest; +} + +namespace storage { +class SpecialStoragePolicy; +} + +namespace storage { + +class ObfuscatedFileUtil; +class WatcherManager; + +class STORAGE_EXPORT PluginPrivateFileSystemBackend + : public FileSystemBackend, + public FileSystemQuotaUtil { + public: + class FileSystemIDToPluginMap; + typedef base::Callback<void(base::File::Error result)> StatusCallback; + + PluginPrivateFileSystemBackend( + base::SequencedTaskRunner* file_task_runner, + const base::FilePath& profile_path, + storage::SpecialStoragePolicy* special_storage_policy, + const FileSystemOptions& file_system_options); + virtual ~PluginPrivateFileSystemBackend(); + + // This must be used to open 'private' filesystem instead of regular + // OpenFileSystem. + // |plugin_id| must be an identifier string for per-plugin + // isolation, e.g. name, MIME type etc. + // NOTE: |plugin_id| must be sanitized ASCII string that doesn't + // include *any* dangerous character like '/'. + void OpenPrivateFileSystem( + const GURL& origin_url, + FileSystemType type, + const std::string& filesystem_id, + const std::string& plugin_id, + OpenFileSystemMode mode, + const StatusCallback& callback); + + // FileSystemBackend overrides. + virtual bool CanHandleType(FileSystemType type) const OVERRIDE; + virtual void Initialize(FileSystemContext* context) OVERRIDE; + virtual void ResolveURL(const FileSystemURL& url, + OpenFileSystemMode mode, + const OpenFileSystemCallback& callback) OVERRIDE; + virtual AsyncFileUtil* GetAsyncFileUtil(FileSystemType type) OVERRIDE; + virtual WatcherManager* GetWatcherManager(FileSystemType type) OVERRIDE; + virtual CopyOrMoveFileValidatorFactory* GetCopyOrMoveFileValidatorFactory( + FileSystemType type, + base::File::Error* error_code) OVERRIDE; + virtual FileSystemOperation* CreateFileSystemOperation( + const FileSystemURL& url, + FileSystemContext* context, + base::File::Error* error_code) const OVERRIDE; + virtual bool SupportsStreaming(const FileSystemURL& url) const OVERRIDE; + virtual bool HasInplaceCopyImplementation( + storage::FileSystemType type) const OVERRIDE; + virtual scoped_ptr<storage::FileStreamReader> CreateFileStreamReader( + const FileSystemURL& url, + int64 offset, + const base::Time& expected_modification_time, + FileSystemContext* context) const OVERRIDE; + virtual scoped_ptr<FileStreamWriter> CreateFileStreamWriter( + const FileSystemURL& url, + int64 offset, + FileSystemContext* context) const OVERRIDE; + virtual FileSystemQuotaUtil* GetQuotaUtil() OVERRIDE; + + // FileSystemQuotaUtil overrides. + virtual base::File::Error DeleteOriginDataOnFileTaskRunner( + FileSystemContext* context, + storage::QuotaManagerProxy* proxy, + const GURL& origin_url, + FileSystemType type) OVERRIDE; + virtual void GetOriginsForTypeOnFileTaskRunner( + FileSystemType type, + std::set<GURL>* origins) OVERRIDE; + virtual void GetOriginsForHostOnFileTaskRunner( + FileSystemType type, + const std::string& host, + std::set<GURL>* origins) OVERRIDE; + virtual int64 GetOriginUsageOnFileTaskRunner( + FileSystemContext* context, + const GURL& origin_url, + FileSystemType type) OVERRIDE; + virtual scoped_refptr<QuotaReservation> + CreateQuotaReservationOnFileTaskRunner( + const GURL& origin_url, + FileSystemType type) OVERRIDE; + virtual void AddFileUpdateObserver( + FileSystemType type, + FileUpdateObserver* observer, + base::SequencedTaskRunner* task_runner) OVERRIDE; + virtual void AddFileChangeObserver( + FileSystemType type, + FileChangeObserver* observer, + base::SequencedTaskRunner* task_runner) OVERRIDE; + virtual void AddFileAccessObserver( + FileSystemType type, + FileAccessObserver* observer, + base::SequencedTaskRunner* task_runner) OVERRIDE; + virtual const UpdateObserverList* GetUpdateObservers( + FileSystemType type) const OVERRIDE; + virtual const ChangeObserverList* GetChangeObservers( + FileSystemType type) const OVERRIDE; + virtual const AccessObserverList* GetAccessObservers( + FileSystemType type) const OVERRIDE; + + private: + friend class content::PluginPrivateFileSystemBackendTest; + + ObfuscatedFileUtil* obfuscated_file_util(); + const base::FilePath& base_path() const { return base_path_; } + + scoped_refptr<base::SequencedTaskRunner> file_task_runner_; + const FileSystemOptions file_system_options_; + const base::FilePath base_path_; + scoped_ptr<AsyncFileUtil> file_util_; + FileSystemIDToPluginMap* plugin_map_; // Owned by file_util_. + base::WeakPtrFactory<PluginPrivateFileSystemBackend> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(PluginPrivateFileSystemBackend); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_PLUGIN_PRIVATE_FILE_SYSTEM_BACKEND_H_ diff --git a/webkit/browser/fileapi/quota/open_file_handle.cc b/storage/browser/fileapi/quota/open_file_handle.cc index b8c0b29..8842438 100644 --- a/webkit/browser/fileapi/quota/open_file_handle.cc +++ b/storage/browser/fileapi/quota/open_file_handle.cc @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/quota/open_file_handle.h" +#include "storage/browser/fileapi/quota/open_file_handle.h" -#include "webkit/browser/fileapi/quota/open_file_handle_context.h" -#include "webkit/browser/fileapi/quota/quota_reservation.h" +#include "storage/browser/fileapi/quota/open_file_handle_context.h" +#include "storage/browser/fileapi/quota/quota_reservation.h" namespace storage { diff --git a/storage/browser/fileapi/quota/open_file_handle.h b/storage/browser/fileapi/quota/open_file_handle.h new file mode 100644 index 0000000..8954b1d --- /dev/null +++ b/storage/browser/fileapi/quota/open_file_handle.h @@ -0,0 +1,70 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_QUOTA_OPEN_FILE_HANDLE_H_ +#define STORAGE_BROWSER_FILEAPI_QUOTA_OPEN_FILE_HANDLE_H_ + +#include "base/basictypes.h" +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class FilePath; +} + +namespace storage { + +class QuotaReservation; +class OpenFileHandleContext; +class QuotaReservationBuffer; + +// Represents an open file like a file descriptor. +// This should be alive while a consumer keeps a file opened and should be +// deleted when the plugin closes the file. +class STORAGE_EXPORT OpenFileHandle { + public: + ~OpenFileHandle(); + + // Updates cached file size and consumes quota for that. + // Both this and AddAppendModeWriteAmount should be called for each modified + // file before calling QuotaReservation::RefreshQuota and before closing the + // file. + void UpdateMaxWrittenOffset(int64 offset); + + // Notifies that |amount| of data is written to the file in append mode, and + // consumes quota for that. + // Both this and UpdateMaxWrittenOffset should be called for each modified + // file before calling QuotaReservation::RefreshQuota and before closing the + // file. + void AddAppendModeWriteAmount(int64 amount); + + // Returns the estimated file size for the quota consumption calculation. + // The client must consume its reserved quota when it writes data to the file + // beyond the estimated file size. + // The estimated file size is greater than or equal to actual file size after + // all clients report their file usage, and is monotonically increasing over + // OpenFileHandle object life cycle, so that client may cache the value. + int64 GetEstimatedFileSize() const; + + int64 GetMaxWrittenOffset() const; + const base::FilePath& platform_path() const; + + private: + friend class QuotaReservationBuffer; + + OpenFileHandle(QuotaReservation* reservation, + OpenFileHandleContext* context); + + scoped_refptr<QuotaReservation> reservation_; + scoped_refptr<OpenFileHandleContext> context_; + + base::SequenceChecker sequence_checker_; + + DISALLOW_COPY_AND_ASSIGN(OpenFileHandle); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_QUOTA_OPEN_FILE_HANDLE_H_ diff --git a/webkit/browser/fileapi/quota/open_file_handle_context.cc b/storage/browser/fileapi/quota/open_file_handle_context.cc index afc338e..816a777 100644 --- a/webkit/browser/fileapi/quota/open_file_handle_context.cc +++ b/storage/browser/fileapi/quota/open_file_handle_context.cc @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/quota/open_file_handle_context.h" +#include "storage/browser/fileapi/quota/open_file_handle_context.h" -#include "base/files/file_util.h" -#include "webkit/browser/fileapi/quota/quota_reservation_buffer.h" +#include "base/file_util.h" +#include "storage/browser/fileapi/quota/quota_reservation_buffer.h" namespace storage { diff --git a/storage/browser/fileapi/quota/open_file_handle_context.h b/storage/browser/fileapi/quota/open_file_handle_context.h new file mode 100644 index 0000000..cb37064 --- /dev/null +++ b/storage/browser/fileapi/quota/open_file_handle_context.h @@ -0,0 +1,61 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_OPEN_FILE_HANDLE_CONTEXT_H_ +#define STORAGE_BROWSER_FILEAPI_OPEN_FILE_HANDLE_CONTEXT_H_ + +#include <map> + +#include "base/basictypes.h" +#include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/fileapi/file_system_types.h" +#include "url/gurl.h" + +namespace storage { + +class QuotaReservationBuffer; + +// This class represents a underlying file of a managed FileSystem file. +// The instance keeps alive while at least one consumer keeps an open file +// handle. +// This class is usually manipulated only via OpenFileHandle. +class OpenFileHandleContext : public base::RefCounted<OpenFileHandleContext> { + public: + OpenFileHandleContext(const base::FilePath& platform_path, + QuotaReservationBuffer* reservation_buffer); + + // Updates the max written offset and returns the amount of growth. + int64 UpdateMaxWrittenOffset(int64 offset); + + void AddAppendModeWriteAmount(int64 amount); + + const base::FilePath& platform_path() const { + return platform_path_; + } + + int64 GetEstimatedFileSize() const; + int64 GetMaxWrittenOffset() const; + + private: + friend class base::RefCounted<OpenFileHandleContext>; + virtual ~OpenFileHandleContext(); + + int64 initial_file_size_; + int64 maximum_written_offset_; + int64 append_mode_write_amount_; + base::FilePath platform_path_; + + scoped_refptr<QuotaReservationBuffer> reservation_buffer_; + + base::SequenceChecker sequence_checker_; + + DISALLOW_COPY_AND_ASSIGN(OpenFileHandleContext); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_OPEN_FILE_HANDLE_CONTEXT_H_ diff --git a/webkit/browser/fileapi/quota/quota_backend_impl.cc b/storage/browser/fileapi/quota/quota_backend_impl.cc index deb100e..6969f7f 100644 --- a/webkit/browser/fileapi/quota/quota_backend_impl.cc +++ b/storage/browser/fileapi/quota/quota_backend_impl.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/quota/quota_backend_impl.h" +#include "storage/browser/fileapi/quota/quota_backend_impl.h" #include <string> @@ -11,10 +11,10 @@ #include "base/logging.h" #include "base/numerics/safe_conversions.h" #include "base/sequenced_task_runner.h" -#include "webkit/browser/fileapi/file_system_usage_cache.h" -#include "webkit/browser/quota/quota_client.h" -#include "webkit/browser/quota/quota_manager_proxy.h" -#include "webkit/common/fileapi/file_system_util.h" +#include "storage/browser/fileapi/file_system_usage_cache.h" +#include "storage/browser/quota/quota_client.h" +#include "storage/browser/quota/quota_manager_proxy.h" +#include "storage/common/fileapi/file_system_util.h" namespace storage { diff --git a/storage/browser/fileapi/quota/quota_backend_impl.h b/storage/browser/fileapi/quota/quota_backend_impl.h new file mode 100644 index 0000000..ed15157 --- /dev/null +++ b/storage/browser/fileapi/quota/quota_backend_impl.h @@ -0,0 +1,106 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_QUOTA_QUOTA_BACKEND_IMPL_H_ +#define STORAGE_BROWSER_FILEAPI_QUOTA_QUOTA_BACKEND_IMPL_H_ + +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "storage/browser/fileapi/quota/quota_reservation_manager.h" +#include "storage/browser/fileapi/sandbox_file_system_backend_delegate.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/quota/quota_status_code.h" + +namespace base { +class SequencedTaskRunner; +} + +namespace content { +class QuotaBackendImplTest; +} + +namespace storage { +class QuotaManagerProxy; +} + +namespace storage { + +class FileSystemUsageCache; +class ObfuscatedFileUtil; + +// An instance of this class is owned by QuotaReservationManager. +class STORAGE_EXPORT QuotaBackendImpl + : public QuotaReservationManager::QuotaBackend { + public: + typedef QuotaReservationManager::ReserveQuotaCallback + ReserveQuotaCallback; + + QuotaBackendImpl(base::SequencedTaskRunner* file_task_runner, + ObfuscatedFileUtil* obfuscated_file_util, + FileSystemUsageCache* file_system_usage_cache, + storage::QuotaManagerProxy* quota_manager_proxy); + virtual ~QuotaBackendImpl(); + + // QuotaReservationManager::QuotaBackend overrides. + virtual void ReserveQuota( + const GURL& origin, + FileSystemType type, + int64 delta, + const ReserveQuotaCallback& callback) OVERRIDE; + virtual void ReleaseReservedQuota( + const GURL& origin, + FileSystemType type, + int64 size) OVERRIDE; + virtual void CommitQuotaUsage( + const GURL& origin, + FileSystemType type, + int64 delta) OVERRIDE; + virtual void IncrementDirtyCount( + const GURL& origin, + FileSystemType type) OVERRIDE; + virtual void DecrementDirtyCount( + const GURL& origin, + FileSystemType type) OVERRIDE; + + private: + friend class content::QuotaBackendImplTest; + + struct QuotaReservationInfo { + QuotaReservationInfo(const GURL& origin, FileSystemType type, int64 delta); + ~QuotaReservationInfo(); + + GURL origin; + FileSystemType type; + int64 delta; + }; + + void DidGetUsageAndQuotaForReserveQuota(const QuotaReservationInfo& info, + const ReserveQuotaCallback& callback, + storage::QuotaStatusCode status, + int64 usage, + int64 quota); + + void ReserveQuotaInternal( + const QuotaReservationInfo& info); + base::File::Error GetUsageCachePath( + const GURL& origin, + FileSystemType type, + base::FilePath* usage_file_path); + + scoped_refptr<base::SequencedTaskRunner> file_task_runner_; + + // Owned by SandboxFileSystemBackendDelegate. + ObfuscatedFileUtil* obfuscated_file_util_; + FileSystemUsageCache* file_system_usage_cache_; + + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy_; + + base::WeakPtrFactory<QuotaBackendImpl> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(QuotaBackendImpl); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_QUOTA_QUOTA_BACKEND_IMPL_H_ diff --git a/webkit/browser/fileapi/quota/quota_reservation.cc b/storage/browser/fileapi/quota/quota_reservation.cc index 5139d0b..fff7f16 100644 --- a/webkit/browser/fileapi/quota/quota_reservation.cc +++ b/storage/browser/fileapi/quota/quota_reservation.cc @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/quota/quota_reservation.h" +#include "storage/browser/fileapi/quota/quota_reservation.h" #include "base/bind.h" -#include "webkit/browser/fileapi/quota/open_file_handle.h" -#include "webkit/browser/fileapi/quota/quota_reservation_buffer.h" +#include "storage/browser/fileapi/quota/open_file_handle.h" +#include "storage/browser/fileapi/quota/quota_reservation_buffer.h" namespace storage { diff --git a/storage/browser/fileapi/quota/quota_reservation.h b/storage/browser/fileapi/quota/quota_reservation.h new file mode 100644 index 0000000..be35b9e --- /dev/null +++ b/storage/browser/fileapi/quota/quota_reservation.h @@ -0,0 +1,95 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_H_ +#define STORAGE_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_H_ + +#include "base/basictypes.h" +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "storage/browser/fileapi/quota/quota_reservation_manager.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/fileapi/file_system_types.h" + +class GURL; + +namespace storage { + +class QuotaReservationBuffer; +class OpenFileHandle; + +// Represents a unit of quota reservation. +class STORAGE_EXPORT QuotaReservation + : public base::RefCounted<QuotaReservation> { + public: + typedef base::Callback<void(base::File::Error error)> StatusCallback; + + // Reclaims unused quota and reserves another |size| of quota. So that the + // resulting new |remaining_quota_| will be same as |size| as far as available + // space is enough. |remaining_quota_| may be less than |size| if there is + // not enough space available. + // Invokes |callback| upon completion. + void RefreshReservation(int64 size, const StatusCallback& callback); + + // Associates |platform_path| to the QuotaReservation instance. + // Returns an OpenFileHandle instance that represents a quota managed file. + scoped_ptr<OpenFileHandle> GetOpenFileHandle( + const base::FilePath& platform_path); + + // Should be called when the associated client is crashed. + // This implies the client can no longer report its consumption of the + // reserved quota. + // QuotaReservation puts all remaining quota to the QuotaReservationBuffer, so + // that the remaining quota will be reclaimed after all open files associated + // to the origin and type. + void OnClientCrash(); + + // Consumes |size| of reserved quota for a associated file. + // Consumed quota is sent to associated QuotaReservationBuffer for staging. + void ConsumeReservation(int64 size); + + // Returns amount of unused reserved quota. + int64 remaining_quota() const { return remaining_quota_; } + + QuotaReservationManager* reservation_manager(); + const GURL& origin() const; + FileSystemType type() const; + + private: + friend class QuotaReservationBuffer; + + // Use QuotaReservationManager as the entry point. + explicit QuotaReservation(QuotaReservationBuffer* reservation_buffer); + + friend class base::RefCounted<QuotaReservation>; + virtual ~QuotaReservation(); + + static bool AdaptDidUpdateReservedQuota( + const base::WeakPtr<QuotaReservation>& reservation, + int64 previous_size, + const StatusCallback& callback, + base::File::Error error, + int64 delta); + bool DidUpdateReservedQuota(int64 previous_size, + const StatusCallback& callback, + base::File::Error error, + int64 delta); + + bool client_crashed_; + bool running_refresh_request_; + int64 remaining_quota_; + + scoped_refptr<QuotaReservationBuffer> reservation_buffer_; + + base::SequenceChecker sequence_checker_; + base::WeakPtrFactory<QuotaReservation> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(QuotaReservation); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_H_ diff --git a/webkit/browser/fileapi/quota/quota_reservation_buffer.cc b/storage/browser/fileapi/quota/quota_reservation_buffer.cc index cfa567f..faa70eb 100644 --- a/webkit/browser/fileapi/quota/quota_reservation_buffer.cc +++ b/storage/browser/fileapi/quota/quota_reservation_buffer.cc @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/quota/quota_reservation_buffer.h" +#include "storage/browser/fileapi/quota/quota_reservation_buffer.h" #include "base/bind.h" -#include "webkit/browser/fileapi/quota/open_file_handle.h" -#include "webkit/browser/fileapi/quota/open_file_handle_context.h" -#include "webkit/browser/fileapi/quota/quota_reservation.h" +#include "storage/browser/fileapi/quota/open_file_handle.h" +#include "storage/browser/fileapi/quota/open_file_handle_context.h" +#include "storage/browser/fileapi/quota/quota_reservation.h" namespace storage { diff --git a/storage/browser/fileapi/quota/quota_reservation_buffer.h b/storage/browser/fileapi/quota/quota_reservation_buffer.h new file mode 100644 index 0000000..0e893b6 --- /dev/null +++ b/storage/browser/fileapi/quota/quota_reservation_buffer.h @@ -0,0 +1,87 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_BUFFER_H_ +#define STORAGE_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_BUFFER_H_ + +#include <map> + +#include "base/basictypes.h" +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/fileapi/file_system_types.h" +#include "url/gurl.h" + +namespace storage { + +class QuotaReservation; +class OpenFileHandle; +class OpenFileHandleContext; +class QuotaReservationManager; + +// QuotaReservationBuffer manages QuotaReservation instances. All consumed +// quota and leaked quota by associated QuotaReservation will be staged in +// QuotaReservationBuffer, and will be committed on a modified file is closed. +// The instance keeps alive while any associated QuotaReservation or +// OpenFileHandle alive. +// This class is usually manipulated only via OpenFileHandle and +// QuotaReservation. +class QuotaReservationBuffer : public base::RefCounted<QuotaReservationBuffer> { + public: + QuotaReservationBuffer( + base::WeakPtr<QuotaReservationManager> reservation_manager, + const GURL& origin, + FileSystemType type); + + scoped_refptr<QuotaReservation> CreateReservation(); + scoped_ptr<OpenFileHandle> GetOpenFileHandle( + QuotaReservation* reservation, + const base::FilePath& platform_path); + void CommitFileGrowth(int64 quota_consumption, int64 usage_delta); + void DetachOpenFileHandleContext(OpenFileHandleContext* context); + void PutReservationToBuffer(int64 size); + + QuotaReservationManager* reservation_manager() { + return reservation_manager_.get(); + } + + const GURL& origin() const { return origin_; } + FileSystemType type() const { return type_; } + + private: + friend class base::RefCounted<QuotaReservationBuffer>; + virtual ~QuotaReservationBuffer(); + + static bool DecrementDirtyCount( + base::WeakPtr<QuotaReservationManager> reservation_manager, + const GURL& origin, + FileSystemType type, + base::File::Error error, + int64 delta); + + typedef std::map<base::FilePath, OpenFileHandleContext*> + OpenFileHandleContextByPath; + + // Not owned. The destructor of OpenFileHandler should erase itself from + // |open_files_|. + OpenFileHandleContextByPath open_files_; + + base::WeakPtr<QuotaReservationManager> reservation_manager_; + + GURL origin_; + storage::FileSystemType type_; + + int64 reserved_quota_; + + base::SequenceChecker sequence_checker_; + + DISALLOW_COPY_AND_ASSIGN(QuotaReservationBuffer); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_BUFFER_H_ diff --git a/webkit/browser/fileapi/quota/quota_reservation_manager.cc b/storage/browser/fileapi/quota/quota_reservation_manager.cc index 6ab2c26..b5ee5d8 100644 --- a/webkit/browser/fileapi/quota/quota_reservation_manager.cc +++ b/storage/browser/fileapi/quota/quota_reservation_manager.cc @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/quota/quota_reservation_manager.h" +#include "storage/browser/fileapi/quota/quota_reservation_manager.h" -#include "webkit/browser/fileapi/quota/quota_reservation.h" -#include "webkit/browser/fileapi/quota/quota_reservation_buffer.h" +#include "storage/browser/fileapi/quota/quota_reservation.h" +#include "storage/browser/fileapi/quota/quota_reservation_buffer.h" namespace storage { diff --git a/storage/browser/fileapi/quota/quota_reservation_manager.h b/storage/browser/fileapi/quota/quota_reservation_manager.h new file mode 100644 index 0000000..ec04245 --- /dev/null +++ b/storage/browser/fileapi/quota/quota_reservation_manager.h @@ -0,0 +1,127 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_MANAGER_H_ +#define STORAGE_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_MANAGER_H_ + +#include <map> +#include <utility> + +#include "base/basictypes.h" +#include "base/callback_forward.h" +#include "base/files/file.h" +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/fileapi/file_system_types.h" +#include "url/gurl.h" + +namespace content { +class QuotaReservationManagerTest; +} + +namespace storage { + +class QuotaReservation; +class QuotaReservationBuffer; +class OpenFileHandle; +class OpenFileHandleContext; + +class STORAGE_EXPORT QuotaReservationManager { + public: + // Callback for ReserveQuota. When this callback returns false, ReserveQuota + // operation should be reverted. + typedef base::Callback<bool(base::File::Error error, int64 delta)> + ReserveQuotaCallback; + + // An abstraction of backing quota system. + class STORAGE_EXPORT QuotaBackend { + public: + QuotaBackend() {} + virtual ~QuotaBackend() {} + + // Reserves or reclaims |delta| of quota for |origin| and |type| pair. + // Reserved quota should be counted as usage, but it should be on-memory + // and be cleared by a browser restart. + // Invokes |callback| upon completion with an error code. + // |callback| should return false if it can't accept the reservation, in + // that case, the backend should roll back the reservation. + virtual void ReserveQuota(const GURL& origin, + FileSystemType type, + int64 delta, + const ReserveQuotaCallback& callback) = 0; + + // Reclaims |size| of quota for |origin| and |type|. + virtual void ReleaseReservedQuota(const GURL& origin, + FileSystemType type, + int64 size) = 0; + + // Updates disk usage of |origin| and |type|. + // Invokes |callback| upon completion with an error code. + virtual void CommitQuotaUsage(const GURL& origin, + FileSystemType type, + int64 delta) = 0; + + virtual void IncrementDirtyCount(const GURL& origin, + FileSystemType type) = 0; + virtual void DecrementDirtyCount(const GURL& origin, + FileSystemType type) = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(QuotaBackend); + }; + + explicit QuotaReservationManager(scoped_ptr<QuotaBackend> backend); + ~QuotaReservationManager(); + + // The entry point of the quota reservation. Creates new reservation object + // for |origin| and |type|. + scoped_refptr<QuotaReservation> CreateReservation( + const GURL& origin, + FileSystemType type); + + private: + typedef std::map<std::pair<GURL, FileSystemType>, QuotaReservationBuffer*> + ReservationBufferByOriginAndType; + + friend class QuotaReservation; + friend class QuotaReservationBuffer; + friend class content::QuotaReservationManagerTest; + + void ReserveQuota(const GURL& origin, + FileSystemType type, + int64 delta, + const ReserveQuotaCallback& callback); + + void ReleaseReservedQuota(const GURL& origin, + FileSystemType type, + int64 size); + + void CommitQuotaUsage(const GURL& origin, + FileSystemType type, + int64 delta); + + void IncrementDirtyCount(const GURL& origin, FileSystemType type); + void DecrementDirtyCount(const GURL& origin, FileSystemType type); + + scoped_refptr<QuotaReservationBuffer> GetReservationBuffer( + const GURL& origin, + FileSystemType type); + void ReleaseReservationBuffer(QuotaReservationBuffer* reservation_pool); + + scoped_ptr<QuotaBackend> backend_; + + // Not owned. The destructor of ReservationBuffer should erase itself from + // |reservation_buffers_| by calling ReleaseReservationBuffer. + ReservationBufferByOriginAndType reservation_buffers_; + + base::SequenceChecker sequence_checker_; + base::WeakPtrFactory<QuotaReservationManager> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(QuotaReservationManager); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_MANAGER_H_ diff --git a/webkit/browser/fileapi/recursive_operation_delegate.cc b/storage/browser/fileapi/recursive_operation_delegate.cc index 7836b32..e9d1466 100644 --- a/webkit/browser/fileapi/recursive_operation_delegate.cc +++ b/storage/browser/fileapi/recursive_operation_delegate.cc @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/recursive_operation_delegate.h" +#include "storage/browser/fileapi/recursive_operation_delegate.h" #include "base/bind.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation_runner.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation_runner.h" namespace storage { diff --git a/storage/browser/fileapi/recursive_operation_delegate.h b/storage/browser/fileapi/recursive_operation_delegate.h new file mode 100644 index 0000000..f7f07c2 --- /dev/null +++ b/storage/browser/fileapi/recursive_operation_delegate.h @@ -0,0 +1,152 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_RECURSIVE_OPERATION_DELEGATE_H_ +#define STORAGE_BROWSER_FILEAPI_RECURSIVE_OPERATION_DELEGATE_H_ + +#include <queue> +#include <stack> + +#include "base/basictypes.h" +#include "base/callback.h" +#include "base/memory/weak_ptr.h" +#include "storage/browser/fileapi/file_system_operation.h" +#include "storage/browser/fileapi/file_system_url.h" + +namespace storage { + +class FileSystemContext; +class FileSystemOperationRunner; + +// A base class for recursive operation delegates. +// +// In short, each subclass should override ProcessFile and ProcessDirectory +// to process a directory or a file. To start the recursive operation it +// should also call StartRecursiveOperation. +class STORAGE_EXPORT RecursiveOperationDelegate + : public base::SupportsWeakPtr<RecursiveOperationDelegate> { + public: + typedef FileSystemOperation::StatusCallback StatusCallback; + typedef FileSystemOperation::FileEntryList FileEntryList; + + virtual ~RecursiveOperationDelegate(); + + // This is called when the consumer of this instance starts a non-recursive + // operation. + virtual void Run() = 0; + + // This is called when the consumer of this instance starts a recursive + // operation. + virtual void RunRecursively() = 0; + + // This is called each time a file is found while recursively + // performing an operation. + virtual void ProcessFile(const FileSystemURL& url, + const StatusCallback& callback) = 0; + + // This is called each time a directory is found while recursively + // performing an operation. + virtual void ProcessDirectory(const FileSystemURL& url, + const StatusCallback& callback) = 0; + + + // This is called each time after files and subdirectories for a + // directory is processed while recursively performing an operation. + virtual void PostProcessDirectory(const FileSystemURL& url, + const StatusCallback& callback) = 0; + + // Cancels the currently running operation. + void Cancel(); + + protected: + explicit RecursiveOperationDelegate(FileSystemContext* file_system_context); + + // Starts to process files/directories recursively from the given |root|. + // This will call ProcessFile and ProcessDirectory on each file or directory. + // + // First, this tries to call ProcessFile with |root| regardless whether it is + // actually a file or a directory. If it is a directory, ProcessFile should + // return File::FILE_NOT_A_FILE. + // + // For each directory, the recursive operation works as follows: + // ProcessDirectory is called first for the directory. + // Then the directory contents are read (to obtain its sub directories and + // files in it). + // ProcessFile is called for found files. This may run in parallel. + // The same step is recursively applied to each subdirectory. + // After all files and subdirectories in a directory are processed, + // PostProcessDirectory is called for the directory. + // Here is an example; + // a_dir/ -+- b1_dir/ -+- c1_dir/ -+- d1_file + // | | | + // | +- c2_file +- d2_file + // | + // +- b2_dir/ --- e_dir/ + // | + // +- b3_file + // | + // +- b4_file + // Then traverse order is: + // ProcessFile(a_dir) (This should return File::FILE_NOT_A_FILE). + // ProcessDirectory(a_dir). + // ProcessFile(b3_file), ProcessFile(b4_file). (in parallel). + // ProcessDirectory(b1_dir). + // ProcessFile(c2_file) + // ProcessDirectory(c1_dir). + // ProcessFile(d1_file), ProcessFile(d2_file). (in parallel). + // PostProcessDirectory(c1_dir) + // PostProcessDirectory(b1_dir). + // ProcessDirectory(b2_dir) + // ProcessDirectory(e_dir) + // PostProcessDirectory(e_dir) + // PostProcessDirectory(b2_dir) + // PostProcessDirectory(a_dir) + // + // |callback| is fired with base::File::FILE_OK when every file/directory + // under |root| is processed, or fired earlier when any suboperation fails. + void StartRecursiveOperation(const FileSystemURL& root, + const StatusCallback& callback); + + FileSystemContext* file_system_context() { return file_system_context_; } + const FileSystemContext* file_system_context() const { + return file_system_context_; + } + + FileSystemOperationRunner* operation_runner(); + + // Called when Cancel() is called. This is a hook to do something more + // in a derived class. By default, do nothing. + virtual void OnCancel(); + + private: + void DidTryProcessFile(const FileSystemURL& root, + base::File::Error error); + void ProcessNextDirectory(); + void DidProcessDirectory(base::File::Error error); + void DidReadDirectory(const FileSystemURL& parent, + base::File::Error error, + const FileEntryList& entries, + bool has_more); + void ProcessPendingFiles(); + void DidProcessFile(base::File::Error error); + void ProcessSubDirectory(); + void DidPostProcessDirectory(base::File::Error error); + + // Called when all recursive operation is done (or an error occurs). + void Done(base::File::Error error); + + FileSystemContext* file_system_context_; + StatusCallback callback_; + std::stack<FileSystemURL> pending_directories_; + std::stack<std::queue<FileSystemURL> > pending_directory_stack_; + std::queue<FileSystemURL> pending_files_; + int inflight_operations_; + bool canceled_; + + DISALLOW_COPY_AND_ASSIGN(RecursiveOperationDelegate); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_RECURSIVE_OPERATION_DELEGATE_H_ diff --git a/webkit/browser/fileapi/remove_operation_delegate.cc b/storage/browser/fileapi/remove_operation_delegate.cc index 8e645cd..eb28587 100644 --- a/webkit/browser/fileapi/remove_operation_delegate.cc +++ b/storage/browser/fileapi/remove_operation_delegate.cc @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/remove_operation_delegate.h" +#include "storage/browser/fileapi/remove_operation_delegate.h" #include "base/bind.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation_runner.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation_runner.h" namespace storage { diff --git a/storage/browser/fileapi/remove_operation_delegate.h b/storage/browser/fileapi/remove_operation_delegate.h new file mode 100644 index 0000000..436a641 --- /dev/null +++ b/storage/browser/fileapi/remove_operation_delegate.h @@ -0,0 +1,46 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_REMOVE_OPERATION_DELEGATE_H_ +#define STORAGE_BROWSER_FILEAPI_REMOVE_OPERATION_DELEGATE_H_ + +#include <stack> + +#include "storage/browser/fileapi/recursive_operation_delegate.h" + +namespace storage { + +class RemoveOperationDelegate : public RecursiveOperationDelegate { + public: + RemoveOperationDelegate(FileSystemContext* file_system_context, + const FileSystemURL& url, + const StatusCallback& callback); + virtual ~RemoveOperationDelegate(); + + // RecursiveOperationDelegate overrides: + virtual void Run() OVERRIDE; + virtual void RunRecursively() OVERRIDE; + virtual void ProcessFile(const FileSystemURL& url, + const StatusCallback& callback) OVERRIDE; + virtual void ProcessDirectory(const FileSystemURL& url, + const StatusCallback& callback) OVERRIDE; + virtual void PostProcessDirectory(const FileSystemURL& url, + const StatusCallback& callback) OVERRIDE; + + private: + void DidTryRemoveFile(base::File::Error error); + void DidTryRemoveDirectory(base::File::Error remove_file_error, + base::File::Error remove_directory_error); + void DidRemoveFile(const StatusCallback& callback, + base::File::Error error); + + FileSystemURL url_; + StatusCallback callback_; + base::WeakPtrFactory<RemoveOperationDelegate> weak_factory_; + DISALLOW_COPY_AND_ASSIGN(RemoveOperationDelegate); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_REMOVE_OPERATION_DELEGATE_H_ diff --git a/webkit/browser/fileapi/sandbox_directory_database.cc b/storage/browser/fileapi/sandbox_directory_database.cc index 600562e..e34d324 100644 --- a/webkit/browser/fileapi/sandbox_directory_database.cc +++ b/storage/browser/fileapi/sandbox_directory_database.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/sandbox_directory_database.h" +#include "storage/browser/fileapi/sandbox_directory_database.h" #include <math.h> #include <algorithm> @@ -16,10 +16,10 @@ #include "base/pickle.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" +#include "storage/browser/fileapi/file_system_usage_cache.h" +#include "storage/common/fileapi/file_system_util.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" #include "third_party/leveldatabase/src/include/leveldb/write_batch.h" -#include "webkit/browser/fileapi/file_system_usage_cache.h" -#include "webkit/common/fileapi/file_system_util.h" namespace { diff --git a/storage/browser/fileapi/sandbox_directory_database.h b/storage/browser/fileapi/sandbox_directory_database.h new file mode 100644 index 0000000..a966811 --- /dev/null +++ b/storage/browser/fileapi/sandbox_directory_database.h @@ -0,0 +1,135 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_SANDBOX_DIRECTORY_DATABASE_H_ +#define STORAGE_BROWSER_FILEAPI_SANDBOX_DIRECTORY_DATABASE_H_ + +#include <string> +#include <vector> + +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/memory/scoped_ptr.h" +#include "base/time/time.h" +#include "storage/browser/storage_browser_export.h" + +namespace content { +class SandboxDirectoryDatabaseTest; +} + +namespace tracked_objects { +class Location; +} + +namespace leveldb { +class DB; +class Env; +class Status; +class WriteBatch; +} + +namespace storage { + +// This class WILL NOT protect you against producing directory loops, giving an +// empty directory a backing data file, giving two files the same backing file, +// or pointing to a nonexistent backing file. It does no file IO other than +// that involved with talking to its underlying database. It does not create or +// in any way touch real files; it only creates path entries in its database. + +// TODO(ericu): Safe mode, which does more checks such as the above on debug +// builds. +// TODO(ericu): Add a method that will give a unique filename for a data file. +class STORAGE_EXPORT_PRIVATE SandboxDirectoryDatabase { + public: + typedef int64 FileId; + + struct STORAGE_EXPORT_PRIVATE FileInfo { + FileInfo(); + ~FileInfo(); + + bool is_directory() const { + return data_path.empty(); + } + + FileId parent_id; + base::FilePath data_path; + base::FilePath::StringType name; + // This modification time is valid only for directories, not files, as + // FileWriter will get the files out of sync. + // For files, look at the modification time of the underlying data_path. + base::Time modification_time; + }; + + SandboxDirectoryDatabase( + const base::FilePath& filesystem_data_directory, + leveldb::Env* env_override); + ~SandboxDirectoryDatabase(); + + bool GetChildWithName( + FileId parent_id, + const base::FilePath::StringType& name, + FileId* child_id); + bool GetFileWithPath(const base::FilePath& path, FileId* file_id); + // ListChildren will succeed, returning 0 children, if parent_id doesn't + // exist. + bool ListChildren(FileId parent_id, std::vector<FileId>* children); + bool GetFileInfo(FileId file_id, FileInfo* info); + base::File::Error AddFileInfo(const FileInfo& info, FileId* file_id); + bool RemoveFileInfo(FileId file_id); + // This does a full update of the FileInfo, and is what you'd use for moves + // and renames. If you just want to update the modification_time, use + // UpdateModificationTime. + bool UpdateFileInfo(FileId file_id, const FileInfo& info); + bool UpdateModificationTime( + FileId file_id, const base::Time& modification_time); + // This is used for an overwriting move of a file [not a directory] on top of + // another file [also not a directory]; we need to alter two files' info in a + // single transaction to avoid weird backing file references in the event of a + // partial failure. + bool OverwritingMoveFile(FileId src_file_id, FileId dest_file_id); + + // This produces the series 0, 1, 2..., starting at 0 when the underlying + // filesystem is first created, and maintaining state across + // creation/destruction of SandboxDirectoryDatabase objects. + bool GetNextInteger(int64* next); + + bool IsDirectory(FileId file_id); + + // Returns true if the database looks consistent with local filesystem. + bool IsFileSystemConsistent(); + + static bool DestroyDatabase(const base::FilePath& path, + leveldb::Env* env_override); + + private: + enum RecoveryOption { + DELETE_ON_CORRUPTION, + REPAIR_ON_CORRUPTION, + FAIL_ON_CORRUPTION, + }; + + friend class content::SandboxDirectoryDatabaseTest; + friend class ObfuscatedFileUtil; + + bool Init(RecoveryOption recovery_option); + bool RepairDatabase(const std::string& db_path); + void ReportInitStatus(const leveldb::Status& status); + bool StoreDefaultValues(); + bool GetLastFileId(FileId* file_id); + bool AddFileInfoHelper( + const FileInfo& info, FileId file_id, leveldb::WriteBatch* batch); + bool RemoveFileInfoHelper(FileId file_id, leveldb::WriteBatch* batch); + void HandleError(const tracked_objects::Location& from_here, + const leveldb::Status& status); + + const base::FilePath filesystem_data_directory_; + leveldb::Env* env_override_; + scoped_ptr<leveldb::DB> db_; + base::Time last_reported_time_; + DISALLOW_COPY_AND_ASSIGN(SandboxDirectoryDatabase); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_SANDBOX_DIRECTORY_DATABASE_H_ diff --git a/webkit/browser/fileapi/sandbox_file_stream_writer.cc b/storage/browser/fileapi/sandbox_file_stream_writer.cc index 8fd39bc..d87c66d 100644 --- a/webkit/browser/fileapi/sandbox_file_stream_writer.cc +++ b/storage/browser/fileapi/sandbox_file_stream_writer.cc @@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/sandbox_file_stream_writer.h" +#include "storage/browser/fileapi/sandbox_file_stream_writer.h" #include "base/files/file_util_proxy.h" #include "base/sequenced_task_runner.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" -#include "webkit/browser/blob/file_stream_reader.h" -#include "webkit/browser/fileapi/file_observers.h" -#include "webkit/browser/fileapi/file_stream_writer.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation_runner.h" -#include "webkit/browser/quota/quota_manager_proxy.h" -#include "webkit/common/fileapi/file_system_util.h" +#include "storage/browser/blob/file_stream_reader.h" +#include "storage/browser/fileapi/file_observers.h" +#include "storage/browser/fileapi/file_stream_writer.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation_runner.h" +#include "storage/browser/quota/quota_manager_proxy.h" +#include "storage/common/fileapi/file_system_util.h" namespace storage { diff --git a/storage/browser/fileapi/sandbox_file_stream_writer.h b/storage/browser/fileapi/sandbox_file_stream_writer.h new file mode 100644 index 0000000..d24e5b9 --- /dev/null +++ b/storage/browser/fileapi/sandbox_file_stream_writer.h @@ -0,0 +1,96 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_SANDBOX_FILE_STREAM_WRITER_H_ +#define STORAGE_BROWSER_FILEAPI_SANDBOX_FILE_STREAM_WRITER_H_ + +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/memory/scoped_ptr.h" +#include "storage/browser/fileapi/file_stream_writer.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/task_runner_bound_observer_list.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/blob/shareable_file_reference.h" +#include "storage/common/fileapi/file_system_types.h" +#include "storage/common/quota/quota_types.h" +#include "url/gurl.h" + +namespace storage { + +class FileSystemContext; +class FileSystemQuotaUtil; +class FileStreamWriter; + +class STORAGE_EXPORT_PRIVATE SandboxFileStreamWriter + : public NON_EXPORTED_BASE(FileStreamWriter) { + public: + SandboxFileStreamWriter(FileSystemContext* file_system_context, + const FileSystemURL& url, + int64 initial_offset, + const UpdateObserverList& observers); + virtual ~SandboxFileStreamWriter(); + + // FileStreamWriter overrides. + virtual int Write(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback) OVERRIDE; + virtual int Cancel(const net::CompletionCallback& callback) OVERRIDE; + virtual int Flush(const net::CompletionCallback& callback) OVERRIDE; + + // Used only by tests. + void set_default_quota(int64 quota) { + default_quota_ = quota; + } + + private: + // Performs quota calculation and calls local_file_writer_->Write(). + int WriteInternal(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback); + + // Callbacks that are chained for the first write. This eventually calls + // WriteInternal. + void DidCreateSnapshotFile( + const net::CompletionCallback& callback, + base::File::Error file_error, + const base::File::Info& file_info, + const base::FilePath& platform_path, + const scoped_refptr<storage::ShareableFileReference>& file_ref); + void DidGetUsageAndQuota(const net::CompletionCallback& callback, + storage::QuotaStatusCode status, + int64 usage, + int64 quota); + void DidInitializeForWrite(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback, + int init_status); + + void DidWrite(const net::CompletionCallback& callback, int write_response); + + // Stops the in-flight operation, calls |cancel_callback_| and returns true + // if there's a pending cancel request. + bool CancelIfRequested(); + + scoped_refptr<FileSystemContext> file_system_context_; + FileSystemURL url_; + int64 initial_offset_; + scoped_ptr<FileStreamWriter> local_file_writer_; + net::CompletionCallback cancel_callback_; + + UpdateObserverList observers_; + + base::FilePath file_path_; + int64 file_size_; + int64 total_bytes_written_; + int64 allowed_bytes_to_write_; + bool has_pending_operation_; + + int64 default_quota_; + + base::WeakPtrFactory<SandboxFileStreamWriter> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(SandboxFileStreamWriter); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_SANDBOX_FILE_STREAM_WRITER_H_ diff --git a/webkit/browser/fileapi/sandbox_file_system_backend.cc b/storage/browser/fileapi/sandbox_file_system_backend.cc index e80a0c4..888d4f5 100644 --- a/webkit/browser/fileapi/sandbox_file_system_backend.cc +++ b/storage/browser/fileapi/sandbox_file_system_backend.cc @@ -2,29 +2,29 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/sandbox_file_system_backend.h" +#include "storage/browser/fileapi/sandbox_file_system_backend.h" #include "base/bind.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/task_runner_util.h" +#include "storage/browser/blob/file_stream_reader.h" +#include "storage/browser/fileapi/async_file_util_adapter.h" +#include "storage/browser/fileapi/copy_or_move_file_validator.h" +#include "storage/browser/fileapi/file_stream_writer.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation.h" +#include "storage/browser/fileapi/file_system_operation_context.h" +#include "storage/browser/fileapi/file_system_options.h" +#include "storage/browser/fileapi/file_system_usage_cache.h" +#include "storage/browser/fileapi/obfuscated_file_util.h" +#include "storage/browser/fileapi/sandbox_file_system_backend_delegate.h" +#include "storage/browser/fileapi/sandbox_quota_observer.h" +#include "storage/browser/quota/quota_manager.h" +#include "storage/common/fileapi/file_system_types.h" +#include "storage/common/fileapi/file_system_util.h" #include "url/gurl.h" -#include "webkit/browser/blob/file_stream_reader.h" -#include "webkit/browser/fileapi/async_file_util_adapter.h" -#include "webkit/browser/fileapi/copy_or_move_file_validator.h" -#include "webkit/browser/fileapi/file_stream_writer.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation.h" -#include "webkit/browser/fileapi/file_system_operation_context.h" -#include "webkit/browser/fileapi/file_system_options.h" -#include "webkit/browser/fileapi/file_system_usage_cache.h" -#include "webkit/browser/fileapi/obfuscated_file_util.h" -#include "webkit/browser/fileapi/sandbox_file_system_backend_delegate.h" -#include "webkit/browser/fileapi/sandbox_quota_observer.h" -#include "webkit/browser/quota/quota_manager.h" -#include "webkit/common/fileapi/file_system_types.h" -#include "webkit/common/fileapi/file_system_util.h" using storage::QuotaManagerProxy; using storage::SpecialStoragePolicy; diff --git a/storage/browser/fileapi/sandbox_file_system_backend.h b/storage/browser/fileapi/sandbox_file_system_backend.h new file mode 100644 index 0000000..1f939a5 --- /dev/null +++ b/storage/browser/fileapi/sandbox_file_system_backend.h @@ -0,0 +1,85 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_SANDBOX_FILE_SYSTEM_BACKEND_H_ +#define STORAGE_BROWSER_FILEAPI_SANDBOX_FILE_SYSTEM_BACKEND_H_ + +#include <set> +#include <string> + +#include "base/compiler_specific.h" +#include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "storage/browser/fileapi/file_system_backend.h" +#include "storage/browser/fileapi/file_system_quota_util.h" +#include "storage/browser/fileapi/sandbox_file_system_backend_delegate.h" +#include "storage/browser/fileapi/task_runner_bound_observer_list.h" +#include "storage/browser/quota/special_storage_policy.h" +#include "storage/browser/storage_browser_export.h" + +namespace storage { + +// TEMPORARY or PERSISTENT filesystems, which are placed under the user's +// profile directory in a sandboxed way. +// This interface also lets one enumerate and remove storage for the origins +// that use the filesystem. +class STORAGE_EXPORT SandboxFileSystemBackend + : public FileSystemBackend { + public: + explicit SandboxFileSystemBackend(SandboxFileSystemBackendDelegate* delegate); + virtual ~SandboxFileSystemBackend(); + + // FileSystemBackend overrides. + virtual bool CanHandleType(FileSystemType type) const OVERRIDE; + virtual void Initialize(FileSystemContext* context) OVERRIDE; + virtual void ResolveURL(const FileSystemURL& url, + OpenFileSystemMode mode, + const OpenFileSystemCallback& callback) OVERRIDE; + virtual AsyncFileUtil* GetAsyncFileUtil(FileSystemType type) OVERRIDE; + virtual WatcherManager* GetWatcherManager(FileSystemType type) OVERRIDE; + virtual CopyOrMoveFileValidatorFactory* GetCopyOrMoveFileValidatorFactory( + FileSystemType type, + base::File::Error* error_code) OVERRIDE; + virtual FileSystemOperation* CreateFileSystemOperation( + const FileSystemURL& url, + FileSystemContext* context, + base::File::Error* error_code) const OVERRIDE; + virtual bool SupportsStreaming(const FileSystemURL& url) const OVERRIDE; + virtual bool HasInplaceCopyImplementation( + storage::FileSystemType type) const OVERRIDE; + virtual scoped_ptr<storage::FileStreamReader> CreateFileStreamReader( + const FileSystemURL& url, + int64 offset, + const base::Time& expected_modification_time, + FileSystemContext* context) const OVERRIDE; + virtual scoped_ptr<FileStreamWriter> CreateFileStreamWriter( + const FileSystemURL& url, + int64 offset, + FileSystemContext* context) const OVERRIDE; + virtual FileSystemQuotaUtil* GetQuotaUtil() OVERRIDE; + + // Returns an origin enumerator of this backend. + // This method can only be called on the file thread. + SandboxFileSystemBackendDelegate::OriginEnumerator* CreateOriginEnumerator(); + + void set_enable_temporary_file_system_in_incognito(bool enable) { + enable_temporary_file_system_in_incognito_ = enable; + } + bool enable_temporary_file_system_in_incognito() const { + return enable_temporary_file_system_in_incognito_; + } + + + private: + SandboxFileSystemBackendDelegate* delegate_; // Not owned. + + bool enable_temporary_file_system_in_incognito_; + + DISALLOW_COPY_AND_ASSIGN(SandboxFileSystemBackend); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_SANDBOX_FILE_SYSTEM_BACKEND_H_ diff --git a/webkit/browser/fileapi/sandbox_file_system_backend_delegate.cc b/storage/browser/fileapi/sandbox_file_system_backend_delegate.cc index e8ba8a9..a5b1f63 100644 --- a/webkit/browser/fileapi/sandbox_file_system_backend_delegate.cc +++ b/storage/browser/fileapi/sandbox_file_system_backend_delegate.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/sandbox_file_system_backend_delegate.h" +#include "storage/browser/fileapi/sandbox_file_system_backend_delegate.h" #include <vector> @@ -12,21 +12,21 @@ #include "base/stl_util.h" #include "base/task_runner_util.h" #include "net/base/net_util.h" -#include "webkit/browser/blob/file_stream_reader.h" -#include "webkit/browser/fileapi/async_file_util_adapter.h" -#include "webkit/browser/fileapi/file_system_context.h" -#include "webkit/browser/fileapi/file_system_operation_context.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/fileapi/file_system_usage_cache.h" -#include "webkit/browser/fileapi/obfuscated_file_util.h" -#include "webkit/browser/fileapi/quota/quota_backend_impl.h" -#include "webkit/browser/fileapi/quota/quota_reservation.h" -#include "webkit/browser/fileapi/quota/quota_reservation_manager.h" -#include "webkit/browser/fileapi/sandbox_file_stream_writer.h" -#include "webkit/browser/fileapi/sandbox_file_system_backend.h" -#include "webkit/browser/fileapi/sandbox_quota_observer.h" -#include "webkit/browser/quota/quota_manager_proxy.h" -#include "webkit/common/fileapi/file_system_util.h" +#include "storage/browser/blob/file_stream_reader.h" +#include "storage/browser/fileapi/async_file_util_adapter.h" +#include "storage/browser/fileapi/file_system_context.h" +#include "storage/browser/fileapi/file_system_operation_context.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/file_system_usage_cache.h" +#include "storage/browser/fileapi/obfuscated_file_util.h" +#include "storage/browser/fileapi/quota/quota_backend_impl.h" +#include "storage/browser/fileapi/quota/quota_reservation.h" +#include "storage/browser/fileapi/quota/quota_reservation_manager.h" +#include "storage/browser/fileapi/sandbox_file_stream_writer.h" +#include "storage/browser/fileapi/sandbox_file_system_backend.h" +#include "storage/browser/fileapi/sandbox_quota_observer.h" +#include "storage/browser/quota/quota_manager_proxy.h" +#include "storage/common/fileapi/file_system_util.h" namespace storage { diff --git a/storage/browser/fileapi/sandbox_file_system_backend_delegate.h b/storage/browser/fileapi/sandbox_file_system_backend_delegate.h new file mode 100644 index 0000000..d93bada --- /dev/null +++ b/storage/browser/fileapi/sandbox_file_system_backend_delegate.h @@ -0,0 +1,260 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_SANDBOX_FILE_SYSTEM_BACKEND_DELEGATE_H_ +#define STORAGE_BROWSER_FILEAPI_SANDBOX_FILE_SYSTEM_BACKEND_DELEGATE_H_ + +#include <map> +#include <set> +#include <string> +#include <utility> + +#include "base/files/file_path.h" +#include "base/gtest_prod_util.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "base/threading/thread_checker.h" +#include "base/time/time.h" +#include "storage/browser/fileapi/file_system_backend.h" +#include "storage/browser/fileapi/file_system_options.h" +#include "storage/browser/fileapi/file_system_quota_util.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class SequencedTaskRunner; +} + +namespace content { +class SandboxFileSystemBackendDelegateTest; +class SandboxFileSystemTestHelper; +} + +namespace storage { +class QuotaManagerProxy; +class SpecialStoragePolicy; +} + +namespace storage { +class FileStreamReader; +} + +namespace storage { + +class AsyncFileUtil; +class FileStreamWriter; +class FileSystemFileUtil; +class FileSystemOperationContext; +class FileSystemURL; +class FileSystemUsageCache; +class ObfuscatedFileUtil; +class QuotaReservationManager; +class SandboxFileSystemBackend; +class SandboxQuotaObserver; + +// Delegate implementation of the some methods in Sandbox/SyncFileSystemBackend. +// An instance of this class is created and owned by FileSystemContext. +class STORAGE_EXPORT SandboxFileSystemBackendDelegate + : public FileSystemQuotaUtil { + public: + typedef FileSystemBackend::OpenFileSystemCallback OpenFileSystemCallback; + + // The FileSystem directory name. + static const base::FilePath::CharType kFileSystemDirectory[]; + + // Origin enumerator interface. + // An instance of this interface is assumed to be called on the file thread. + class OriginEnumerator { + public: + virtual ~OriginEnumerator() {} + + // Returns the next origin. Returns empty if there are no more origins. + virtual GURL Next() = 0; + + // Returns the current origin's information. + virtual bool HasFileSystemType(FileSystemType type) const = 0; + }; + + // Returns the type directory name in sandbox directory for given |type|. + static std::string GetTypeString(FileSystemType type); + + SandboxFileSystemBackendDelegate( + storage::QuotaManagerProxy* quota_manager_proxy, + base::SequencedTaskRunner* file_task_runner, + const base::FilePath& profile_path, + storage::SpecialStoragePolicy* special_storage_policy, + const FileSystemOptions& file_system_options); + + virtual ~SandboxFileSystemBackendDelegate(); + + // Returns an origin enumerator of sandbox filesystem. + // This method can only be called on the file thread. + OriginEnumerator* CreateOriginEnumerator(); + + // Gets a base directory path of the sandboxed filesystem that is + // specified by |origin_url| and |type|. + // (The path is similar to the origin's root path but doesn't contain + // the 'unique' part.) + // Returns an empty path if the given type is invalid. + // This method can only be called on the file thread. + base::FilePath GetBaseDirectoryForOriginAndType( + const GURL& origin_url, + FileSystemType type, + bool create); + + // FileSystemBackend helpers. + void OpenFileSystem( + const GURL& origin_url, + FileSystemType type, + OpenFileSystemMode mode, + const OpenFileSystemCallback& callback, + const GURL& root_url); + scoped_ptr<FileSystemOperationContext> CreateFileSystemOperationContext( + const FileSystemURL& url, + FileSystemContext* context, + base::File::Error* error_code) const; + scoped_ptr<storage::FileStreamReader> CreateFileStreamReader( + const FileSystemURL& url, + int64 offset, + const base::Time& expected_modification_time, + FileSystemContext* context) const; + scoped_ptr<FileStreamWriter> CreateFileStreamWriter( + const FileSystemURL& url, + int64 offset, + FileSystemContext* context, + FileSystemType type) const; + + // FileSystemQuotaUtil overrides. + virtual base::File::Error DeleteOriginDataOnFileTaskRunner( + FileSystemContext* context, + storage::QuotaManagerProxy* proxy, + const GURL& origin_url, + FileSystemType type) OVERRIDE; + virtual void GetOriginsForTypeOnFileTaskRunner( + FileSystemType type, + std::set<GURL>* origins) OVERRIDE; + virtual void GetOriginsForHostOnFileTaskRunner( + FileSystemType type, + const std::string& host, + std::set<GURL>* origins) OVERRIDE; + virtual int64 GetOriginUsageOnFileTaskRunner( + FileSystemContext* context, + const GURL& origin_url, + FileSystemType type) OVERRIDE; + virtual scoped_refptr<QuotaReservation> + CreateQuotaReservationOnFileTaskRunner( + const GURL& origin_url, + FileSystemType type) OVERRIDE; + virtual void AddFileUpdateObserver( + FileSystemType type, + FileUpdateObserver* observer, + base::SequencedTaskRunner* task_runner) OVERRIDE; + virtual void AddFileChangeObserver( + FileSystemType type, + FileChangeObserver* observer, + base::SequencedTaskRunner* task_runner) OVERRIDE; + virtual void AddFileAccessObserver( + FileSystemType type, + FileAccessObserver* observer, + base::SequencedTaskRunner* task_runner) OVERRIDE; + virtual const UpdateObserverList* GetUpdateObservers( + FileSystemType type) const OVERRIDE; + virtual const ChangeObserverList* GetChangeObservers( + FileSystemType type) const OVERRIDE; + virtual const AccessObserverList* GetAccessObservers( + FileSystemType type) const OVERRIDE; + + // Registers quota observer for file updates on filesystem of |type|. + void RegisterQuotaUpdateObserver(FileSystemType type); + + void InvalidateUsageCache(const GURL& origin_url, + FileSystemType type); + void StickyInvalidateUsageCache(const GURL& origin_url, + FileSystemType type); + + void CollectOpenFileSystemMetrics(base::File::Error error_code); + + base::SequencedTaskRunner* file_task_runner() { + return file_task_runner_.get(); + } + + AsyncFileUtil* file_util() { return sandbox_file_util_.get(); } + FileSystemUsageCache* usage_cache() { return file_system_usage_cache_.get(); } + SandboxQuotaObserver* quota_observer() { return quota_observer_.get(); } + + storage::SpecialStoragePolicy* special_storage_policy() { + return special_storage_policy_.get(); + } + + const FileSystemOptions& file_system_options() const { + return file_system_options_; + } + + FileSystemFileUtil* sync_file_util(); + + private: + friend class QuotaBackendImpl; + friend class SandboxQuotaObserver; + friend class content::SandboxFileSystemBackendDelegateTest; + friend class content::SandboxFileSystemTestHelper; + + // Performs API-specific validity checks on the given path |url|. + // Returns true if access to |url| is valid in this filesystem. + bool IsAccessValid(const FileSystemURL& url) const; + + // Returns true if the given |url|'s scheme is allowed to access + // filesystem. + bool IsAllowedScheme(const GURL& url) const; + + // Returns a path to the usage cache file. + base::FilePath GetUsageCachePathForOriginAndType( + const GURL& origin_url, + FileSystemType type); + + // Returns a path to the usage cache file (static version). + static base::FilePath GetUsageCachePathForOriginAndType( + ObfuscatedFileUtil* sandbox_file_util, + const GURL& origin_url, + FileSystemType type, + base::File::Error* error_out); + + int64 RecalculateUsage(FileSystemContext* context, + const GURL& origin, + FileSystemType type); + + ObfuscatedFileUtil* obfuscated_file_util(); + + scoped_refptr<base::SequencedTaskRunner> file_task_runner_; + + scoped_ptr<AsyncFileUtil> sandbox_file_util_; + scoped_ptr<FileSystemUsageCache> file_system_usage_cache_; + scoped_ptr<SandboxQuotaObserver> quota_observer_; + scoped_ptr<QuotaReservationManager> quota_reservation_manager_; + + scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy_; + + FileSystemOptions file_system_options_; + + bool is_filesystem_opened_; + base::ThreadChecker io_thread_checker_; + + // Accessed only on the file thread. + std::set<GURL> visited_origins_; + + std::set<std::pair<GURL, FileSystemType> > sticky_dirty_origins_; + + std::map<FileSystemType, UpdateObserverList> update_observers_; + std::map<FileSystemType, ChangeObserverList> change_observers_; + std::map<FileSystemType, AccessObserverList> access_observers_; + + base::Time next_release_time_for_open_filesystem_stat_; + + base::WeakPtrFactory<SandboxFileSystemBackendDelegate> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(SandboxFileSystemBackendDelegate); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_SANDBOX_FILE_SYSTEM_BACKEND_DELEGATE_H_ diff --git a/webkit/browser/fileapi/sandbox_isolated_origin_database.cc b/storage/browser/fileapi/sandbox_isolated_origin_database.cc index 9d8afea..3e3c218 100644 --- a/webkit/browser/fileapi/sandbox_isolated_origin_database.cc +++ b/storage/browser/fileapi/sandbox_isolated_origin_database.cc @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/sandbox_isolated_origin_database.h" +#include "storage/browser/fileapi/sandbox_isolated_origin_database.h" #include "base/files/file_util.h" #include "base/logging.h" -#include "webkit/browser/fileapi/sandbox_origin_database.h" +#include "storage/browser/fileapi/sandbox_origin_database.h" namespace storage { diff --git a/storage/browser/fileapi/sandbox_isolated_origin_database.h b/storage/browser/fileapi/sandbox_isolated_origin_database.h new file mode 100644 index 0000000..f3ee49c --- /dev/null +++ b/storage/browser/fileapi/sandbox_isolated_origin_database.h @@ -0,0 +1,61 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_SANDBOX_ISOLATED_ORIGIN_DATABASE_H_ +#define STORAGE_BROWSER_FILEAPI_SANDBOX_ISOLATED_ORIGIN_DATABASE_H_ + +#include <string> +#include <vector> + +#include "storage/browser/fileapi/sandbox_origin_database_interface.h" + +namespace storage { + +class SandboxOriginDatabase; + +// This origin database implementation supports only one origin +// (therefore is expected to run very fast). +class STORAGE_EXPORT_PRIVATE SandboxIsolatedOriginDatabase + : public SandboxOriginDatabaseInterface { + public: + static const base::FilePath::CharType kObsoleteOriginDirectory[]; + + // Initialize this database for |origin| which makes GetPathForOrigin return + // |origin_directory| (in |file_system_directory|). + SandboxIsolatedOriginDatabase( + const std::string& origin, + const base::FilePath& file_system_directory, + const base::FilePath& origin_directory); + virtual ~SandboxIsolatedOriginDatabase(); + + // SandboxOriginDatabaseInterface overrides. + virtual bool HasOriginPath(const std::string& origin) OVERRIDE; + virtual bool GetPathForOrigin(const std::string& origin, + base::FilePath* directory) OVERRIDE; + virtual bool RemovePathForOrigin(const std::string& origin) OVERRIDE; + virtual bool ListAllOrigins(std::vector<OriginRecord>* origins) OVERRIDE; + virtual void DropDatabase() OVERRIDE; + + // TODO(kinuko): Deprecate this after a few release cycles, e.g. around M33. + static void MigrateBackFromObsoleteOriginDatabase( + const std::string& origin, + const base::FilePath& file_system_directory, + SandboxOriginDatabase* origin_database); + + const std::string& origin() const { return origin_; } + + private: + void MigrateDatabaseIfNeeded(); + + bool migration_checked_; + const std::string origin_; + const base::FilePath file_system_directory_; + const base::FilePath origin_directory_; + + DISALLOW_COPY_AND_ASSIGN(SandboxIsolatedOriginDatabase); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_SANDBOX_ISOLATED_ORIGIN_DATABASE_H_ diff --git a/webkit/browser/fileapi/sandbox_origin_database.cc b/storage/browser/fileapi/sandbox_origin_database.cc index 42205ed..fa0521f 100644 --- a/webkit/browser/fileapi/sandbox_origin_database.cc +++ b/storage/browser/fileapi/sandbox_origin_database.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/sandbox_origin_database.h" +#include "storage/browser/fileapi/sandbox_origin_database.h" #include <set> #include <utility> @@ -16,9 +16,9 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" +#include "storage/common/fileapi/file_system_util.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" #include "third_party/leveldatabase/src/include/leveldb/write_batch.h" -#include "webkit/common/fileapi/file_system_util.h" namespace { diff --git a/storage/browser/fileapi/sandbox_origin_database.h b/storage/browser/fileapi/sandbox_origin_database.h new file mode 100644 index 0000000..21779d5 --- /dev/null +++ b/storage/browser/fileapi/sandbox_origin_database.h @@ -0,0 +1,77 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_SANDBOX_ORIGIN_DATABASE_H_ +#define STORAGE_BROWSER_FILEAPI_SANDBOX_ORIGIN_DATABASE_H_ + +#include <string> +#include <vector> + +#include "base/memory/scoped_ptr.h" +#include "base/time/time.h" +#include "storage/browser/fileapi/sandbox_origin_database_interface.h" + +namespace leveldb { +class DB; +class Env; +class Status; +} + +namespace tracked_objects { +class Location; +} + +namespace storage { + +// All methods of this class other than the constructor may be used only from +// the browser's FILE thread. The constructor may be used on any thread. +class STORAGE_EXPORT_PRIVATE SandboxOriginDatabase + : public SandboxOriginDatabaseInterface { + public: + // Only one instance of SandboxOriginDatabase should exist for a given path + // at a given time. + SandboxOriginDatabase(const base::FilePath& file_system_directory, + leveldb::Env* env_override); + virtual ~SandboxOriginDatabase(); + + // SandboxOriginDatabaseInterface overrides. + virtual bool HasOriginPath(const std::string& origin) OVERRIDE; + virtual bool GetPathForOrigin(const std::string& origin, + base::FilePath* directory) OVERRIDE; + virtual bool RemovePathForOrigin(const std::string& origin) OVERRIDE; + virtual bool ListAllOrigins(std::vector<OriginRecord>* origins) OVERRIDE; + virtual void DropDatabase() OVERRIDE; + + base::FilePath GetDatabasePath() const; + void RemoveDatabase(); + + private: + enum RecoveryOption { + REPAIR_ON_CORRUPTION, + DELETE_ON_CORRUPTION, + FAIL_ON_CORRUPTION, + }; + + enum InitOption { + CREATE_IF_NONEXISTENT, + FAIL_IF_NONEXISTENT, + }; + + bool Init(InitOption init_option, RecoveryOption recovery_option); + bool RepairDatabase(const std::string& db_path); + void HandleError(const tracked_objects::Location& from_here, + const leveldb::Status& status); + void ReportInitStatus(const leveldb::Status& status); + bool GetLastPathNumber(int* number); + + base::FilePath file_system_directory_; + leveldb::Env* env_override_; + scoped_ptr<leveldb::DB> db_; + base::Time last_reported_time_; + DISALLOW_COPY_AND_ASSIGN(SandboxOriginDatabase); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_SANDBOX_ORIGIN_DATABASE_H_ diff --git a/webkit/browser/fileapi/sandbox_origin_database_interface.cc b/storage/browser/fileapi/sandbox_origin_database_interface.cc index 855e4c3..25ba1dc 100644 --- a/webkit/browser/fileapi/sandbox_origin_database_interface.cc +++ b/storage/browser/fileapi/sandbox_origin_database_interface.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/sandbox_origin_database_interface.h" +#include "storage/browser/fileapi/sandbox_origin_database_interface.h" namespace storage { diff --git a/storage/browser/fileapi/sandbox_origin_database_interface.h b/storage/browser/fileapi/sandbox_origin_database_interface.h new file mode 100644 index 0000000..4a01e43 --- /dev/null +++ b/storage/browser/fileapi/sandbox_origin_database_interface.h @@ -0,0 +1,55 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_SANDBOX_ORIGIN_DATABASE_INTERFACE_H_ +#define STORAGE_BROWSER_FILEAPI_SANDBOX_ORIGIN_DATABASE_INTERFACE_H_ + +#include <string> +#include <vector> + +#include "base/files/file_path.h" +#include "storage/browser/storage_browser_export.h" + +namespace storage { + +class STORAGE_EXPORT_PRIVATE SandboxOriginDatabaseInterface { + public: + struct STORAGE_EXPORT_PRIVATE OriginRecord { + std::string origin; + base::FilePath path; + + OriginRecord(); + OriginRecord(const std::string& origin, const base::FilePath& path); + ~OriginRecord(); + }; + + virtual ~SandboxOriginDatabaseInterface() {} + + // Returns true if the origin's path is included in this database. + virtual bool HasOriginPath(const std::string& origin) = 0; + + // This will produce a unique path and add it to its database, if it's not + // already present. + virtual bool GetPathForOrigin(const std::string& origin, + base::FilePath* directory) = 0; + + // Removes the origin's path from the database. + // Returns success if the origin has been successfully removed, or + // the origin is not found. + // (This doesn't remove the actual path). + virtual bool RemovePathForOrigin(const std::string& origin) = 0; + + // Lists all origins in this database. + virtual bool ListAllOrigins(std::vector<OriginRecord>* origins) = 0; + + // This will release all database resources in use; call it to save memory. + virtual void DropDatabase() = 0; + + protected: + SandboxOriginDatabaseInterface() {} +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_SANDBOX_ORIGIN_DATABASE_INTERFACE_H_ diff --git a/webkit/browser/fileapi/sandbox_prioritized_origin_database.cc b/storage/browser/fileapi/sandbox_prioritized_origin_database.cc index 9308504..80ccd27 100644 --- a/webkit/browser/fileapi/sandbox_prioritized_origin_database.cc +++ b/storage/browser/fileapi/sandbox_prioritized_origin_database.cc @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/sandbox_prioritized_origin_database.h" +#include "storage/browser/fileapi/sandbox_prioritized_origin_database.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/pickle.h" -#include "webkit/browser/fileapi/sandbox_isolated_origin_database.h" -#include "webkit/browser/fileapi/sandbox_origin_database.h" +#include "storage/browser/fileapi/sandbox_isolated_origin_database.h" +#include "storage/browser/fileapi/sandbox_origin_database.h" namespace storage { diff --git a/storage/browser/fileapi/sandbox_prioritized_origin_database.h b/storage/browser/fileapi/sandbox_prioritized_origin_database.h new file mode 100644 index 0000000..bbe1420 --- /dev/null +++ b/storage/browser/fileapi/sandbox_prioritized_origin_database.h @@ -0,0 +1,72 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_SANDBOX_PRIORITIZED_ORIGIN_DATABASE_H_ +#define STORAGE_BROWSER_FILEAPI_SANDBOX_PRIORITIZED_ORIGIN_DATABASE_H_ + +#include <string> +#include <vector> + +#include "base/memory/scoped_ptr.h" +#include "storage/browser/fileapi/sandbox_origin_database_interface.h" + +namespace leveldb { +class Env; +} + +namespace storage { + +class ObfuscatedFileUtil; +class SandboxIsolatedOriginDatabase; +class SandboxOriginDatabase; + +class STORAGE_EXPORT_PRIVATE SandboxPrioritizedOriginDatabase + : public SandboxOriginDatabaseInterface { + public: + SandboxPrioritizedOriginDatabase(const base::FilePath& file_system_directory, + leveldb::Env* env_override); + virtual ~SandboxPrioritizedOriginDatabase(); + + // Sets |origin| as primary origin in this database (e.g. may + // allow faster access). + // Returns false if this database already has a primary origin + // which is different from |origin|. + bool InitializePrimaryOrigin(const std::string& origin); + std::string GetPrimaryOrigin(); + + // SandboxOriginDatabaseInterface overrides. + virtual bool HasOriginPath(const std::string& origin) OVERRIDE; + virtual bool GetPathForOrigin(const std::string& origin, + base::FilePath* directory) OVERRIDE; + virtual bool RemovePathForOrigin(const std::string& origin) OVERRIDE; + virtual bool ListAllOrigins(std::vector<OriginRecord>* origins) OVERRIDE; + virtual void DropDatabase() OVERRIDE; + + const base::FilePath& primary_origin_file() const { + return primary_origin_file_; + } + + private: + bool MaybeLoadPrimaryOrigin(); + bool ResetPrimaryOrigin(const std::string& origin); + void MaybeMigrateDatabase(const std::string& origin); + void MaybeInitializeDatabases(bool create); + void MaybeInitializeNonPrimaryDatabase(bool create); + + // For migration. + friend class ObfuscatedFileUtil; + SandboxOriginDatabase* GetSandboxOriginDatabase(); + + const base::FilePath file_system_directory_; + leveldb::Env* env_override_; + const base::FilePath primary_origin_file_; + scoped_ptr<SandboxOriginDatabase> origin_database_; + scoped_ptr<SandboxIsolatedOriginDatabase> primary_origin_database_; + + DISALLOW_COPY_AND_ASSIGN(SandboxPrioritizedOriginDatabase); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_SANDBOX_PRIORITIZED_ORIGIN_DATABASE_H_ diff --git a/webkit/browser/fileapi/sandbox_quota_observer.cc b/storage/browser/fileapi/sandbox_quota_observer.cc index 412fd50..0c39464 100644 --- a/webkit/browser/fileapi/sandbox_quota_observer.cc +++ b/storage/browser/fileapi/sandbox_quota_observer.cc @@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/sandbox_quota_observer.h" +#include "storage/browser/fileapi/sandbox_quota_observer.h" #include "base/sequenced_task_runner.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/fileapi/file_system_usage_cache.h" -#include "webkit/browser/fileapi/sandbox_file_system_backend_delegate.h" -#include "webkit/browser/fileapi/timed_task_helper.h" -#include "webkit/browser/quota/quota_client.h" -#include "webkit/browser/quota/quota_manager_proxy.h" -#include "webkit/common/fileapi/file_system_util.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/file_system_usage_cache.h" +#include "storage/browser/fileapi/sandbox_file_system_backend_delegate.h" +#include "storage/browser/fileapi/timed_task_helper.h" +#include "storage/browser/quota/quota_client.h" +#include "storage/browser/quota/quota_manager_proxy.h" +#include "storage/common/fileapi/file_system_util.h" namespace storage { diff --git a/storage/browser/fileapi/sandbox_quota_observer.h b/storage/browser/fileapi/sandbox_quota_observer.h new file mode 100644 index 0000000..4ae2cf9 --- /dev/null +++ b/storage/browser/fileapi/sandbox_quota_observer.h @@ -0,0 +1,81 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_SANDBOX_QUOTA_OBSERVER_H_ +#define STORAGE_BROWSER_FILEAPI_SANDBOX_QUOTA_OBSERVER_H_ + +#include <map> + +#include "base/basictypes.h" +#include "base/compiler_specific.h" +#include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "storage/browser/fileapi/file_observers.h" +#include "storage/browser/fileapi/file_system_url.h" + +namespace base { +class SequencedTaskRunner; +} + +namespace storage { +class QuotaManagerProxy; +} + +namespace storage { + +class FileSystemUsageCache; +class FileSystemURL; +class TimedTaskHelper; +class ObfuscatedFileUtil; + +class SandboxQuotaObserver + : public FileUpdateObserver, + public FileAccessObserver { + public: + typedef std::map<base::FilePath, int64> PendingUpdateNotificationMap; + + SandboxQuotaObserver(storage::QuotaManagerProxy* quota_manager_proxy, + base::SequencedTaskRunner* update_notify_runner, + ObfuscatedFileUtil* sandbox_file_util, + FileSystemUsageCache* file_system_usage_cache_); + virtual ~SandboxQuotaObserver(); + + // FileUpdateObserver overrides. + virtual void OnStartUpdate(const FileSystemURL& url) OVERRIDE; + virtual void OnUpdate(const FileSystemURL& url, int64 delta) OVERRIDE; + virtual void OnEndUpdate(const FileSystemURL& url) OVERRIDE; + + // FileAccessObserver overrides. + virtual void OnAccess(const FileSystemURL& url) OVERRIDE; + + void SetUsageCacheEnabled(const GURL& origin, + FileSystemType type, + bool enabled); + + private: + void ApplyPendingUsageUpdate(); + void UpdateUsageCacheFile(const base::FilePath& usage_file_path, int64 delta); + + base::FilePath GetUsageCachePath(const FileSystemURL& url); + + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy_; + scoped_refptr<base::SequencedTaskRunner> update_notify_runner_; + + // Not owned; sandbox_file_util_ should have identical lifetime with this. + ObfuscatedFileUtil* sandbox_file_util_; + + // Not owned; file_system_usage_cache_ should have longer lifetime than this. + FileSystemUsageCache* file_system_usage_cache_; + + PendingUpdateNotificationMap pending_update_notification_; + scoped_ptr<TimedTaskHelper> delayed_cache_update_helper_; + + DISALLOW_COPY_AND_ASSIGN(SandboxQuotaObserver); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_SANDBOX_QUOTA_OBSERVER_H_ diff --git a/storage/browser/fileapi/task_runner_bound_observer_list.h b/storage/browser/fileapi/task_runner_bound_observer_list.h new file mode 100644 index 0000000..304eccb --- /dev/null +++ b/storage/browser/fileapi/task_runner_bound_observer_list.h @@ -0,0 +1,99 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_TASK_RUNNER_BOUND_OBSERVER_LIST_H_ +#define STORAGE_BROWSER_FILEAPI_TASK_RUNNER_BOUND_OBSERVER_LIST_H_ + +#include <map> + +#include "base/basictypes.h" +#include "base/bind.h" +#include "base/memory/ref_counted.h" +#include "base/sequenced_task_runner.h" +#include "base/threading/thread.h" + +namespace storage { + +// A wrapper for dispatching method. +template <class T, class Method, class Params> +void NotifyWrapper(T obj, Method m, const Params& p) { + DispatchToMethod(base::internal::UnwrapTraits<T>::Unwrap(obj), m, p); +} + +// An observer list helper to notify on a given task runner. +// Observer pointers (stored as ObserverStoreType) must be kept alive +// until this list dispatches all the notifications. +// +// Unlike regular ObserverList or ObserverListThreadSafe internal observer +// list is immutable (though not declared const) and cannot be modified after +// constructed. +// +// It is ok to specify scoped_refptr<Observer> as ObserverStoreType to +// explicitly keep references if necessary. +template <class Observer, class ObserverStoreType = Observer*> +class TaskRunnerBoundObserverList { + public: + typedef scoped_refptr<base::SequencedTaskRunner> TaskRunnerPtr; + typedef std::map<ObserverStoreType, TaskRunnerPtr> ObserversListMap; + + // Creates an empty list. + TaskRunnerBoundObserverList<Observer, ObserverStoreType>() {} + + // Creates a new list with given |observers|. + explicit TaskRunnerBoundObserverList<Observer, ObserverStoreType>( + const ObserversListMap& observers) + : observers_(observers) {} + + virtual ~TaskRunnerBoundObserverList<Observer, ObserverStoreType>() {} + + // Returns a new observer list with given observer. + // It is valid to give NULL as |runner_to_notify|, and in that case + // notifications are dispatched on the current runner. + // Note that this is a const method and does NOT change 'this' observer + // list but returns a new list. + TaskRunnerBoundObserverList<Observer, ObserverStoreType> AddObserver( + Observer* observer, + base::SequencedTaskRunner* runner_to_notify) const { + ObserversListMap observers = observers_; + observers.insert(std::make_pair(observer, runner_to_notify)); + return TaskRunnerBoundObserverList<Observer, ObserverStoreType>(observers); + } + + // Notify on the task runner that is given to AddObserver. + // If we're already on the runner this just dispatches the method. + template <class Method, class Params> + void Notify(Method method, const Params& params) const { + COMPILE_ASSERT( + (base::internal::ParamsUseScopedRefptrCorrectly<Params>::value), + badunboundmethodparams); + for (typename ObserversListMap::const_iterator it = observers_.begin(); + it != observers_.end(); ++it) { + if (!it->second.get() || it->second->RunsTasksOnCurrentThread()) { + DispatchToMethod(UnwrapTraits::Unwrap(it->first), method, params); + continue; + } + it->second->PostTask( + FROM_HERE, + base::Bind(&NotifyWrapper<ObserverStoreType, Method, Params>, + it->first, method, params)); + } + } + + private: + typedef base::internal::UnwrapTraits<ObserverStoreType> UnwrapTraits; + + ObserversListMap observers_; +}; + +class FileAccessObserver; +class FileChangeObserver; +class FileUpdateObserver; + +typedef TaskRunnerBoundObserverList<FileAccessObserver> AccessObserverList; +typedef TaskRunnerBoundObserverList<FileChangeObserver> ChangeObserverList; +typedef TaskRunnerBoundObserverList<FileUpdateObserver> UpdateObserverList; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_TASK_RUNNER_BOUND_OBSERVER_LIST_H_ diff --git a/webkit/browser/fileapi/timed_task_helper.cc b/storage/browser/fileapi/timed_task_helper.cc index 4794723..950df76 100644 --- a/webkit/browser/fileapi/timed_task_helper.cc +++ b/storage/browser/fileapi/timed_task_helper.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/timed_task_helper.h" +#include "storage/browser/fileapi/timed_task_helper.h" #include "base/bind.h" #include "base/logging.h" diff --git a/storage/browser/fileapi/timed_task_helper.h b/storage/browser/fileapi/timed_task_helper.h new file mode 100644 index 0000000..4663501 --- /dev/null +++ b/storage/browser/fileapi/timed_task_helper.h @@ -0,0 +1,59 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_TIMED_TASK_HELPER_H_ +#define STORAGE_BROWSER_FILEAPI_TIMED_TASK_HELPER_H_ + +#include "base/basictypes.h" +#include "base/callback.h" +#include "base/location.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/time/time.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class SequencedTaskRunner; +} + +namespace storage { + +// Works similarly as base::Timer, but takes SequencedTaskRunner and +// runs tasks on it (instead of implicitly bound to a thread). +// TODO(kinuko): This has nothing to do with fileapi. Move somewhere +// more common place. +class STORAGE_EXPORT TimedTaskHelper { + public: + explicit TimedTaskHelper(base::SequencedTaskRunner* task_runner); + ~TimedTaskHelper(); + + bool IsRunning() const; + void Start(const tracked_objects::Location& posted_from, + base::TimeDelta delay, + const base::Closure& user_task); + void Reset(); + + private: + struct Tracker; + static void Fired(scoped_ptr<Tracker> tracker); + + void OnFired(scoped_ptr<Tracker> tracker); + void PostDelayedTask(scoped_ptr<Tracker> tracker, base::TimeDelta delay); + + scoped_refptr<base::SequencedTaskRunner> task_runner_; + tracked_objects::Location posted_from_; + base::TimeDelta delay_; + base::Closure user_task_; + + base::TimeTicks desired_run_time_; + + // This is set to non-null and owned by a timer task while timer is running. + Tracker* tracker_; + + DISALLOW_COPY_AND_ASSIGN(TimedTaskHelper); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_TIMED_TASK_HELPER_H_ diff --git a/webkit/browser/fileapi/transient_file_util.cc b/storage/browser/fileapi/transient_file_util.cc index 334b5ed..c0c2a6b 100644 --- a/webkit/browser/fileapi/transient_file_util.cc +++ b/storage/browser/fileapi/transient_file_util.cc @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/fileapi/transient_file_util.h" +#include "storage/browser/fileapi/transient_file_util.h" #include <string> #include "base/bind.h" #include "base/files/file_path.h" -#include "webkit/browser/fileapi/file_system_operation_context.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/fileapi/isolated_context.h" +#include "storage/browser/fileapi/file_system_operation_context.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/fileapi/isolated_context.h" using storage::ScopedFile; diff --git a/storage/browser/fileapi/transient_file_util.h b/storage/browser/fileapi/transient_file_util.h new file mode 100644 index 0000000..16d710e --- /dev/null +++ b/storage/browser/fileapi/transient_file_util.h @@ -0,0 +1,36 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_TRANSIENT_FILE_UTIL_H_ +#define STORAGE_BROWSER_FILEAPI_TRANSIENT_FILE_UTIL_H_ + +#include "base/memory/scoped_ptr.h" +#include "storage/browser/fileapi/local_file_util.h" +#include "storage/browser/storage_browser_export.h" + +namespace storage { + +class FileSystemOperationContext; + +class STORAGE_EXPORT_PRIVATE TransientFileUtil + : public LocalFileUtil { + public: + TransientFileUtil() {} + virtual ~TransientFileUtil() {} + + // LocalFileUtil overrides. + virtual storage::ScopedFile CreateSnapshotFile( + FileSystemOperationContext* context, + const FileSystemURL& url, + base::File::Error* error, + base::File::Info* file_info, + base::FilePath* platform_path) OVERRIDE; + + private: + DISALLOW_COPY_AND_ASSIGN(TransientFileUtil); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_TRANSIENT_FILE_UTIL_H_ diff --git a/storage/browser/fileapi/watcher_manager.h b/storage/browser/fileapi/watcher_manager.h new file mode 100644 index 0000000..40f3733 --- /dev/null +++ b/storage/browser/fileapi/watcher_manager.h @@ -0,0 +1,67 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_WATCHER_MANAGER_H_ +#define STORAGE_BROWSER_FILEAPI_WATCHER_MANAGER_H_ + +#include <vector> + +#include "base/basictypes.h" +#include "base/callback_forward.h" +#include "base/files/file.h" + +namespace base { +class Time; +} + +namespace storage { + +class FileSystemOperationContext; +class FileSystemURL; + +// An interface for providing entry observing capability for file system +// backends. +// +// It is NOT valid to give null callback to this class, and implementors +// can assume that they don't get any null callbacks. +class WatcherManager { + public: + typedef base::Callback<void(base::File::Error result)> StatusCallback; + + // Observes watched entries. + class Observer { + public: + Observer() {} + virtual ~Observer() {} + + // Notifies about an entry represented by |url| being changed. + virtual void OnEntryChanged(const FileSystemURL& url) = 0; + + // Notifies about an entry represented by |url| being removed. + virtual void OnEntryRemoved(const FileSystemURL& url) = 0; + }; + + virtual ~WatcherManager() {} + + virtual void AddObserver(Observer* observer) = 0; + virtual void RemoveObserver(Observer* observer) = 0; + virtual bool HasObserver(Observer* observer) const = 0; + + // Observes a directory entry. If the |recursive| mode is not supported then + // FILE_ERROR_INVALID_OPERATION must be returned as an error. If the |url| is + // already watched, or setting up the watcher fails, then |callback| + // must be called with a specific error code. Otherwise |callback| must be + // called with the FILE_OK error code. + virtual void WatchDirectory(const FileSystemURL& url, + bool recursive, + const StatusCallback& callback) = 0; + + // Stops observing an entry represented by |url|. + virtual void UnwatchEntry(const FileSystemURL& url, + const StatusCallback& callback) = 0; +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_WATCHER_MANAGER_H_ diff --git a/webkit/browser/quota/OWNERS b/storage/browser/quota/OWNERS index 66ba5d2..66ba5d2 100644 --- a/webkit/browser/quota/OWNERS +++ b/storage/browser/quota/OWNERS diff --git a/storage/browser/quota/quota_callbacks.h b/storage/browser/quota/quota_callbacks.h new file mode 100644 index 0000000..b499922 --- /dev/null +++ b/storage/browser/quota/quota_callbacks.h @@ -0,0 +1,129 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_QUOTA_QUOTA_CALLBACKS_H_ +#define STORAGE_BROWSER_QUOTA_QUOTA_CALLBACKS_H_ + +#include <map> +#include <set> +#include <string> +#include <vector> + +#include "base/basictypes.h" +#include "base/callback.h" +#include "base/tuple.h" +#include "storage/common/quota/quota_status_code.h" +#include "storage/common/quota/quota_types.h" + +class GURL; + +namespace storage { + +struct UsageInfo; +typedef std::vector<UsageInfo> UsageInfoEntries; + +// Common callback types that are used throughout in the quota module. +typedef base::Callback<void(int64 usage, + int64 unlimited_usage)> GlobalUsageCallback; +typedef base::Callback<void(QuotaStatusCode status, int64 quota)> QuotaCallback; +typedef base::Callback<void(int64 usage)> UsageCallback; +typedef base::Callback<void(QuotaStatusCode, int64)> AvailableSpaceCallback; +typedef base::Callback<void(QuotaStatusCode)> StatusCallback; +typedef base::Callback<void(const std::set<GURL>& origins, + StorageType type)> GetOriginsCallback; +typedef base::Callback<void(const UsageInfoEntries&)> GetUsageInfoCallback; + +template<typename CallbackType, typename Args> +void DispatchToCallback(const CallbackType& callback, + const Args& args) { + DispatchToMethod(&callback, &CallbackType::Run, args); +} + +// Simple template wrapper for a callback queue. +template <typename CallbackType, typename Args> +class CallbackQueue { + public: + // Returns true if the given |callback| is the first one added to the queue. + bool Add(const CallbackType& callback) { + callbacks_.push_back(callback); + return (callbacks_.size() == 1); + } + + bool HasCallbacks() const { + return !callbacks_.empty(); + } + + // Runs the callbacks added to the queue and clears the queue. + void Run(const Args& args) { + typedef typename std::vector<CallbackType>::iterator iterator; + for (iterator iter = callbacks_.begin(); + iter != callbacks_.end(); ++iter) + DispatchToCallback(*iter, args); + callbacks_.clear(); + } + + private: + std::vector<CallbackType> callbacks_; +}; + +typedef CallbackQueue<GlobalUsageCallback, + Tuple2<int64, int64> > + GlobalUsageCallbackQueue; +typedef CallbackQueue<UsageCallback, Tuple1<int64> > + UsageCallbackQueue; +typedef CallbackQueue<AvailableSpaceCallback, + Tuple2<QuotaStatusCode, int64> > + AvailableSpaceCallbackQueue; +typedef CallbackQueue<QuotaCallback, + Tuple2<QuotaStatusCode, int64> > + GlobalQuotaCallbackQueue; +typedef CallbackQueue<base::Closure, Tuple0> ClosureQueue; + +template <typename CallbackType, typename Key, typename Args> +class CallbackQueueMap { + public: + typedef CallbackQueue<CallbackType, Args> CallbackQueueType; + typedef std::map<Key, CallbackQueueType> CallbackMap; + typedef typename CallbackMap::iterator iterator; + + bool Add(const Key& key, const CallbackType& callback) { + return callback_map_[key].Add(callback); + } + + bool HasCallbacks(const Key& key) const { + return (callback_map_.find(key) != callback_map_.end()); + } + + bool HasAnyCallbacks() const { + return !callback_map_.empty(); + } + + iterator Begin() { return callback_map_.begin(); } + iterator End() { return callback_map_.end(); } + + void Clear() { callback_map_.clear(); } + + // Runs the callbacks added for the given |key| and clears the key + // from the map. + void Run(const Key& key, const Args& args) { + if (!this->HasCallbacks(key)) + return; + CallbackQueueType& queue = callback_map_[key]; + queue.Run(args); + callback_map_.erase(key); + } + + private: + CallbackMap callback_map_; +}; + +typedef CallbackQueueMap<UsageCallback, std::string, Tuple1<int64> > + HostUsageCallbackMap; +typedef CallbackQueueMap<QuotaCallback, std::string, + Tuple2<QuotaStatusCode, int64> > + HostQuotaCallbackMap; + +} // namespace storage + +#endif // STORAGE_QUOTA_QUOTA_TYPES_H_ diff --git a/storage/browser/quota/quota_client.h b/storage/browser/quota/quota_client.h new file mode 100644 index 0000000..8a6a294 --- /dev/null +++ b/storage/browser/quota/quota_client.h @@ -0,0 +1,81 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_QUOTA_QUOTA_CLIENT_H_ +#define STORAGE_BROWSER_QUOTA_QUOTA_CLIENT_H_ + +#include <list> +#include <set> +#include <string> + +#include "base/callback.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/quota/quota_types.h" +#include "url/gurl.h" + +namespace storage { + +// An abstract interface for quota manager clients. +// Each storage API must provide an implementation of this interface and +// register it to the quota manager. +// All the methods are assumed to be called on the IO thread in the browser. +class STORAGE_EXPORT QuotaClient { + public: + typedef base::Callback<void(int64 usage)> GetUsageCallback; + typedef base::Callback<void(const std::set<GURL>& origins)> + GetOriginsCallback; + typedef base::Callback<void(QuotaStatusCode status)> DeletionCallback; + + virtual ~QuotaClient() {} + + enum ID { + kUnknown = 1 << 0, + kFileSystem = 1 << 1, + kDatabase = 1 << 2, + kAppcache = 1 << 3, + kIndexedDatabase = 1 << 4, + kAllClientsMask = -1, + }; + + virtual ID id() const = 0; + + // Called when the quota manager is destroyed. + virtual void OnQuotaManagerDestroyed() = 0; + + // Called by the QuotaManager. + // Gets the amount of data stored in the storage specified by + // |origin_url| and |type|. + // Note it is safe to fire the callback after the QuotaClient is destructed. + virtual void GetOriginUsage(const GURL& origin_url, + StorageType type, + const GetUsageCallback& callback) = 0; + + // Called by the QuotaManager. + // Returns a list of origins that has data in the |type| storage. + // Note it is safe to fire the callback after the QuotaClient is destructed. + virtual void GetOriginsForType(StorageType type, + const GetOriginsCallback& callback) = 0; + + // Called by the QuotaManager. + // Returns a list of origins that match the |host|. + // Note it is safe to fire the callback after the QuotaClient is destructed. + virtual void GetOriginsForHost(StorageType type, + const std::string& host, + const GetOriginsCallback& callback) = 0; + + // Called by the QuotaManager. + // Note it is safe to fire the callback after the QuotaClient is destructed. + virtual void DeleteOriginData(const GURL& origin, + StorageType type, + const DeletionCallback& callback) = 0; + + virtual bool DoesSupport(StorageType type) const = 0; +}; + +// TODO(dmikurube): Replace it to std::vector for efficiency. +typedef std::list<QuotaClient*> QuotaClientList; + +} // namespace storage + +#endif // STORAGE_BROWSER_QUOTA_QUOTA_CLIENT_H_ diff --git a/webkit/browser/quota/quota_database.cc b/storage/browser/quota/quota_database.cc index f455272..d6c94b3 100644 --- a/webkit/browser/quota/quota_database.cc +++ b/storage/browser/quota/quota_database.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/quota/quota_database.h" +#include "storage/browser/quota/quota_database.h" #include <string> #include <vector> @@ -15,8 +15,8 @@ #include "sql/meta_table.h" #include "sql/statement.h" #include "sql/transaction.h" +#include "storage/browser/quota/special_storage_policy.h" #include "url/gurl.h" -#include "webkit/browser/quota/special_storage_policy.h" namespace storage { namespace { diff --git a/storage/browser/quota/quota_database.h b/storage/browser/quota/quota_database.h new file mode 100644 index 0000000..6ca5651 --- /dev/null +++ b/storage/browser/quota/quota_database.h @@ -0,0 +1,190 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_QUOTA_QUOTA_DATABASE_H_ +#define STORAGE_BROWSER_QUOTA_QUOTA_DATABASE_H_ + +#include <set> +#include <string> + +#include "base/basictypes.h" +#include "base/callback.h" +#include "base/files/file_path.h" +#include "base/gtest_prod_util.h" +#include "base/memory/scoped_ptr.h" +#include "base/time/time.h" +#include "base/timer/timer.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/quota/quota_types.h" +#include "url/gurl.h" + +namespace content { +class QuotaDatabaseTest; +} + +namespace sql { +class Connection; +class MetaTable; +} + +class GURL; + +namespace storage { + +class SpecialStoragePolicy; + +// All the methods of this class must run on the DB thread. +class STORAGE_EXPORT_PRIVATE QuotaDatabase { + public: + // Constants for {Get,Set}QuotaConfigValue keys. + static const char kDesiredAvailableSpaceKey[]; + static const char kTemporaryQuotaOverrideKey[]; + + // If 'path' is empty, an in memory database will be used. + explicit QuotaDatabase(const base::FilePath& path); + ~QuotaDatabase(); + + void CloseConnection(); + + bool GetHostQuota(const std::string& host, StorageType type, int64* quota); + bool SetHostQuota(const std::string& host, StorageType type, int64 quota); + bool DeleteHostQuota(const std::string& host, StorageType type); + + bool SetOriginLastAccessTime(const GURL& origin, + StorageType type, + base::Time last_access_time); + + bool SetOriginLastModifiedTime(const GURL& origin, + StorageType type, + base::Time last_modified_time); + + // Register initial |origins| info |type| to the database. + // This method is assumed to be called only after the installation or + // the database schema reset. + bool RegisterInitialOriginInfo( + const std::set<GURL>& origins, StorageType type); + + bool DeleteOriginInfo(const GURL& origin, StorageType type); + + bool GetQuotaConfigValue(const char* key, int64* value); + bool SetQuotaConfigValue(const char* key, int64 value); + + // Sets |origin| to the least recently used origin of origins not included + // in |exceptions| and not granted the special unlimited storage right. + // It returns false when it failed in accessing the database. + // |origin| is set to empty when there is no matching origin. + bool GetLRUOrigin(StorageType type, + const std::set<GURL>& exceptions, + SpecialStoragePolicy* special_storage_policy, + GURL* origin); + + // Populates |origins| with the ones that have been modified since + // the |modified_since|. + bool GetOriginsModifiedSince(StorageType type, + std::set<GURL>* origins, + base::Time modified_since); + + // Returns false if SetOriginDatabaseBootstrapped has never + // been called before, which means existing origins may not have been + // registered. + bool IsOriginDatabaseBootstrapped(); + bool SetOriginDatabaseBootstrapped(bool bootstrap_flag); + + private: + struct STORAGE_EXPORT_PRIVATE QuotaTableEntry { + QuotaTableEntry(); + QuotaTableEntry( + const std::string& host, + StorageType type, + int64 quota); + std::string host; + StorageType type; + int64 quota; + }; + friend STORAGE_EXPORT_PRIVATE bool operator <( + const QuotaTableEntry& lhs, const QuotaTableEntry& rhs); + + struct STORAGE_EXPORT_PRIVATE OriginInfoTableEntry { + OriginInfoTableEntry(); + OriginInfoTableEntry( + const GURL& origin, + StorageType type, + int used_count, + const base::Time& last_access_time, + const base::Time& last_modified_time); + GURL origin; + StorageType type; + int used_count; + base::Time last_access_time; + base::Time last_modified_time; + }; + friend STORAGE_EXPORT_PRIVATE bool operator <( + const OriginInfoTableEntry& lhs, const OriginInfoTableEntry& rhs); + + // Structures used for CreateSchema. + struct TableSchema { + const char* table_name; + const char* columns; + }; + struct IndexSchema { + const char* index_name; + const char* table_name; + const char* columns; + bool unique; + }; + + typedef base::Callback<bool (const QuotaTableEntry&)> QuotaTableCallback; + typedef base::Callback<bool (const OriginInfoTableEntry&)> + OriginInfoTableCallback; + + struct QuotaTableImporter; + + // For long-running transactions support. We always keep a transaction open + // so that multiple transactions can be batched. They are flushed + // with a delay after a modification has been made. We support neither + // nested transactions nor rollback (as we don't need them for now). + void Commit(); + void ScheduleCommit(); + + bool FindOriginUsedCount(const GURL& origin, + StorageType type, + int* used_count); + + bool LazyOpen(bool create_if_needed); + bool EnsureDatabaseVersion(); + bool ResetSchema(); + bool UpgradeSchema(int current_version); + + static bool CreateSchema( + sql::Connection* database, + sql::MetaTable* meta_table, + int schema_version, int compatible_version, + const TableSchema* tables, size_t tables_size, + const IndexSchema* indexes, size_t indexes_size); + + // |callback| may return false to stop reading data. + bool DumpQuotaTable(const QuotaTableCallback& callback); + bool DumpOriginInfoTable(const OriginInfoTableCallback& callback); + + base::FilePath db_file_path_; + + scoped_ptr<sql::Connection> db_; + scoped_ptr<sql::MetaTable> meta_table_; + bool is_recreating_; + bool is_disabled_; + + base::OneShotTimer<QuotaDatabase> timer_; + + friend class content::QuotaDatabaseTest; + friend class QuotaManager; + + static const TableSchema kTables[]; + static const IndexSchema kIndexes[]; + + DISALLOW_COPY_AND_ASSIGN(QuotaDatabase); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_QUOTA_QUOTA_DATABASE_H_ diff --git a/webkit/browser/quota/quota_manager.cc b/storage/browser/quota/quota_manager.cc index a669008..e0f3b14 100644 --- a/webkit/browser/quota/quota_manager.cc +++ b/storage/browser/quota/quota_manager.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/quota/quota_manager.h" +#include "storage/browser/quota/quota_manager.h" #include <algorithm> #include <deque> @@ -23,12 +23,12 @@ #include "base/task_runner_util.h" #include "base/time/time.h" #include "net/base/net_util.h" -#include "webkit/browser/quota/quota_database.h" -#include "webkit/browser/quota/quota_manager_proxy.h" -#include "webkit/browser/quota/quota_temporary_storage_evictor.h" -#include "webkit/browser/quota/storage_monitor.h" -#include "webkit/browser/quota/usage_tracker.h" -#include "webkit/common/quota/quota_types.h" +#include "storage/browser/quota/quota_database.h" +#include "storage/browser/quota/quota_manager_proxy.h" +#include "storage/browser/quota/quota_temporary_storage_evictor.h" +#include "storage/browser/quota/storage_monitor.h" +#include "storage/browser/quota/usage_tracker.h" +#include "storage/common/quota/quota_types.h" #define UMA_HISTOGRAM_MBYTES(name, sample) \ UMA_HISTOGRAM_CUSTOM_COUNTS( \ diff --git a/storage/browser/quota/quota_manager.h b/storage/browser/quota/quota_manager.h new file mode 100644 index 0000000..98a9415 --- /dev/null +++ b/storage/browser/quota/quota_manager.h @@ -0,0 +1,460 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_QUOTA_QUOTA_MANAGER_H_ +#define STORAGE_BROWSER_QUOTA_QUOTA_MANAGER_H_ + +#include <deque> +#include <list> +#include <map> +#include <set> +#include <string> +#include <utility> +#include <vector> + +#include "base/basictypes.h" +#include "base/callback.h" +#include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "base/sequenced_task_runner_helpers.h" +#include "storage/browser/quota/quota_callbacks.h" +#include "storage/browser/quota/quota_client.h" +#include "storage/browser/quota/quota_database.h" +#include "storage/browser/quota/quota_task.h" +#include "storage/browser/quota/special_storage_policy.h" +#include "storage/browser/quota/storage_observer.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class FilePath; +class SequencedTaskRunner; +class SingleThreadTaskRunner; +} + +namespace quota_internals { +class QuotaInternalsProxy; +} + +namespace content { +class MockQuotaManager; +class MockStorageClient; +class QuotaManagerTest; +class StorageMonitorTest; + +} + +namespace storage { + +class QuotaDatabase; +class QuotaManagerProxy; +class QuotaTemporaryStorageEvictor; +class StorageMonitor; +class UsageTracker; + +struct QuotaManagerDeleter; + +struct STORAGE_EXPORT UsageAndQuota { + int64 usage; + int64 global_limited_usage; + int64 quota; + int64 available_disk_space; + + UsageAndQuota(); + UsageAndQuota(int64 usage, + int64 global_limited_usage, + int64 quota, + int64 available_disk_space); +}; + +// An interface called by QuotaTemporaryStorageEvictor. +class STORAGE_EXPORT QuotaEvictionHandler { + public: + typedef base::Callback<void(const GURL&)> GetLRUOriginCallback; + typedef StatusCallback EvictOriginDataCallback; + typedef base::Callback<void(QuotaStatusCode status, + const UsageAndQuota& usage_and_quota)> + UsageAndQuotaCallback; + + // Returns the least recently used origin. It might return empty + // GURL when there are no evictable origins. + virtual void GetLRUOrigin( + StorageType type, + const GetLRUOriginCallback& callback) = 0; + + virtual void EvictOriginData( + const GURL& origin, + StorageType type, + const EvictOriginDataCallback& callback) = 0; + + virtual void GetUsageAndQuotaForEviction( + const UsageAndQuotaCallback& callback) = 0; + + protected: + virtual ~QuotaEvictionHandler() {} +}; + +struct UsageInfo { + UsageInfo(const std::string& host, StorageType type, int64 usage) + : host(host), + type(type), + usage(usage) {} + std::string host; + StorageType type; + int64 usage; +}; + +// The quota manager class. This class is instantiated per profile and +// held by the profile. With the exception of the constructor and the +// proxy() method, all methods should only be called on the IO thread. +class STORAGE_EXPORT QuotaManager + : public QuotaTaskObserver, + public QuotaEvictionHandler, + public base::RefCountedThreadSafe<QuotaManager, QuotaManagerDeleter> { + public: + typedef base::Callback<void(QuotaStatusCode, + int64 /* usage */, + int64 /* quota */)> + GetUsageAndQuotaCallback; + + static const int64 kIncognitoDefaultQuotaLimit; + static const int64 kNoLimit; + + QuotaManager( + bool is_incognito, + const base::FilePath& profile_path, + const scoped_refptr<base::SingleThreadTaskRunner>& io_thread, + const scoped_refptr<base::SequencedTaskRunner>& db_thread, + const scoped_refptr<SpecialStoragePolicy>& special_storage_policy); + + // Returns a proxy object that can be used on any thread. + QuotaManagerProxy* proxy() { return proxy_.get(); } + + // Called by clients or webapps. Returns usage per host. + void GetUsageInfo(const GetUsageInfoCallback& callback); + + // Called by Web Apps. + // This method is declared as virtual to allow test code to override it. + virtual void GetUsageAndQuotaForWebApps( + const GURL& origin, + StorageType type, + const GetUsageAndQuotaCallback& callback); + + // Called by StorageClients. + // This method is declared as virtual to allow test code to override it. + // + // For UnlimitedStorage origins, this version skips usage and quota handling + // to avoid extra query cost. + // Do not call this method for apps/user-facing code. + virtual void GetUsageAndQuota( + const GURL& origin, + StorageType type, + const GetUsageAndQuotaCallback& callback); + + // Called by clients via proxy. + // Client storage should call this method when storage is accessed. + // Used to maintain LRU ordering. + void NotifyStorageAccessed(QuotaClient::ID client_id, + const GURL& origin, + StorageType type); + + // Called by clients via proxy. + // Client storage must call this method whenever they have made any + // modifications that change the amount of data stored in their storage. + void NotifyStorageModified(QuotaClient::ID client_id, + const GURL& origin, + StorageType type, + int64 delta); + + // Used to avoid evicting origins with open pages. + // A call to NotifyOriginInUse must be balanced by a later call + // to NotifyOriginNoLongerInUse. + void NotifyOriginInUse(const GURL& origin); + void NotifyOriginNoLongerInUse(const GURL& origin); + bool IsOriginInUse(const GURL& origin) const { + return origins_in_use_.find(origin) != origins_in_use_.end(); + } + + void SetUsageCacheEnabled(QuotaClient::ID client_id, + const GURL& origin, + StorageType type, + bool enabled); + + // DeleteOriginData and DeleteHostData (surprisingly enough) delete data of a + // particular StorageType associated with either a specific origin or set of + // origins. Each method additionally requires a |quota_client_mask| which + // specifies the types of QuotaClients to delete from the origin. This is + // specified by the caller as a bitmask built from QuotaClient::IDs. Setting + // the mask to QuotaClient::kAllClientsMask will remove all clients from the + // origin, regardless of type. + virtual void DeleteOriginData(const GURL& origin, + StorageType type, + int quota_client_mask, + const StatusCallback& callback); + void DeleteHostData(const std::string& host, + StorageType type, + int quota_client_mask, + const StatusCallback& callback); + + // Called by UI and internal modules. + void GetAvailableSpace(const AvailableSpaceCallback& callback); + void GetTemporaryGlobalQuota(const QuotaCallback& callback); + + // Ok to call with NULL callback. + void SetTemporaryGlobalOverrideQuota(int64 new_quota, + const QuotaCallback& callback); + + void GetPersistentHostQuota(const std::string& host, + const QuotaCallback& callback); + void SetPersistentHostQuota(const std::string& host, + int64 new_quota, + const QuotaCallback& callback); + void GetGlobalUsage(StorageType type, const GlobalUsageCallback& callback); + void GetHostUsage(const std::string& host, StorageType type, + const UsageCallback& callback); + void GetHostUsage(const std::string& host, StorageType type, + QuotaClient::ID client_id, + const UsageCallback& callback); + + bool IsTrackingHostUsage(StorageType type, QuotaClient::ID client_id) const; + + void GetStatistics(std::map<std::string, std::string>* statistics); + + bool IsStorageUnlimited(const GURL& origin, StorageType type) const; + + bool CanQueryDiskSize(const GURL& origin) const { + return special_storage_policy_.get() && + special_storage_policy_->CanQueryDiskSize(origin); + } + + virtual void GetOriginsModifiedSince(StorageType type, + base::Time modified_since, + const GetOriginsCallback& callback); + + bool ResetUsageTracker(StorageType type); + + // Used to register/deregister observers that wish to monitor storage events. + void AddStorageObserver(StorageObserver* observer, + const StorageObserver::MonitorParams& params); + void RemoveStorageObserver(StorageObserver* observer); + void RemoveStorageObserverForFilter(StorageObserver* observer, + const StorageObserver::Filter& filter); + + // Determines the portion of the temp pool that can be + // utilized by a single host (ie. 5 for 20%). + static const int kPerHostTemporaryPortion; + + static const int64 kPerHostPersistentQuotaLimit; + + static const char kDatabaseName[]; + + static const int kThresholdOfErrorsToBeBlacklisted; + + static const int kEvictionIntervalInMilliSeconds; + + // These are kept non-const so that test code can change the value. + // TODO(kinuko): Make this a real const value and add a proper way to set + // the quota for syncable storage. (http://crbug.com/155488) + static int64 kMinimumPreserveForSystem; + static int64 kSyncableStorageDefaultHostQuota; + + protected: + virtual ~QuotaManager(); + + private: + friend class base::DeleteHelper<QuotaManager>; + friend class base::RefCountedThreadSafe<QuotaManager, QuotaManagerDeleter>; + friend class content::QuotaManagerTest; + friend class content::StorageMonitorTest; + friend class content::MockQuotaManager; + friend class content::MockStorageClient; + friend class quota_internals::QuotaInternalsProxy; + friend class QuotaManagerProxy; + friend class QuotaTemporaryStorageEvictor; + friend struct QuotaManagerDeleter; + + class GetUsageInfoTask; + + class OriginDataDeleter; + class HostDataDeleter; + + class GetModifiedSinceHelper; + class DumpQuotaTableHelper; + class DumpOriginInfoTableHelper; + + typedef QuotaDatabase::QuotaTableEntry QuotaTableEntry; + typedef QuotaDatabase::OriginInfoTableEntry OriginInfoTableEntry; + typedef std::vector<QuotaTableEntry> QuotaTableEntries; + typedef std::vector<OriginInfoTableEntry> OriginInfoTableEntries; + + // Function pointer type used to store the function which returns the + // available disk space for the disk containing the given FilePath. + typedef int64 (*GetAvailableDiskSpaceFn)(const base::FilePath&); + + typedef base::Callback<void(const QuotaTableEntries&)> + DumpQuotaTableCallback; + typedef base::Callback<void(const OriginInfoTableEntries&)> + DumpOriginInfoTableCallback; + + struct EvictionContext { + EvictionContext(); + virtual ~EvictionContext(); + GURL evicted_origin; + StorageType evicted_type; + + EvictOriginDataCallback evict_origin_data_callback; + }; + + typedef QuotaEvictionHandler::UsageAndQuotaCallback + UsageAndQuotaDispatcherCallback; + + // This initialization method is lazily called on the IO thread + // when the first quota manager API is called. + // Initialize must be called after all quota clients are added to the + // manager by RegisterStorage. + void LazyInitialize(); + + // Called by clients via proxy. + // Registers a quota client to the manager. + // The client must remain valid until OnQuotaManagerDestored is called. + void RegisterClient(QuotaClient* client); + + UsageTracker* GetUsageTracker(StorageType type) const; + + // Extract cached origins list from the usage tracker. + // (Might return empty list if no origin is tracked by the tracker.) + void GetCachedOrigins(StorageType type, std::set<GURL>* origins); + + // These internal methods are separately defined mainly for testing. + void NotifyStorageAccessedInternal( + QuotaClient::ID client_id, + const GURL& origin, + StorageType type, + base::Time accessed_time); + void NotifyStorageModifiedInternal( + QuotaClient::ID client_id, + const GURL& origin, + StorageType type, + int64 delta, + base::Time modified_time); + + void DumpQuotaTable(const DumpQuotaTableCallback& callback); + void DumpOriginInfoTable(const DumpOriginInfoTableCallback& callback); + + // Methods for eviction logic. + void StartEviction(); + void DeleteOriginFromDatabase(const GURL& origin, StorageType type); + + void DidOriginDataEvicted(QuotaStatusCode status); + + void ReportHistogram(); + void DidGetTemporaryGlobalUsageForHistogram(int64 usage, + int64 unlimited_usage); + void DidGetPersistentGlobalUsageForHistogram(int64 usage, + int64 unlimited_usage); + + // QuotaEvictionHandler. + virtual void GetLRUOrigin( + StorageType type, + const GetLRUOriginCallback& callback) OVERRIDE; + virtual void EvictOriginData( + const GURL& origin, + StorageType type, + const EvictOriginDataCallback& callback) OVERRIDE; + virtual void GetUsageAndQuotaForEviction( + const UsageAndQuotaCallback& callback) OVERRIDE; + + void DidSetTemporaryGlobalOverrideQuota(const QuotaCallback& callback, + const int64* new_quota, + bool success); + void DidGetPersistentHostQuota(const std::string& host, + const int64* quota, + bool success); + void DidSetPersistentHostQuota(const std::string& host, + const QuotaCallback& callback, + const int64* new_quota, + bool success); + void DidInitialize(int64* temporary_quota_override, + int64* desired_available_space, + bool success); + void DidGetLRUOrigin(const GURL* origin, + bool success); + void DidGetInitialTemporaryGlobalQuota(QuotaStatusCode status, + int64 quota_unused); + void DidInitializeTemporaryOriginsInfo(bool success); + void DidGetAvailableSpace(int64 space); + void DidDatabaseWork(bool success); + + void DeleteOnCorrectThread() const; + + void PostTaskAndReplyWithResultForDBThread( + const tracked_objects::Location& from_here, + const base::Callback<bool(QuotaDatabase*)>& task, + const base::Callback<void(bool)>& reply); + + const bool is_incognito_; + const base::FilePath profile_path_; + + scoped_refptr<QuotaManagerProxy> proxy_; + bool db_disabled_; + bool eviction_disabled_; + scoped_refptr<base::SingleThreadTaskRunner> io_thread_; + scoped_refptr<base::SequencedTaskRunner> db_thread_; + mutable scoped_ptr<QuotaDatabase> database_; + + GetLRUOriginCallback lru_origin_callback_; + std::set<GURL> access_notified_origins_; + + QuotaClientList clients_; + + scoped_ptr<UsageTracker> temporary_usage_tracker_; + scoped_ptr<UsageTracker> persistent_usage_tracker_; + scoped_ptr<UsageTracker> syncable_usage_tracker_; + // TODO(michaeln): Need a way to clear the cache, drop and + // reinstantiate the trackers when they're not handling requests. + + scoped_ptr<QuotaTemporaryStorageEvictor> temporary_storage_evictor_; + EvictionContext eviction_context_; + + ClosureQueue db_initialization_callbacks_; + AvailableSpaceCallbackQueue available_space_callbacks_; + GlobalQuotaCallbackQueue temporary_global_quota_callbacks_; + HostQuotaCallbackMap persistent_host_quota_callbacks_; + + bool temporary_quota_initialized_; + int64 temporary_quota_override_; + + int64 desired_available_space_; + + // Map from origin to count. + std::map<GURL, int> origins_in_use_; + // Map from origin to error count. + std::map<GURL, int> origins_in_error_; + + scoped_refptr<SpecialStoragePolicy> special_storage_policy_; + + base::RepeatingTimer<QuotaManager> histogram_timer_; + + // Pointer to the function used to get the available disk space. This is + // overwritten by QuotaManagerTest in order to attain a deterministic reported + // value. The default value points to base::SysInfo::AmountOfFreeDiskSpace. + GetAvailableDiskSpaceFn get_disk_space_fn_; + + scoped_ptr<StorageMonitor> storage_monitor_; + + base::WeakPtrFactory<QuotaManager> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(QuotaManager); +}; + +struct QuotaManagerDeleter { + static void Destruct(const QuotaManager* manager) { + manager->DeleteOnCorrectThread(); + } +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_QUOTA_QUOTA_MANAGER_H_ diff --git a/webkit/browser/quota/quota_manager_proxy.cc b/storage/browser/quota/quota_manager_proxy.cc index 499535e..c044258 100644 --- a/webkit/browser/quota/quota_manager_proxy.cc +++ b/storage/browser/quota/quota_manager_proxy.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/quota/quota_manager_proxy.h" +#include "storage/browser/quota/quota_manager_proxy.h" #include "base/bind.h" #include "base/bind_helpers.h" diff --git a/storage/browser/quota/quota_manager_proxy.h b/storage/browser/quota/quota_manager_proxy.h new file mode 100644 index 0000000..bf9d9ca --- /dev/null +++ b/storage/browser/quota/quota_manager_proxy.h @@ -0,0 +1,79 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_QUOTA_QUOTA_MANAGER_PROXY_H_ +#define STORAGE_BROWSER_QUOTA_QUOTA_MANAGER_PROXY_H_ + +#include "base/basictypes.h" +#include "base/callback.h" +#include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "base/sequenced_task_runner_helpers.h" +#include "storage/browser/quota/quota_callbacks.h" +#include "storage/browser/quota/quota_client.h" +#include "storage/browser/quota/quota_database.h" +#include "storage/browser/quota/quota_manager.h" +#include "storage/browser/quota/quota_task.h" +#include "storage/browser/quota/special_storage_policy.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class SequencedTaskRunner; +class SingleThreadTaskRunner; +} + +namespace storage { + +// The proxy may be called and finally released on any thread. +class STORAGE_EXPORT QuotaManagerProxy + : public base::RefCountedThreadSafe<QuotaManagerProxy> { + public: + typedef QuotaManager::GetUsageAndQuotaCallback + GetUsageAndQuotaCallback; + + virtual void RegisterClient(QuotaClient* client); + virtual void NotifyStorageAccessed(QuotaClient::ID client_id, + const GURL& origin, + StorageType type); + virtual void NotifyStorageModified(QuotaClient::ID client_id, + const GURL& origin, + StorageType type, + int64 delta); + virtual void NotifyOriginInUse(const GURL& origin); + virtual void NotifyOriginNoLongerInUse(const GURL& origin); + + virtual void SetUsageCacheEnabled(QuotaClient::ID client_id, + const GURL& origin, + StorageType type, + bool enabled); + virtual void GetUsageAndQuota( + base::SequencedTaskRunner* original_task_runner, + const GURL& origin, + StorageType type, + const GetUsageAndQuotaCallback& callback); + + // This method may only be called on the IO thread. + // It may return NULL if the manager has already been deleted. + QuotaManager* quota_manager() const; + + protected: + friend class QuotaManager; + friend class base::RefCountedThreadSafe<QuotaManagerProxy>; + + QuotaManagerProxy( + QuotaManager* manager, + const scoped_refptr<base::SingleThreadTaskRunner>& io_thread); + virtual ~QuotaManagerProxy(); + + QuotaManager* manager_; // only accessed on the io thread + scoped_refptr<base::SingleThreadTaskRunner> io_thread_; + + DISALLOW_COPY_AND_ASSIGN(QuotaManagerProxy); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_QUOTA_QUOTA_MANAGER_PROXY_H_ diff --git a/webkit/browser/quota/quota_task.cc b/storage/browser/quota/quota_task.cc index 98594a9..b8d4ed1 100644 --- a/webkit/browser/quota/quota_task.cc +++ b/storage/browser/quota/quota_task.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/quota/quota_task.h" +#include "storage/browser/quota/quota_task.h" #include <algorithm> #include <functional> diff --git a/storage/browser/quota/quota_task.h b/storage/browser/quota/quota_task.h new file mode 100644 index 0000000..35e004e --- /dev/null +++ b/storage/browser/quota/quota_task.h @@ -0,0 +1,79 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_QUOTA_QUOTA_TASK_H_ +#define STORAGE_BROWSER_QUOTA_QUOTA_TASK_H_ + +#include <set> + +#include "base/basictypes.h" +#include "base/compiler_specific.h" +#include "base/memory/ref_counted.h" +#include "base/sequenced_task_runner_helpers.h" +#include "storage/browser/storage_browser_export.h" + +namespace base { +class SingleThreadTaskRunner; +class TaskRunner; +} + +namespace storage { + +class QuotaTaskObserver; + +// A base class for quota tasks. +// TODO(kinuko): Revise this using base::Callback. +class QuotaTask { + public: + void Start(); + + protected: + explicit QuotaTask(QuotaTaskObserver* observer); + virtual ~QuotaTask(); + + // The task body. + virtual void Run() = 0; + + // Called upon completion, on the original message loop. + virtual void Completed() = 0; + + // Called when the task is aborted. + virtual void Aborted() {} + + void CallCompleted(); + + // Call this to delete itself. + void DeleteSoon(); + + QuotaTaskObserver* observer() const { return observer_; } + base::SingleThreadTaskRunner* original_task_runner() const { + return original_task_runner_.get(); + } + + private: + friend class base::DeleteHelper<QuotaTask>; + friend class QuotaTaskObserver; + + void Abort(); + QuotaTaskObserver* observer_; + scoped_refptr<base::SingleThreadTaskRunner> original_task_runner_; + bool delete_scheduled_; +}; + +class STORAGE_EXPORT QuotaTaskObserver { + protected: + friend class QuotaTask; + + QuotaTaskObserver(); + virtual ~QuotaTaskObserver(); + + void RegisterTask(QuotaTask* task); + void UnregisterTask(QuotaTask* task); + + typedef std::set<QuotaTask*> TaskSet; + TaskSet running_quota_tasks_; +}; +} + +#endif // STORAGE_BROWSER_QUOTA_QUOTA_TASK_H_ diff --git a/webkit/browser/quota/quota_temporary_storage_evictor.cc b/storage/browser/quota/quota_temporary_storage_evictor.cc index 3eaad3f..cb4c504 100644 --- a/webkit/browser/quota/quota_temporary_storage_evictor.cc +++ b/storage/browser/quota/quota_temporary_storage_evictor.cc @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/quota/quota_temporary_storage_evictor.h" +#include "storage/browser/quota/quota_temporary_storage_evictor.h" #include <algorithm> #include "base/bind.h" #include "base/metrics/histogram.h" +#include "storage/browser/quota/quota_manager.h" #include "url/gurl.h" -#include "webkit/browser/quota/quota_manager.h" #define UMA_HISTOGRAM_MBYTES(name, sample) \ UMA_HISTOGRAM_CUSTOM_COUNTS( \ diff --git a/storage/browser/quota/quota_temporary_storage_evictor.h b/storage/browser/quota/quota_temporary_storage_evictor.h new file mode 100644 index 0000000..706355d --- /dev/null +++ b/storage/browser/quota/quota_temporary_storage_evictor.h @@ -0,0 +1,134 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_QUOTA_QUOTA_TEMPORARY_STORAGE_EVICTOR_H_ +#define STORAGE_BROWSER_QUOTA_QUOTA_TEMPORARY_STORAGE_EVICTOR_H_ + +#include <map> +#include <string> + +#include "base/memory/weak_ptr.h" +#include "base/threading/non_thread_safe.h" +#include "base/timer/timer.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/quota/quota_types.h" + +class GURL; + +namespace content { +class QuotaTemporaryStorageEvictorTest; +} + +namespace storage { + +class QuotaEvictionHandler; +struct UsageAndQuota; + +class STORAGE_EXPORT_PRIVATE QuotaTemporaryStorageEvictor + : public base::NonThreadSafe { + public: + struct Statistics { + Statistics() + : num_errors_on_evicting_origin(0), + num_errors_on_getting_usage_and_quota(0), + num_evicted_origins(0), + num_eviction_rounds(0), + num_skipped_eviction_rounds(0) {} + int64 num_errors_on_evicting_origin; + int64 num_errors_on_getting_usage_and_quota; + int64 num_evicted_origins; + int64 num_eviction_rounds; + int64 num_skipped_eviction_rounds; + + void subtract_assign(const Statistics& rhs) { + num_errors_on_evicting_origin -= rhs.num_errors_on_evicting_origin; + num_errors_on_getting_usage_and_quota -= + rhs.num_errors_on_getting_usage_and_quota; + num_evicted_origins -= rhs.num_evicted_origins; + num_eviction_rounds -= rhs.num_eviction_rounds; + num_skipped_eviction_rounds -= rhs.num_skipped_eviction_rounds; + } + }; + + struct EvictionRoundStatistics { + EvictionRoundStatistics(); + + bool in_round; + bool is_initialized; + + base::Time start_time; + int64 usage_overage_at_round; + int64 diskspace_shortage_at_round; + + int64 usage_on_beginning_of_round; + int64 usage_on_end_of_round; + int64 num_evicted_origins_in_round; + }; + + QuotaTemporaryStorageEvictor( + QuotaEvictionHandler* quota_eviction_handler, + int64 interval_ms); + virtual ~QuotaTemporaryStorageEvictor(); + + void GetStatistics(std::map<std::string, int64>* statistics); + void ReportPerRoundHistogram(); + void ReportPerHourHistogram(); + void Start(); + + int64 min_available_disk_space_to_start_eviction() { + return min_available_disk_space_to_start_eviction_; + } + void reset_min_available_disk_space_to_start_eviction() { + min_available_disk_space_to_start_eviction_ = + kMinAvailableDiskSpaceToStartEvictionNotSpecified; + } + void set_min_available_disk_space_to_start_eviction(int64 value) { + min_available_disk_space_to_start_eviction_ = value; + } + + private: + friend class content::QuotaTemporaryStorageEvictorTest; + + void StartEvictionTimerWithDelay(int delay_ms); + void ConsiderEviction(); + void OnGotUsageAndQuotaForEviction( + QuotaStatusCode status, + const UsageAndQuota& quota_and_usage); + void OnGotLRUOrigin(const GURL& origin); + void OnEvictionComplete(QuotaStatusCode status); + + void OnEvictionRoundStarted(); + void OnEvictionRoundFinished(); + + // This is only used for tests. + void set_repeated_eviction(bool repeated_eviction) { + repeated_eviction_ = repeated_eviction; + } + + static const int kMinAvailableDiskSpaceToStartEvictionNotSpecified; + + int64 min_available_disk_space_to_start_eviction_; + + // Not owned; quota_eviction_handler owns us. + QuotaEvictionHandler* quota_eviction_handler_; + + Statistics statistics_; + Statistics previous_statistics_; + EvictionRoundStatistics round_statistics_; + base::Time time_of_end_of_last_nonskipped_round_; + base::Time time_of_end_of_last_round_; + + int64 interval_ms_; + bool repeated_eviction_; + + base::OneShotTimer<QuotaTemporaryStorageEvictor> eviction_timer_; + base::RepeatingTimer<QuotaTemporaryStorageEvictor> histogram_timer_; + base::WeakPtrFactory<QuotaTemporaryStorageEvictor> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(QuotaTemporaryStorageEvictor); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_QUOTA_QUOTA_TEMPORARY_STORAGE_EVICTOR_H_ diff --git a/webkit/browser/quota/special_storage_policy.cc b/storage/browser/quota/special_storage_policy.cc index eac7ba0..6e77450 100644 --- a/webkit/browser/quota/special_storage_policy.cc +++ b/storage/browser/quota/special_storage_policy.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/quota/special_storage_policy.h" +#include "storage/browser/quota/special_storage_policy.h" namespace storage { diff --git a/storage/browser/quota/special_storage_policy.h b/storage/browser/quota/special_storage_policy.h new file mode 100644 index 0000000..e6c37b5 --- /dev/null +++ b/storage/browser/quota/special_storage_policy.h @@ -0,0 +1,86 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_QUOTA_SPECIAL_STORAGE_POLICY_H_ +#define STORAGE_BROWSER_QUOTA_SPECIAL_STORAGE_POLICY_H_ + +#include <string> + +#include "base/memory/ref_counted.h" +#include "base/observer_list.h" +#include "storage/browser/storage_browser_export.h" + +class GURL; + +namespace storage { + +// Special rights are granted to 'extensions' and 'applications'. The +// storage subsystems query this interface to determine which origins +// have these rights. Chrome provides an impl that is cognizant of what +// is currently installed in the extensions system. +// The IsSomething() methods must be thread-safe, however Observers should +// only be notified, added, and removed on the IO thead. +class STORAGE_EXPORT SpecialStoragePolicy + : public base::RefCountedThreadSafe<SpecialStoragePolicy> { + public: + typedef int StoragePolicy; + enum ChangeFlags { + STORAGE_PROTECTED = 1 << 0, + STORAGE_UNLIMITED = 1 << 1, + }; + + class STORAGE_EXPORT Observer { + public: + virtual void OnGranted(const GURL& origin, int change_flags) = 0; + virtual void OnRevoked(const GURL& origin, int change_flags) = 0; + virtual void OnCleared() = 0; + + protected: + virtual ~Observer(); + }; + + SpecialStoragePolicy(); + + // Protected storage is not subject to removal by the browsing data remover. + virtual bool IsStorageProtected(const GURL& origin) = 0; + + // Unlimited storage is not subject to 'quotas'. + virtual bool IsStorageUnlimited(const GURL& origin) = 0; + + // Some origins (e.g. installed apps) have access to the size of the remaining + // disk capacity. + virtual bool CanQueryDiskSize(const GURL& origin) = 0; + + // Checks if extension identified with |extension_id| is registered as + // file handler. + virtual bool IsFileHandler(const std::string& extension_id) = 0; + + // Checks if the origin contains per-site isolated storage. + virtual bool HasIsolatedStorage(const GURL& origin) = 0; + + // Some origins are only allowed to store session-only data which is deleted + // when the session ends. + virtual bool IsStorageSessionOnly(const GURL& origin) = 0; + + // Returns true if some origins are only allowed session-only storage. + virtual bool HasSessionOnlyOrigins() = 0; + + // Adds/removes an observer, the policy does not take + // ownership of the observer. Should only be called on the IO thread. + void AddObserver(Observer* observer); + void RemoveObserver(Observer* observer); + + protected: + friend class base::RefCountedThreadSafe<SpecialStoragePolicy>; + virtual ~SpecialStoragePolicy(); + void NotifyGranted(const GURL& origin, int change_flags); + void NotifyRevoked(const GURL& origin, int change_flags); + void NotifyCleared(); + + ObserverList<Observer> observers_; +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_QUOTA_SPECIAL_STORAGE_POLICY_H_ diff --git a/webkit/browser/quota/storage_monitor.cc b/storage/browser/quota/storage_monitor.cc index 366d4d7..f312bd3 100644 --- a/webkit/browser/quota/storage_monitor.cc +++ b/storage/browser/quota/storage_monitor.cc @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/quota/storage_monitor.h" +#include "storage/browser/quota/storage_monitor.h" #include <algorithm> #include "base/stl_util.h" #include "net/base/net_util.h" -#include "webkit/browser/quota/quota_manager.h" -#include "webkit/common/quota/quota_status_code.h" +#include "storage/browser/quota/quota_manager.h" +#include "storage/common/quota/quota_status_code.h" namespace storage { diff --git a/storage/browser/quota/storage_monitor.h b/storage/browser/quota/storage_monitor.h new file mode 100644 index 0000000..650c7b1 --- /dev/null +++ b/storage/browser/quota/storage_monitor.h @@ -0,0 +1,180 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_QUOTA_STORAGE_MONITOR_H_ +#define STORAGE_BROWSER_QUOTA_STORAGE_MONITOR_H_ + +#include <map> + +#include "base/memory/weak_ptr.h" +#include "base/time/time.h" +#include "base/timer/timer.h" +#include "storage/browser/quota/storage_observer.h" + +namespace content { +class StorageMonitorTestBase; +} + +namespace storage { + +class QuotaManager; + +// This class dispatches storage events to observers of a common +// StorageObserver::Filter. +class STORAGE_EXPORT_PRIVATE StorageObserverList { + public: + StorageObserverList(); + virtual ~StorageObserverList(); + + // Adds/removes an observer. + void AddObserver(StorageObserver* observer, + const StorageObserver::MonitorParams& params); + void RemoveObserver(StorageObserver* observer); + + // Returns the number of observers. + int ObserverCount() const; + + // Forwards a storage change to observers. The event may be dispatched + // immediately to an observer or after a delay, depending on the desired event + // rate of the observer. + void OnStorageChange(const StorageObserver::Event& event); + + // Dispatch an event to observers that require it. + void MaybeDispatchEvent(const StorageObserver::Event& event); + + // Ensure the specified observer receives the next dispatched event. + void ScheduleUpdateForObserver(StorageObserver* observer); + + private: + struct STORAGE_EXPORT_PRIVATE ObserverState { + GURL origin; + base::TimeTicks last_notification_time; + base::TimeDelta rate; + bool requires_update; + + ObserverState(); + }; + typedef std::map<StorageObserver*, ObserverState> StorageObserverStateMap; + + void DispatchPendingEvent(); + + StorageObserverStateMap observers_; + base::OneShotTimer<StorageObserverList> notification_timer_; + StorageObserver::Event pending_event_; + + friend class content::StorageMonitorTestBase; + + DISALLOW_COPY_AND_ASSIGN(StorageObserverList); +}; + + +// Manages the storage observers of a common host. Caches the usage and quota of +// the host to avoid accumulating for every change. +class STORAGE_EXPORT_PRIVATE HostStorageObservers { + public: + explicit HostStorageObservers(QuotaManager* quota_manager); + virtual ~HostStorageObservers(); + + bool is_initialized() const { return initialized_; } + + // Adds/removes an observer. + void AddObserver( + StorageObserver* observer, + const StorageObserver::MonitorParams& params); + void RemoveObserver(StorageObserver* observer); + bool ContainsObservers() const; + + // Handles a usage change. + void NotifyUsageChange(const StorageObserver::Filter& filter, int64 delta); + + private: + void StartInitialization(const StorageObserver::Filter& filter); + void GotHostUsageAndQuota(const StorageObserver::Filter& filter, + QuotaStatusCode status, + int64 usage, + int64 quota); + void DispatchEvent(const StorageObserver::Filter& filter, bool is_update); + + QuotaManager* quota_manager_; + StorageObserverList observers_; + + // Flags used during initialization of the cached properties. + bool initialized_; + bool initializing_; + bool event_occurred_before_init_; + int64 usage_deltas_during_init_; + + // Cached accumulated usage and quota for the host. + int64 cached_usage_; + int64 cached_quota_; + + base::WeakPtrFactory<HostStorageObservers> weak_factory_; + + friend class content::StorageMonitorTestBase; + + DISALLOW_COPY_AND_ASSIGN(HostStorageObservers); +}; + + +// Manages the observers of a common storage type. +class STORAGE_EXPORT_PRIVATE StorageTypeObservers { + public: + explicit StorageTypeObservers(QuotaManager* quota_manager); + virtual ~StorageTypeObservers(); + + // Adds and removes an observer. + void AddObserver(StorageObserver* observer, + const StorageObserver::MonitorParams& params); + void RemoveObserver(StorageObserver* observer); + void RemoveObserverForFilter(StorageObserver* observer, + const StorageObserver::Filter& filter); + + // Returns the observers of a specific host. + const HostStorageObservers* GetHostObservers(const std::string& host) const; + + // Handles a usage change. + void NotifyUsageChange(const StorageObserver::Filter& filter, int64 delta); + + private: + typedef std::map<std::string, HostStorageObservers*> HostObserversMap; + + QuotaManager* quota_manager_; + HostObserversMap host_observers_map_; + + DISALLOW_COPY_AND_ASSIGN(StorageTypeObservers); +}; + + +// Storage monitor manages observers and dispatches storage events to them. +class STORAGE_EXPORT_PRIVATE StorageMonitor { + public: + explicit StorageMonitor(QuotaManager* quota_manager); + virtual ~StorageMonitor(); + + // Adds and removes an observer. + void AddObserver(StorageObserver* observer, + const StorageObserver::MonitorParams& params); + void RemoveObserver(StorageObserver* observer); + void RemoveObserverForFilter(StorageObserver* observer, + const StorageObserver::Filter& filter); + + // Returns the observers of a specific storage type. + const StorageTypeObservers* GetStorageTypeObservers( + StorageType storage_type) const; + + // Handles a usage change. + void NotifyUsageChange(const StorageObserver::Filter& filter, int64 delta); + + private: + typedef std::map<StorageType, StorageTypeObservers*> StorageTypeObserversMap; + + QuotaManager* quota_manager_; + StorageTypeObserversMap storage_type_observers_map_; + + DISALLOW_COPY_AND_ASSIGN(StorageMonitor); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_QUOTA_STORAGE_MONITOR_H_ diff --git a/webkit/browser/quota/storage_observer.cc b/storage/browser/quota/storage_observer.cc index ec0fe23..986b639 100644 --- a/webkit/browser/quota/storage_observer.cc +++ b/storage/browser/quota/storage_observer.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/quota/storage_observer.h" +#include "storage/browser/quota/storage_observer.h" namespace storage { diff --git a/storage/browser/quota/storage_observer.h b/storage/browser/quota/storage_observer.h new file mode 100644 index 0000000..729dadd --- /dev/null +++ b/storage/browser/quota/storage_observer.h @@ -0,0 +1,79 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_QUOTA_STORAGE_OBSERVER_H_ +#define STORAGE_BROWSER_QUOTA_STORAGE_OBSERVER_H_ + +#include "base/basictypes.h" +#include "base/time/time.h" +#include "storage/browser/quota/quota_client.h" +#include "storage/common/quota/quota_types.h" +#include "url/gurl.h" + +namespace storage { + +// This interface is implemented by observers that wish to monitor storage +// events, such as changes in quota or usage. +class STORAGE_EXPORT StorageObserver { + public: + struct STORAGE_EXPORT Filter { + // The storage type to monitor. This must not be kStorageTypeUnknown or + // kStorageTypeQuotaNotManaged. + StorageType storage_type; + + // The origin to monitor usage for. Must be specified. + GURL origin; + + Filter(); + Filter(StorageType storage_type, const GURL& origin); + bool operator==(const Filter& other) const; + }; + + struct STORAGE_EXPORT MonitorParams { + // Storage type and origin to monitor. + Filter filter; + + // The rate at which storage events will be fired. Events will be fired at + // approximately this rate, or when a storage status change has been + // detected, whichever is the least frequent. + base::TimeDelta rate; + + // If set to true, the observer will be dispatched an event when added. + bool dispatch_initial_state; + + MonitorParams(); + MonitorParams(StorageType storage_type, + const GURL& origin, + const base::TimeDelta& rate, + bool get_initial_state); + MonitorParams(const Filter& filter, + const base::TimeDelta& rate, + bool get_initial_state); + }; + + struct STORAGE_EXPORT Event { + // The storage type and origin monitored. + Filter filter; + + // The current usage corresponding to the filter. + int64 usage; + + // The quota corresponding to the filter. + int64 quota; + + Event(); + Event(const Filter& filter, int64 usage, int64 quota); + bool operator==(const Event& other) const; + }; + + // Will be called on the IO thread when a storage event occurs. + virtual void OnStorageEvent(const Event& event) = 0; + + protected: + virtual ~StorageObserver() {} +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_QUOTA_STORAGE_OBSERVER_H_ diff --git a/webkit/browser/quota/usage_tracker.cc b/storage/browser/quota/usage_tracker.cc index c2aa4c6..1c222bc 100644 --- a/webkit/browser/quota/usage_tracker.cc +++ b/storage/browser/quota/usage_tracker.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "webkit/browser/quota/usage_tracker.h" +#include "storage/browser/quota/usage_tracker.h" #include <algorithm> #include <deque> @@ -14,8 +14,8 @@ #include "base/message_loop/message_loop_proxy.h" #include "base/stl_util.h" #include "net/base/net_util.h" -#include "webkit/browser/quota/storage_monitor.h" -#include "webkit/browser/quota/storage_observer.h" +#include "storage/browser/quota/storage_monitor.h" +#include "storage/browser/quota/storage_observer.h" namespace storage { diff --git a/storage/browser/quota/usage_tracker.h b/storage/browser/quota/usage_tracker.h new file mode 100644 index 0000000..fda1151 --- /dev/null +++ b/storage/browser/quota/usage_tracker.h @@ -0,0 +1,202 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_QUOTA_USAGE_TRACKER_H_ +#define STORAGE_BROWSER_QUOTA_USAGE_TRACKER_H_ + +#include <list> +#include <map> +#include <set> +#include <string> + +#include "base/basictypes.h" +#include "base/callback.h" +#include "base/memory/scoped_ptr.h" +#include "base/threading/non_thread_safe.h" +#include "storage/browser/quota/quota_callbacks.h" +#include "storage/browser/quota/quota_client.h" +#include "storage/browser/quota/quota_task.h" +#include "storage/browser/quota/special_storage_policy.h" +#include "storage/browser/storage_browser_export.h" +#include "storage/common/quota/quota_types.h" +#include "url/gurl.h" + +namespace storage { + +class ClientUsageTracker; +class StorageMonitor; + +// A helper class that gathers and tracks the amount of data stored in +// all quota clients. +// An instance of this class is created per storage type. +class STORAGE_EXPORT UsageTracker : public QuotaTaskObserver { + public: + UsageTracker(const QuotaClientList& clients, StorageType type, + SpecialStoragePolicy* special_storage_policy, + StorageMonitor* storage_monitor); + virtual ~UsageTracker(); + + StorageType type() const { return type_; } + ClientUsageTracker* GetClientTracker(QuotaClient::ID client_id); + + void GetGlobalLimitedUsage(const UsageCallback& callback); + void GetGlobalUsage(const GlobalUsageCallback& callback); + void GetHostUsage(const std::string& host, const UsageCallback& callback); + void UpdateUsageCache(QuotaClient::ID client_id, + const GURL& origin, + int64 delta); + void GetCachedHostsUsage(std::map<std::string, int64>* host_usage) const; + void GetCachedOrigins(std::set<GURL>* origins) const; + bool IsWorking() const { + return global_usage_callbacks_.HasCallbacks() || + host_usage_callbacks_.HasAnyCallbacks(); + } + + void SetUsageCacheEnabled(QuotaClient::ID client_id, + const GURL& origin, + bool enabled); + + private: + struct AccumulateInfo { + AccumulateInfo() : pending_clients(0), usage(0), unlimited_usage(0) {} + int pending_clients; + int64 usage; + int64 unlimited_usage; + }; + + typedef std::map<QuotaClient::ID, ClientUsageTracker*> ClientTrackerMap; + + friend class ClientUsageTracker; + void AccumulateClientGlobalLimitedUsage(AccumulateInfo* info, + int64 limited_usage); + void AccumulateClientGlobalUsage(AccumulateInfo* info, + int64 usage, + int64 unlimited_usage); + void AccumulateClientHostUsage(AccumulateInfo* info, + const std::string& host, + int64 usage); + + const StorageType type_; + ClientTrackerMap client_tracker_map_; + + UsageCallbackQueue global_limited_usage_callbacks_; + GlobalUsageCallbackQueue global_usage_callbacks_; + HostUsageCallbackMap host_usage_callbacks_; + + StorageMonitor* storage_monitor_; + + base::WeakPtrFactory<UsageTracker> weak_factory_; + DISALLOW_COPY_AND_ASSIGN(UsageTracker); +}; + +// This class holds per-client usage tracking information and caches per-host +// usage data. An instance of this class is created per client. +class ClientUsageTracker : public SpecialStoragePolicy::Observer, + public base::NonThreadSafe, + public base::SupportsWeakPtr<ClientUsageTracker> { + public: + typedef base::Callback<void(int64 limited_usage, + int64 unlimited_usage)> HostUsageAccumulator; + typedef base::Callback<void(const GURL& origin, + int64 usage)> OriginUsageAccumulator; + typedef std::map<std::string, std::set<GURL> > OriginSetByHost; + + ClientUsageTracker(UsageTracker* tracker, + QuotaClient* client, + StorageType type, + SpecialStoragePolicy* special_storage_policy, + StorageMonitor* storage_monitor); + virtual ~ClientUsageTracker(); + + void GetGlobalLimitedUsage(const UsageCallback& callback); + void GetGlobalUsage(const GlobalUsageCallback& callback); + void GetHostUsage(const std::string& host, const UsageCallback& callback); + void UpdateUsageCache(const GURL& origin, int64 delta); + void GetCachedHostsUsage(std::map<std::string, int64>* host_usage) const; + void GetCachedOrigins(std::set<GURL>* origins) const; + int64 GetCachedOriginsUsage(const std::set<GURL>& origins, + std::vector<GURL>* origins_not_in_cache); + bool IsUsageCacheEnabledForOrigin(const GURL& origin) const; + void SetUsageCacheEnabled(const GURL& origin, bool enabled); + + private: + typedef CallbackQueueMap<HostUsageAccumulator, std::string, + Tuple2<int64, int64> > HostUsageAccumulatorMap; + + typedef std::set<std::string> HostSet; + typedef std::map<GURL, int64> UsageMap; + typedef std::map<std::string, UsageMap> HostUsageMap; + + struct AccumulateInfo { + int pending_jobs; + int64 limited_usage; + int64 unlimited_usage; + + AccumulateInfo() + : pending_jobs(0), limited_usage(0), unlimited_usage(0) {} + }; + + void AccumulateLimitedOriginUsage(AccumulateInfo* info, + const UsageCallback& callback, + int64 usage); + void DidGetOriginsForGlobalUsage(const GlobalUsageCallback& callback, + const std::set<GURL>& origins); + void AccumulateHostUsage(AccumulateInfo* info, + const GlobalUsageCallback& callback, + int64 limited_usage, + int64 unlimited_usage); + + void DidGetOriginsForHostUsage(const std::string& host, + const std::set<GURL>& origins); + + void GetUsageForOrigins(const std::string& host, + const std::set<GURL>& origins); + void AccumulateOriginUsage(AccumulateInfo* info, + const std::string& host, + const GURL& origin, + int64 usage); + + void DidGetHostUsageAfterUpdate(const GURL& origin, int64 usage); + + // Methods used by our GatherUsage tasks, as a task makes progress + // origins and hosts are added incrementally to the cache. + void AddCachedOrigin(const GURL& origin, int64 usage); + void AddCachedHost(const std::string& host); + + int64 GetCachedHostUsage(const std::string& host) const; + int64 GetCachedGlobalUnlimitedUsage(); + bool GetCachedOriginUsage(const GURL& origin, int64* usage) const; + + // SpecialStoragePolicy::Observer overrides + virtual void OnGranted(const GURL& origin, int change_flags) OVERRIDE; + virtual void OnRevoked(const GURL& origin, int change_flags) OVERRIDE; + virtual void OnCleared() OVERRIDE; + + bool IsStorageUnlimited(const GURL& origin) const; + + UsageTracker* tracker_; + QuotaClient* client_; + const StorageType type_; + StorageMonitor* storage_monitor_; + + int64 global_limited_usage_; + int64 global_unlimited_usage_; + bool global_usage_retrieved_; + HostSet cached_hosts_; + HostUsageMap cached_usage_by_host_; + + OriginSetByHost non_cached_limited_origins_by_host_; + OriginSetByHost non_cached_unlimited_origins_by_host_; + + GlobalUsageCallbackQueue global_usage_callback_; + HostUsageAccumulatorMap host_usage_accumulators_; + + scoped_refptr<SpecialStoragePolicy> special_storage_policy_; + + DISALLOW_COPY_AND_ASSIGN(ClientUsageTracker); +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_QUOTA_USAGE_TRACKER_H_ diff --git a/storage/browser/storage_browser_export.h b/storage/browser/storage_browser_export.h new file mode 100644 index 0000000..c6d6a37 --- /dev/null +++ b/storage/browser/storage_browser_export.h @@ -0,0 +1,34 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_STORAGE_BROWSER_EXPORT_H__ +#define STORAGE_BROWSER_STORAGE_BROWSER_EXPORT_H__ + +#if defined(COMPONENT_BUILD) +#if defined(WIN32) + +#if defined(STORAGE_BROWSER_IMPLEMENTATION) +#define STORAGE_EXPORT __declspec(dllexport) +#define STORAGE_EXPORT_PRIVATE __declspec(dllexport) +#else +#define STORAGE_EXPORT __declspec(dllimport) +#define STORAGE_EXPORT_PRIVATE __declspec(dllimport) +#endif // defined(STORAGE_BROWSER_IMPLEMENTATION) + +#else // defined(WIN32) +#if defined(STORAGE_BROWSER_IMPLEMENTATION) +#define STORAGE_EXPORT __attribute__((visibility("default"))) +#define STORAGE_EXPORT_PRIVATE __attribute__((visibility("default"))) +#else +#define STORAGE_EXPORT +#define STORAGE_EXPORT_PRIVATE +#endif +#endif + +#else // defined(COMPONENT_BUILD) +#define STORAGE_EXPORT +#define STORAGE_EXPORT_PRIVATE +#endif + +#endif // STORAGE_BROWSER_STORAGE_BROWSER_EXPORT_H__ diff --git a/webkit/storage_browser.gyp b/storage/storage_browser.gyp index ed08918..afa0b47 100644 --- a/webkit/storage_browser.gyp +++ b/storage/storage_browser.gyp @@ -8,7 +8,7 @@ }, 'targets': [ { - # GN version: //webkit/browser:storage + # GN version: //storage/browser 'target_name': 'storage', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, }, diff --git a/webkit/browser/blob/blob_data_handle.h b/webkit/browser/blob/blob_data_handle.h index cb1e365..6e06b88 100644 --- a/webkit/browser/blob/blob_data_handle.h +++ b/webkit/browser/blob/blob_data_handle.h @@ -1,71 +1,5 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_BLOB_BLOB_DATA_HANDLE_H_ -#define WEBKIT_BROWSER_BLOB_BLOB_DATA_HANDLE_H_ - -#include <string> - -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/supports_user_data.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace storage { - -class BlobData; -class BlobStorageContext; - -// A scoper object for use in chrome's main browser process, ensures -// the underlying BlobData and its uuid remain in BlobStorageContext's -// collection for the duration. This object has delete semantics and -// maybe deleted on any thread. -class STORAGE_EXPORT BlobDataHandle - : public base::SupportsUserData::Data { - public: - BlobDataHandle(const BlobDataHandle& other); // May be copied on any thread. - virtual ~BlobDataHandle(); // Maybe be deleted on any thread. - BlobData* data() const; // May only be accessed on the IO thread. - - std::string uuid() const; // May be accessed on any thread. - - private: - class BlobDataHandleShared - : public base::RefCountedThreadSafe<BlobDataHandleShared> { - public: - BlobDataHandleShared(BlobData* blob_data, - BlobStorageContext* context, - base::SequencedTaskRunner* task_runner); - - BlobData* data() const; - const std::string& uuid() const; - - private: - friend class base::DeleteHelper<BlobDataHandleShared>; - friend class base::RefCountedThreadSafe<BlobDataHandleShared>; - friend class BlobDataHandle; - - virtual ~BlobDataHandleShared(); - - scoped_refptr<BlobData> blob_data_; - base::WeakPtr<BlobStorageContext> context_; - - DISALLOW_COPY_AND_ASSIGN(BlobDataHandleShared); - }; - - friend class BlobStorageContext; - BlobDataHandle(BlobData* blob_data, BlobStorageContext* context, - base::SequencedTaskRunner* task_runner); - - scoped_refptr<base::SequencedTaskRunner> io_task_runner_; - scoped_refptr<BlobDataHandleShared> shared_; -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_BLOB_BLOB_DATA_HANDLE_H_ +#include "storage/browser/blob/blob_data_handle.h" diff --git a/webkit/browser/blob/blob_storage_context.h b/webkit/browser/blob/blob_storage_context.h index 32b7ea0..1a34b70 100644 --- a/webkit/browser/blob/blob_storage_context.h +++ b/webkit/browser/blob/blob_storage_context.h @@ -1,118 +1,5 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_BLOB_BLOB_STORAGE_CONTEXT_H_ -#define WEBKIT_BROWSER_BLOB_BLOB_STORAGE_CONTEXT_H_ - -#include <map> -#include <string> - -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "webkit/browser/blob/blob_data_handle.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/blob/blob_data.h" - -class GURL; - -namespace base { -class FilePath; -class Time; -} - -namespace content { -class BlobStorageHost; -} - -namespace storage { - -class BlobDataHandle; - -// This class handles the logistics of blob Storage within the browser process, -// and maintains a mapping from blob uuid to the data. The class is single -// threaded and should only be used on the IO thread. -// In chromium, there is one instance per profile. -class STORAGE_EXPORT BlobStorageContext - : public base::SupportsWeakPtr<BlobStorageContext> { - public: - BlobStorageContext(); - ~BlobStorageContext(); - - scoped_ptr<BlobDataHandle> GetBlobDataFromUUID(const std::string& uuid); - scoped_ptr<BlobDataHandle> GetBlobDataFromPublicURL(const GURL& url); - - // Useful for coining blobs from within the browser process. If the - // blob cannot be added due to memory consumption, returns NULL. - scoped_ptr<BlobDataHandle> AddFinishedBlob(const BlobData* blob_data); - - // Useful for coining blob urls from within the browser process. - bool RegisterPublicBlobURL(const GURL& url, const std::string& uuid); - void RevokePublicBlobURL(const GURL& url); - - private: - friend class content::BlobStorageHost; - friend class BlobDataHandle::BlobDataHandleShared; - friend class ViewBlobInternalsJob; - - enum EntryFlags { - BEING_BUILT = 1 << 0, - EXCEEDED_MEMORY = 1 << 1, - }; - - struct BlobMapEntry { - int refcount; - int flags; - scoped_refptr<BlobData> data; - - BlobMapEntry(); - BlobMapEntry(int refcount, int flags, BlobData* data); - ~BlobMapEntry(); - }; - - typedef std::map<std::string, BlobMapEntry> - BlobMap; - typedef std::map<GURL, std::string> BlobURLMap; - - void StartBuildingBlob(const std::string& uuid); - void AppendBlobDataItem(const std::string& uuid, - const BlobData::Item& data_item); - void FinishBuildingBlob(const std::string& uuid, const std::string& type); - void CancelBuildingBlob(const std::string& uuid); - void IncrementBlobRefCount(const std::string& uuid); - void DecrementBlobRefCount(const std::string& uuid); - - bool ExpandStorageItems(BlobData* target_blob_data, - BlobData* src_blob_data, - uint64 offset, - uint64 length); - bool AppendBytesItem(BlobData* target_blob_data, - const char* data, int64 length); - void AppendFileItem(BlobData* target_blob_data, - const base::FilePath& file_path, - uint64 offset, uint64 length, - const base::Time& expected_modification_time); - void AppendFileSystemFileItem( - BlobData* target_blob_data, - const GURL& url, uint64 offset, uint64 length, - const base::Time& expected_modification_time); - - bool IsInUse(const std::string& uuid); - bool IsBeingBuilt(const std::string& uuid); - bool IsUrlRegistered(const GURL& blob_url); - - BlobMap blob_map_; - BlobURLMap public_blob_urls_; - - // Used to keep track of how much memory is being utilized for blob data, - // we count only the items of TYPE_DATA which are held in memory and not - // items of TYPE_FILE. - int64 memory_usage_; - - DISALLOW_COPY_AND_ASSIGN(BlobStorageContext); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_BLOB_BLOB_STORAGE_CONTEXT_H_ +#include "storage/browser/blob/blob_storage_context.h" diff --git a/webkit/browser/blob/blob_url_request_job.h b/webkit/browser/blob/blob_url_request_job.h index 1f2bf5b..c494621 100644 --- a/webkit/browser/blob/blob_url_request_job.h +++ b/webkit/browser/blob/blob_url_request_job.h @@ -1,129 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_BLOB_BLOB_URL_REQUEST_JOB_H_ -#define WEBKIT_BROWSER_BLOB_BLOB_URL_REQUEST_JOB_H_ - -#include <map> - -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "net/http/http_byte_range.h" -#include "net/http/http_status_code.h" -#include "net/url_request/url_request_job.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/blob/blob_data.h" - -namespace base { -class MessageLoopProxy; -} - -namespace storage { -class FileSystemContext; -} - -namespace net { -class DrainableIOBuffer; -class IOBuffer; -} - -namespace storage { - -class FileStreamReader; - -// A request job that handles reading blob URLs. -class STORAGE_EXPORT BlobURLRequestJob - : public net::URLRequestJob { - public: - BlobURLRequestJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const scoped_refptr<BlobData>& blob_data, - storage::FileSystemContext* file_system_context, - base::MessageLoopProxy* resolving_message_loop_proxy); - - // net::URLRequestJob methods. - virtual void Start() OVERRIDE; - virtual void Kill() OVERRIDE; - virtual bool ReadRawData(net::IOBuffer* buf, - int buf_size, - int* bytes_read) OVERRIDE; - virtual bool GetMimeType(std::string* mime_type) const OVERRIDE; - virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE; - virtual int GetResponseCode() const OVERRIDE; - virtual void SetExtraRequestHeaders( - const net::HttpRequestHeaders& headers) OVERRIDE; - - protected: - virtual ~BlobURLRequestJob(); - - private: - typedef std::map<size_t, FileStreamReader*> IndexToReaderMap; - - // For preparing for read: get the size, apply the range and perform seek. - void DidStart(); - bool AddItemLength(size_t index, int64 item_length); - void CountSize(); - void DidCountSize(int error); - void DidGetFileItemLength(size_t index, int64 result); - void Seek(int64 offset); - - // For reading the blob. - bool ReadLoop(int* bytes_read); - bool ReadItem(); - void AdvanceItem(); - void AdvanceBytesRead(int result); - bool ReadBytesItem(const BlobData::Item& item, int bytes_to_read); - bool ReadFileItem(FileStreamReader* reader, int bytes_to_read); - - void DidReadFile(int result); - void DeleteCurrentFileReader(); - - int ComputeBytesToRead() const; - int BytesReadCompleted(); - - // These methods convert the result of blob data reading into response headers - // and pass it to URLRequestJob's NotifyDone() or NotifyHeadersComplete(). - void NotifySuccess(); - void NotifyFailure(int); - void HeadersCompleted(net::HttpStatusCode status_code); - - // Returns a FileStreamReader for a blob item at |index|. - // If the item at |index| is not of file this returns NULL. - FileStreamReader* GetFileStreamReader(size_t index); - - // Creates a FileStreamReader for the item at |index| with additional_offset. - void CreateFileStreamReader(size_t index, int64 additional_offset); - - scoped_refptr<BlobData> blob_data_; - - // Variables for controlling read from |blob_data_|. - scoped_refptr<storage::FileSystemContext> file_system_context_; - scoped_refptr<base::MessageLoopProxy> file_thread_proxy_; - std::vector<int64> item_length_list_; - int64 total_size_; - int64 remaining_bytes_; - int pending_get_file_info_count_; - IndexToReaderMap index_to_reader_; - size_t current_item_index_; - int64 current_item_offset_; - - // Holds the buffer for read data with the IOBuffer interface. - scoped_refptr<net::DrainableIOBuffer> read_buf_; - - // Is set when NotifyFailure() is called and reset when DidStart is called. - bool error_; - - bool byte_range_set_; - net::HttpByteRange byte_range_; - - scoped_ptr<net::HttpResponseInfo> response_info_; - - base::WeakPtrFactory<BlobURLRequestJob> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(BlobURLRequestJob); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_BLOB_BLOB_URL_REQUEST_JOB_H_ +#include "storage/browser/blob/blob_url_request_job.h" diff --git a/webkit/browser/blob/blob_url_request_job_factory.h b/webkit/browser/blob/blob_url_request_job_factory.h index 75bfe9a..b39167c 100644 --- a/webkit/browser/blob/blob_url_request_job_factory.h +++ b/webkit/browser/blob/blob_url_request_job_factory.h @@ -1,71 +1,5 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_BLOB_BLOB_URL_REQUEST_JOB_FACTORY_H_ -#define WEBKIT_BROWSER_BLOB_BLOB_URL_REQUEST_JOB_FACTORY_H_ - -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_job_factory.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class MessageLoopProxy; -} // namespace base - -namespace storage { -class FileSystemContext; -} // namespace storage - -namespace net { -class URLRequestContext; -} // namespace net - -namespace storage { - -class BlobData; -class BlobDataHandle; -class BlobStorageContext; - -class STORAGE_EXPORT BlobProtocolHandler - : public net::URLRequestJobFactory::ProtocolHandler { - public: - // A helper to manufacture an URLRequest to retrieve the given blob. - static scoped_ptr<net::URLRequest> CreateBlobRequest( - scoped_ptr<BlobDataHandle> blob_data_handle, - const net::URLRequestContext* request_context, - net::URLRequest::Delegate* request_delegate); - - // This class ignores the request's URL and uses the value given - // to SetRequestedBlobDataHandle instead. - static void SetRequestedBlobDataHandle( - net::URLRequest* request, - scoped_ptr<BlobDataHandle> blob_data_handle); - - BlobProtocolHandler( - BlobStorageContext* context, - storage::FileSystemContext* file_system_context, - const scoped_refptr<base::MessageLoopProxy>& file_loop_proxy); - virtual ~BlobProtocolHandler(); - - virtual net::URLRequestJob* MaybeCreateJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const OVERRIDE; - - private: - scoped_refptr<BlobData> LookupBlobData( - net::URLRequest* request) const; - - base::WeakPtr<BlobStorageContext> context_; - const scoped_refptr<storage::FileSystemContext> file_system_context_; - const scoped_refptr<base::MessageLoopProxy> file_loop_proxy_; - - DISALLOW_COPY_AND_ASSIGN(BlobProtocolHandler); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_BLOB_BLOB_URL_REQUEST_JOB_FACTORY_H_ +#include "storage/browser/blob/blob_url_request_job_factory.h" diff --git a/webkit/browser/blob/file_stream_reader.h b/webkit/browser/blob/file_stream_reader.h index 0e7f969..d15eedf 100644 --- a/webkit/browser/blob/file_stream_reader.h +++ b/webkit/browser/blob/file_stream_reader.h @@ -1,99 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BLOB_FILE_STREAM_READER_H_ -#define WEBKIT_BLOB_FILE_STREAM_READER_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/files/file.h" -#include "net/base/completion_callback.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class FilePath; -class TaskRunner; -class Time; -} - -namespace net { -class IOBuffer; -} - -namespace storage { -class FileSystemContext; -class FileSystemURL; -} - -namespace storage { - -// A generic interface for reading a file-like object. -class FileStreamReader { - public: - // Creates a new FileReader for a local file |file_path|. - // |initial_offset| specifies the offset in the file where the first read - // should start. If the given offset is out of the file range any - // read operation may error out with net::ERR_REQUEST_RANGE_NOT_SATISFIABLE. - // |expected_modification_time| specifies the expected last modification - // If the value is non-null, the reader will check the underlying file's - // actual modification time to see if the file has been modified, and if - // it does any succeeding read operations should fail with - // ERR_UPLOAD_FILE_CHANGED error. - STORAGE_EXPORT static FileStreamReader* - CreateForLocalFile(base::TaskRunner* task_runner, - const base::FilePath& file_path, - int64 initial_offset, - const base::Time& expected_modification_time); - - // Creates a new reader for a filesystem URL |url| form |initial_offset|. - // |expected_modification_time| specifies the expected last modification if - // the value is non-null, the reader will check the underlying file's actual - // modification time to see if the file has been modified, and if it does any - // succeeding read operations should fail with ERR_UPLOAD_FILE_CHANGED error. - STORAGE_EXPORT static FileStreamReader* - CreateForFileSystemFile(storage::FileSystemContext* context, - const storage::FileSystemURL& url, - int64 initial_offset, - const base::Time& expected_modification_time); - - // Verify if the underlying file has not been modified. - STORAGE_EXPORT static bool VerifySnapshotTime( - const base::Time& expected_modification_time, - const base::File::Info& file_info); - - // It is valid to delete the reader at any time. If the stream is deleted - // while it has a pending read, its callback will not be called. - virtual ~FileStreamReader() {} - - // Reads from the current cursor position asynchronously. - // - // Up to buf_len bytes will be copied into buf. (In other words, partial - // reads are allowed.) Returns the number of bytes copied, 0 if at - // end-of-file, or an error code if the operation could not be performed. - // If the read could not complete synchronously, then ERR_IO_PENDING is - // returned, and the callback will be run on the thread where Read() - // was called, when the read has completed. - // - // It is invalid to call Read while there is an in-flight Read operation. - // - // If the stream is deleted while it has an in-flight Read operation - // |callback| will not be called. - virtual int Read(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) = 0; - - // Returns the length of the file if it could successfully retrieve the - // file info *and* its last modification time equals to - // expected modification time (rv >= 0 cases). - // Otherwise, a negative error code is returned (rv < 0 cases). - // If the stream is deleted while it has an in-flight GetLength operation - // |callback| will not be called. - // Note that the return type is int64 to return a larger file's size (a file - // larger than 2G) but an error code should fit in the int range (may be - // smaller than int64 range). - virtual int64 GetLength(const net::Int64CompletionCallback& callback) = 0; -}; - -} // namespace storage - -#endif // WEBKIT_BLOB_FILE_STREAM_READER_H_ +#include "storage/browser/blob/file_stream_reader.h" diff --git a/webkit/browser/blob/local_file_stream_reader.h b/webkit/browser/blob/local_file_stream_reader.h index 94fafd2..c6fb7f6 100644 --- a/webkit/browser/blob/local_file_stream_reader.h +++ b/webkit/browser/blob/local_file_stream_reader.h @@ -1,81 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_BLOB_LOCAL_FILE_STREAM_READER_H_ -#define WEBKIT_BROWSER_BLOB_LOCAL_FILE_STREAM_READER_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/memory/weak_ptr.h" -#include "base/time/time.h" -#include "webkit/browser/blob/file_stream_reader.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class TaskRunner; -} - -namespace content { -class LocalFileStreamReaderTest; -} - -namespace net { -class FileStream; -} - -namespace storage { - -// A thin wrapper of net::FileStream with range support for sliced file -// handling. -class STORAGE_EXPORT LocalFileStreamReader - : public NON_EXPORTED_BASE(FileStreamReader) { - public: - virtual ~LocalFileStreamReader(); - - // FileStreamReader overrides. - virtual int Read(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) OVERRIDE; - virtual int64 GetLength( - const net::Int64CompletionCallback& callback) OVERRIDE; - - private: - friend class FileStreamReader; - friend class content::LocalFileStreamReaderTest; - - LocalFileStreamReader(base::TaskRunner* task_runner, - const base::FilePath& file_path, - int64 initial_offset, - const base::Time& expected_modification_time); - int Open(const net::CompletionCallback& callback); - - // Callbacks that are chained from Open for Read. - void DidVerifyForOpen(const net::CompletionCallback& callback, - int64 get_length_result); - void DidOpenFileStream(const net::CompletionCallback& callback, - int result); - void DidSeekFileStream(const net::CompletionCallback& callback, - int64 seek_result); - void DidOpenForRead(net::IOBuffer* buf, - int buf_len, - const net::CompletionCallback& callback, - int open_result); - - void DidGetFileInfoForGetLength(const net::Int64CompletionCallback& callback, - base::File::Error error, - const base::File::Info& file_info); - - scoped_refptr<base::TaskRunner> task_runner_; - scoped_ptr<net::FileStream> stream_impl_; - const base::FilePath file_path_; - const int64 initial_offset_; - const base::Time expected_modification_time_; - bool has_pending_open_; - base::WeakPtrFactory<LocalFileStreamReader> weak_factory_; -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_BLOB_LOCAL_FILE_STREAM_READER_H_ +#include "storage/browser/blob/local_file_stream_reader.h" diff --git a/webkit/browser/blob/view_blob_internals_job.h b/webkit/browser/blob/view_blob_internals_job.h index 9fcf33d..21b33d3 100644 --- a/webkit/browser/blob/view_blob_internals_job.h +++ b/webkit/browser/blob/view_blob_internals_job.h @@ -1,57 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_BLOB_VIEW_BLOB_INTERNALS_JOB_H_ -#define WEBKIT_BROWSER_BLOB_VIEW_BLOB_INTERNALS_JOB_H_ - -#include <string> - -#include "base/memory/weak_ptr.h" -#include "net/url_request/url_request_simple_job.h" -#include "webkit/browser/storage_browser_export.h" - -namespace net { -class URLRequest; -} // namespace net - -namespace storage { - -class BlobData; -class BlobStorageContext; - -// A job subclass that implements a protocol to inspect the internal -// state of blob registry. -class STORAGE_EXPORT ViewBlobInternalsJob - : public net::URLRequestSimpleJob { - public: - ViewBlobInternalsJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate, - BlobStorageContext* blob_storage_context); - - virtual void Start() OVERRIDE; - virtual int GetData(std::string* mime_type, - std::string* charset, - std::string* data, - const net::CompletionCallback& callback) const OVERRIDE; - virtual bool IsRedirectResponse(GURL* location, - int* http_status_code) OVERRIDE; - virtual void Kill() OVERRIDE; - - private: - virtual ~ViewBlobInternalsJob(); - - void GenerateHTML(std::string* out) const; - static void GenerateHTMLForBlobData(const BlobData& blob_data, - int refcount, - std::string* out); - - BlobStorageContext* blob_storage_context_; - base::WeakPtrFactory<ViewBlobInternalsJob> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(ViewBlobInternalsJob); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_BLOB_VIEW_BLOB_INTERNALS_JOB_H_ +#include "storage/browser/blob/view_blob_internals_job.h" diff --git a/webkit/browser/database/database_quota_client.h b/webkit/browser/database/database_quota_client.h index 9325375..b5fec70 100644 --- a/webkit/browser/database/database_quota_client.h +++ b/webkit/browser/database/database_quota_client.h @@ -1,57 +1,5 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_DATABASE_DATABASE_QUOTA_CLIENT_H_ -#define WEBKIT_BROWSER_DATABASE_DATABASE_QUOTA_CLIENT_H_ - -#include <set> -#include <string> - -#include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop_proxy.h" -#include "webkit/browser/quota/quota_client.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/quota/quota_types.h" - -namespace storage { - -class DatabaseTracker; - -// A QuotaClient implementation to integrate WebSQLDatabases -// with the quota management system. This interface is used -// on the IO thread by the quota manager. -class STORAGE_EXPORT_PRIVATE DatabaseQuotaClient - : public storage::QuotaClient { - public: - DatabaseQuotaClient( - base::MessageLoopProxy* tracker_thread, - DatabaseTracker* tracker); - virtual ~DatabaseQuotaClient(); - - // QuotaClient method overrides - virtual ID id() const OVERRIDE; - virtual void OnQuotaManagerDestroyed() OVERRIDE; - virtual void GetOriginUsage(const GURL& origin_url, - storage::StorageType type, - const GetUsageCallback& callback) OVERRIDE; - virtual void GetOriginsForType(storage::StorageType type, - const GetOriginsCallback& callback) OVERRIDE; - virtual void GetOriginsForHost(storage::StorageType type, - const std::string& host, - const GetOriginsCallback& callback) OVERRIDE; - virtual void DeleteOriginData(const GURL& origin, - storage::StorageType type, - const DeletionCallback& callback) OVERRIDE; - virtual bool DoesSupport(storage::StorageType type) const OVERRIDE; - - private: - scoped_refptr<base::MessageLoopProxy> db_tracker_thread_; - scoped_refptr<DatabaseTracker> db_tracker_; // only used on its thread - - DISALLOW_COPY_AND_ASSIGN(DatabaseQuotaClient); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_DATABASE_DATABASE_QUOTA_CLIENT_H_ +#include "storage/browser/database/database_quota_client.h" diff --git a/webkit/browser/database/database_tracker.h b/webkit/browser/database/database_tracker.h index 6f14d7b..9bcd442 100644 --- a/webkit/browser/database/database_tracker.h +++ b/webkit/browser/database/database_tracker.h @@ -1,319 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_DATABASE_DATABASE_TRACKER_H_ -#define WEBKIT_BROWSER_DATABASE_DATABASE_TRACKER_H_ - -#include <map> -#include <set> -#include <utility> - -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/gtest_prod_util.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "base/strings/string16.h" -#include "base/strings/string_util.h" -#include "base/time/time.h" -#include "net/base/completion_callback.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/database/database_connections.h" - -namespace base { -class MessageLoopProxy; -} - -namespace content { -class DatabaseTracker_TestHelper_Test; -class MockDatabaseTracker; -} - -namespace sql { -class Connection; -class MetaTable; -} - -namespace storage { -class QuotaManagerProxy; -class SpecialStoragePolicy; -} - -namespace storage { - -STORAGE_EXPORT extern const base::FilePath::CharType - kDatabaseDirectoryName[]; -STORAGE_EXPORT extern const base::FilePath::CharType - kTrackerDatabaseFileName[]; - -class DatabasesTable; - -// This class is used to store information about all databases in an origin. -class STORAGE_EXPORT OriginInfo { - public: - OriginInfo(); - OriginInfo(const OriginInfo& origin_info); - ~OriginInfo(); - - const std::string& GetOriginIdentifier() const { return origin_identifier_; } - int64 TotalSize() const { return total_size_; } - void GetAllDatabaseNames(std::vector<base::string16>* databases) const; - int64 GetDatabaseSize(const base::string16& database_name) const; - base::string16 GetDatabaseDescription( - const base::string16& database_name) const; - - protected: - typedef std::map<base::string16, std::pair<int64, base::string16> > - DatabaseInfoMap; - - OriginInfo(const std::string& origin_identifier, int64 total_size); - - std::string origin_identifier_; - int64 total_size_; - DatabaseInfoMap database_info_; -}; - -// This class manages the main database and keeps track of open databases. -// -// The data in this class is not thread-safe, so all methods of this class -// should be called on the same thread. The only exceptions are the ctor(), -// the dtor() and the database_directory() and quota_manager_proxy() getters. -// -// Furthermore, some methods of this class have to read/write data from/to -// the disk. Therefore, in a multi-threaded application, all methods of this -// class should be called on the thread dedicated to file operations (file -// thread in the browser process, for example), if such a thread exists. -class STORAGE_EXPORT DatabaseTracker - : public base::RefCountedThreadSafe<DatabaseTracker> { - public: - class Observer { - public: - virtual void OnDatabaseSizeChanged(const std::string& origin_identifier, - const base::string16& database_name, - int64 database_size) = 0; - virtual void OnDatabaseScheduledForDeletion( - const std::string& origin_identifier, - const base::string16& database_name) = 0; - - protected: - virtual ~Observer() {} - }; - - DatabaseTracker(const base::FilePath& profile_path, - bool is_incognito, - storage::SpecialStoragePolicy* special_storage_policy, - storage::QuotaManagerProxy* quota_manager_proxy, - base::MessageLoopProxy* db_tracker_thread); - - void DatabaseOpened(const std::string& origin_identifier, - const base::string16& database_name, - const base::string16& database_details, - int64 estimated_size, - int64* database_size); - void DatabaseModified(const std::string& origin_identifier, - const base::string16& database_name); - void DatabaseClosed(const std::string& origin_identifier, - const base::string16& database_name); - void HandleSqliteError(const std::string& origin_identifier, - const base::string16& database_name, - int error); - - void CloseDatabases(const DatabaseConnections& connections); - - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - - void CloseTrackerDatabaseAndClearCaches(); - - const base::FilePath& DatabaseDirectory() const { return db_dir_; } - base::FilePath GetFullDBFilePath(const std::string& origin_identifier, - const base::string16& database_name); - - // virtual for unit-testing only - virtual bool GetOriginInfo(const std::string& origin_id, OriginInfo* info); - virtual bool GetAllOriginIdentifiers(std::vector<std::string>* origin_ids); - virtual bool GetAllOriginsInfo(std::vector<OriginInfo>* origins_info); - - // Safe to call on any thread. - storage::QuotaManagerProxy* quota_manager_proxy() const { - return quota_manager_proxy_.get(); - } - - bool IsDatabaseScheduledForDeletion(const std::string& origin_identifier, - const base::string16& database_name); - - // Deletes a single database. Returns net::OK on success, net::FAILED on - // failure, or net::ERR_IO_PENDING and |callback| is invoked upon completion, - // if non-NULL. - int DeleteDatabase(const std::string& origin_identifier, - const base::string16& database_name, - const net::CompletionCallback& callback); - - // Delete any databases that have been touched since the cutoff date that's - // supplied, omitting any that match IDs within |protected_origins|. - // Returns net::OK on success, net::FAILED if not all databases could be - // deleted, and net::ERR_IO_PENDING and |callback| is invoked upon completion, - // if non-NULL. Protected origins, according the the SpecialStoragePolicy, - // are not deleted by this method. - int DeleteDataModifiedSince(const base::Time& cutoff, - const net::CompletionCallback& callback); - - // Delete all databases that belong to the given origin. Returns net::OK on - // success, net::FAILED if not all databases could be deleted, and - // net::ERR_IO_PENDING and |callback| is invoked upon completion, if non-NULL. - // virtual for unit testing only - virtual int DeleteDataForOrigin(const std::string& origin_identifier, - const net::CompletionCallback& callback); - - bool IsIncognitoProfile() const { return is_incognito_; } - - const base::File* GetIncognitoFile(const base::string16& vfs_file_path) const; - const base::File* SaveIncognitoFile(const base::string16& vfs_file_path, - base::File file); - void CloseIncognitoFileHandle(const base::string16& vfs_file_path); - bool HasSavedIncognitoFileHandle(const base::string16& vfs_file_path) const; - - // Shutdown the database tracker, deleting database files if the tracker is - // used for an incognito profile. - void Shutdown(); - // Disables the exit-time deletion of session-only data. - void SetForceKeepSessionState(); - - private: - friend class base::RefCountedThreadSafe<DatabaseTracker>; - friend class content::DatabaseTracker_TestHelper_Test; - friend class content::MockDatabaseTracker; // for testing - - typedef std::map<std::string, std::set<base::string16> > DatabaseSet; - typedef std::vector<std::pair<net::CompletionCallback, DatabaseSet> > - PendingDeletionCallbacks; - typedef std::map<base::string16, base::File*> FileHandlesMap; - typedef std::map<std::string, base::string16> OriginDirectoriesMap; - - class CachedOriginInfo : public OriginInfo { - public: - CachedOriginInfo() : OriginInfo(std::string(), 0) {} - void SetOriginIdentifier(const std::string& origin_identifier) { - origin_identifier_ = origin_identifier; - } - void SetDatabaseSize(const base::string16& database_name, int64 new_size) { - int64 old_size = 0; - if (database_info_.find(database_name) != database_info_.end()) - old_size = database_info_[database_name].first; - database_info_[database_name].first = new_size; - if (new_size != old_size) - total_size_ += new_size - old_size; - } - void SetDatabaseDescription(const base::string16& database_name, - const base::string16& description) { - database_info_[database_name].second = description; - } - }; - - // virtual for unit-testing only. - virtual ~DatabaseTracker(); - - // Deletes the directory that stores all DBs in incognito mode, if it exists. - void DeleteIncognitoDBDirectory(); - - // Deletes session-only databases. Blocks databases from being created/opened. - void ClearSessionOnlyOrigins(); - - bool DeleteClosedDatabase(const std::string& origin_identifier, - const base::string16& database_name); - - // Delete all files belonging to the given origin given that no database - // connections within this origin are open, or if |force| is true, delete - // the meta data and rename the associated directory. - bool DeleteOrigin(const std::string& origin_identifier, bool force); - void DeleteDatabaseIfNeeded(const std::string& origin_identifier, - const base::string16& database_name); - - bool LazyInit(); - bool UpgradeToCurrentVersion(); - void InsertOrUpdateDatabaseDetails(const std::string& origin_identifier, - const base::string16& database_name, - const base::string16& database_details, - int64 estimated_size); - - void ClearAllCachedOriginInfo(); - CachedOriginInfo* MaybeGetCachedOriginInfo( - const std::string& origin_identifier, - bool create_if_needed); - CachedOriginInfo* GetCachedOriginInfo( - const std::string& origin_identifier) { - return MaybeGetCachedOriginInfo(origin_identifier, true); - } - - int64 GetDBFileSize(const std::string& origin_identifier, - const base::string16& database_name); - int64 SeedOpenDatabaseInfo(const std::string& origin_identifier, - const base::string16& database_name, - const base::string16& description); - int64 UpdateOpenDatabaseInfoAndNotify(const std::string& origin_identifier, - const base::string16& database_name, - const base::string16* opt_description); - int64 UpdateOpenDatabaseSizeAndNotify(const std::string& origin_identifier, - const base::string16& database_name) { - return UpdateOpenDatabaseInfoAndNotify( - origin_identifier, database_name, NULL); - } - - - void ScheduleDatabaseForDeletion(const std::string& origin_identifier, - const base::string16& database_name); - // Schedule a set of open databases for deletion. If non-null, callback is - // invoked upon completion. - void ScheduleDatabasesForDeletion(const DatabaseSet& databases, - const net::CompletionCallback& callback); - - // Returns the directory where all DB files for the given origin are stored. - base::string16 GetOriginDirectory(const std::string& origin_identifier); - - bool is_initialized_; - const bool is_incognito_; - bool force_keep_session_state_; - bool shutting_down_; - const base::FilePath profile_path_; - const base::FilePath db_dir_; - scoped_ptr<sql::Connection> db_; - scoped_ptr<DatabasesTable> databases_table_; - scoped_ptr<sql::MetaTable> meta_table_; - ObserverList<Observer, true> observers_; - std::map<std::string, CachedOriginInfo> origins_info_map_; - DatabaseConnections database_connections_; - - // The set of databases that should be deleted but are still opened - DatabaseSet dbs_to_be_deleted_; - PendingDeletionCallbacks deletion_callbacks_; - - // Apps and Extensions can have special rights. - scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy_; - - scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy_; - - // The database tracker thread we're supposed to run file IO on. - scoped_refptr<base::MessageLoopProxy> db_tracker_thread_; - - // When in incognito mode, store a DELETE_ON_CLOSE handle to each - // main DB and journal file that was accessed. When the incognito profile - // goes away (or when the browser crashes), all these handles will be - // closed, and the files will be deleted. - FileHandlesMap incognito_file_handles_; - - // In a non-incognito profile, all DBs in an origin are stored in a directory - // named after the origin. In an incognito profile though, we do not want the - // directory structure to reveal the origins visited by the user (in case the - // browser process crashes and those directories are not deleted). So we use - // this map to assign directory names that do not reveal this information. - OriginDirectoriesMap incognito_origin_directories_; - int incognito_origin_directories_generator_; - - FRIEND_TEST_ALL_PREFIXES(DatabaseTracker, TestHelper); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_DATABASE_DATABASE_TRACKER_H_ +#include "storage/browser/database/database_tracker.h" diff --git a/webkit/browser/database/database_util.h b/webkit/browser/database/database_util.h index bb2a6f4..cce434c 100644 --- a/webkit/browser/database/database_util.h +++ b/webkit/browser/database/database_util.h @@ -1,39 +1,5 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_DATABASE_DATABASE_UTIL_H_ -#define WEBKIT_BROWSER_DATABASE_DATABASE_UTIL_H_ - -#include <string> -#include "base/strings/string16.h" -#include "url/gurl.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class FilePath; -} - -namespace storage { - -class DatabaseTracker; - -class STORAGE_EXPORT DatabaseUtil { - public: - static const char kJournalFileSuffix[]; - - // Extract various information from a database vfs_file_name. All return - // parameters are optional. - static bool CrackVfsFileName(const base::string16& vfs_file_name, - std::string* origin_identifier, - base::string16* database_name, - base::string16* sqlite_suffix); - static base::FilePath GetFullFilePathForVfsFile( - DatabaseTracker* db_tracker, - const base::string16& vfs_file_name); - static bool IsValidOriginIdentifier(const std::string& origin_identifier); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_DATABASE_DATABASE_UTIL_H_ +#include "storage/browser/database/database_util.h" diff --git a/webkit/browser/database/databases_table.h b/webkit/browser/database/databases_table.h index c3cdbb82..18342b7 100644 --- a/webkit/browser/database/databases_table.h +++ b/webkit/browser/database/databases_table.h @@ -1,54 +1,5 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_DATABASE_DATABASES_TABLE_H_ -#define WEBKIT_BROWSER_DATABASE_DATABASES_TABLE_H_ - -#include <vector> - -#include "base/strings/string16.h" -#include "webkit/browser/storage_browser_export.h" - -namespace sql { -class Connection; -} - -namespace storage { - -struct STORAGE_EXPORT_PRIVATE DatabaseDetails { - DatabaseDetails(); - ~DatabaseDetails(); - - std::string origin_identifier; - base::string16 database_name; - base::string16 description; - int64 estimated_size; -}; - -class STORAGE_EXPORT_PRIVATE DatabasesTable { - public: - explicit DatabasesTable(sql::Connection* db) : db_(db) { } - - bool Init(); - int64 GetDatabaseID(const std::string& origin_identifier, - const base::string16& database_name); - bool GetDatabaseDetails(const std::string& origin_identifier, - const base::string16& database_name, - DatabaseDetails* details); - bool InsertDatabaseDetails(const DatabaseDetails& details); - bool UpdateDatabaseDetails(const DatabaseDetails& details); - bool DeleteDatabaseDetails(const std::string& origin_identifier, - const base::string16& database_name); - bool GetAllOriginIdentifiers(std::vector<std::string>* origin_identifiers); - bool GetAllDatabaseDetailsForOriginIdentifier( - const std::string& origin_identifier, - std::vector<DatabaseDetails>* details); - bool DeleteOriginIdentifier(const std::string& origin_identifier); - private: - sql::Connection* db_; -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_DATABASE_DATABASES_TABLE_H_ +#include "storage/browser/database/databases_table.h" diff --git a/webkit/browser/database/vfs_backend.h b/webkit/browser/database/vfs_backend.h index 3de6371..3904e15 100644 --- a/webkit/browser/database/vfs_backend.h +++ b/webkit/browser/database/vfs_backend.h @@ -1,42 +1,5 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_DATABASE_VFS_BACKEND_H_ -#define WEBKIT_BROWSER_DATABASE_VFS_BACKEND_H_ - -#include "base/files/file.h" -#include "base/process/process.h" -#include "base/strings/string16.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class FilePath; -} - -namespace storage { - -class STORAGE_EXPORT VfsBackend { - public: - static base::File OpenFile(const base::FilePath& file_path, - int desired_flags); - - static base::File OpenTempFileInDirectory(const base::FilePath& dir_path, - int desired_flags); - - static int DeleteFile(const base::FilePath& file_path, bool sync_dir); - - static uint32 GetFileAttributes(const base::FilePath& file_path); - - static int64 GetFileSize(const base::FilePath& file_path); - - // Used to make decisions in the DatabaseDispatcherHost. - static bool OpenTypeIsReadWrite(int desired_flags); - - private: - static bool OpenFileFlagsAreConsistent(int desired_flags); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_DATABASE_VFS_BACKEND_H_ +#include "storage/browser/database/vfs_backend.h" diff --git a/webkit/browser/fileapi/async_file_util.h b/webkit/browser/fileapi/async_file_util.h index c2b1098..758963f 100644 --- a/webkit/browser/fileapi/async_file_util.h +++ b/webkit/browser/fileapi/async_file_util.h @@ -1,366 +1,5 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_ASYNC_FILE_UTIL_H_ -#define WEBKIT_BROWSER_FILEAPI_ASYNC_FILE_UTIL_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "base/callback_forward.h" -#include "base/files/file.h" -#include "base/files/file_util_proxy.h" -#include "base/memory/scoped_ptr.h" -#include "webkit/browser/fileapi/file_system_operation.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/fileapi/directory_entry.h" - -namespace base { -class Time; -} - -namespace storage { -class ShareableFileReference; -} - -namespace storage { - -class FileSystemOperationContext; -class FileSystemURL; - -// An interface which provides filesystem-specific file operations for -// FileSystemOperationImpl. -// -// Each filesystem which needs to be dispatched from FileSystemOperationImpl -// must implement this interface or a synchronous version of interface: -// FileSystemFileUtil. -// -// As far as an instance of this class is owned by a FileSystemBackend -// (which is owned by FileSystemContext), it's guaranteed that this instance's -// alive while FileSystemOperationContext given to each operation is kept -// alive. (Note that this instance might be freed on different thread -// from the thread it is created.) -// -// It is NOT valid to give null callback to this class, and implementors -// can assume that they don't get any null callbacks. -// -class AsyncFileUtil { - public: - typedef base::Callback<void(base::File::Error result)> StatusCallback; - - // |on_close_callback| will be called after the |file| is closed in the - // child process. |on_close_callback|.is_null() can be true, if no operation - // is needed on closing the file. - typedef base::Callback< - void(base::File file, - const base::Closure& on_close_callback)> CreateOrOpenCallback; - - typedef base::Callback< - void(base::File::Error result, - bool created)> EnsureFileExistsCallback; - - typedef base::Callback< - void(base::File::Error result, - const base::File::Info& file_info)> GetFileInfoCallback; - - typedef std::vector<DirectoryEntry> EntryList; - typedef base::Callback< - void(base::File::Error result, - const EntryList& file_list, - bool has_more)> ReadDirectoryCallback; - - typedef base::Callback< - void(base::File::Error result, - const base::File::Info& file_info, - const base::FilePath& platform_path, - const scoped_refptr<storage::ShareableFileReference>& file_ref)> - CreateSnapshotFileCallback; - - typedef base::Callback<void(int64 size)> CopyFileProgressCallback; - - typedef FileSystemOperation::CopyOrMoveOption CopyOrMoveOption; - - // Creates an AsyncFileUtil instance which performs file operations on - // local native file system. The created instance assumes - // FileSystemURL::path() has the target platform path. - STORAGE_EXPORT static AsyncFileUtil* - CreateForLocalFileSystem(); - - AsyncFileUtil() {} - virtual ~AsyncFileUtil() {} - - // Creates or opens a file with the given flags. - // If File::FLAG_CREATE is set in |file_flags| it always tries to create - // a new file at the given |url| and calls back with - // File::FILE_ERROR_FILE_EXISTS if the |url| already exists. - // - // FileSystemOperationImpl::OpenFile calls this. - // This is used only by Pepper/NaCl File API. - // - virtual void CreateOrOpen( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - int file_flags, - const CreateOrOpenCallback& callback) = 0; - - // Ensures that the given |url| exist. This creates a empty new file - // at |url| if the |url| does not exist. - // - // FileSystemOperationImpl::CreateFile calls this. - // - // This reports following error code via |callback|: - // - File::FILE_OK and created==true if a file has not existed and - // is created at |url|. - // - File::FILE_OK and created==false if the file already exists. - // - Other error code (with created=false) if a file hasn't existed yet - // and there was an error while creating a new file. - // - virtual void EnsureFileExists( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const EnsureFileExistsCallback& callback) = 0; - - // Creates directory at given url. - // - // FileSystemOperationImpl::CreateDirectory calls this. - // - // This reports following error code via |callback|: - // - File::FILE_ERROR_NOT_FOUND if the |url|'s parent directory - // does not exist and |recursive| is false. - // - File::FILE_ERROR_EXISTS if a directory already exists at |url| - // and |exclusive| is true. - // - File::FILE_ERROR_EXISTS if a file already exists at |url| - // (regardless of |exclusive| value). - // - Other error code if it failed to create a directory. - // - virtual void CreateDirectory( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - bool exclusive, - bool recursive, - const StatusCallback& callback) = 0; - - // Retrieves the information about a file. - // - // FileSystemOperationImpl::GetMetadata calls this. - // - // This reports following error code via |callback|: - // - File::FILE_ERROR_NOT_FOUND if the file doesn't exist. - // - Other error code if there was an error while retrieving the file info. - // - virtual void GetFileInfo( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const GetFileInfoCallback& callback) = 0; - - // Reads contents of a directory at |path|. - // - // FileSystemOperationImpl::ReadDirectory calls this. - // - // Note that the |name| field of each entry in |file_list| - // returned by |callback| should have a base file name - // of the entry relative to the directory, but not an absolute path. - // - // (E.g. if ReadDirectory is called for a directory - // 'path/to/dir' and the directory has entries 'a' and 'b', - // the returned |file_list| should include entries whose names - // are 'a' and 'b', but not '/path/to/dir/a' and '/path/to/dir/b'.) - // - // This reports following error code via |callback|: - // - File::FILE_ERROR_NOT_FOUND if the target directory doesn't exist. - // - File::FILE_ERROR_NOT_A_DIRECTORY if an entry exists at |url| but - // is a file (not a directory). - // - virtual void ReadDirectory( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const ReadDirectoryCallback& callback) = 0; - - // Modifies timestamps of a file or directory at |url| with - // |last_access_time| and |last_modified_time|. The function DOES NOT - // create a file unlike 'touch' command on Linux. - // - // FileSystemOperationImpl::TouchFile calls this. - // This is used only by Pepper/NaCl File API. - // - virtual void Touch( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const base::Time& last_access_time, - const base::Time& last_modified_time, - const StatusCallback& callback) = 0; - - // Truncates a file at |path| to |length|. If |length| is larger than - // the original file size, the file will be extended, and the extended - // part is filled with null bytes. - // - // FileSystemOperationImpl::Truncate calls this. - // - // This reports following error code via |callback|: - // - File::FILE_ERROR_NOT_FOUND if the file doesn't exist. - // - virtual void Truncate( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - int64 length, - const StatusCallback& callback) = 0; - - // Copies a file from |src_url| to |dest_url|. - // This must be called for files that belong to the same filesystem - // (i.e. type() and origin() of the |src_url| and |dest_url| must match). - // |progress_callback| is a callback to report the progress update. - // See file_system_operations.h for details. This should be called on the - // same thread as where the method's called (IO thread). Calling this - // is optional. It is recommended to use this callback for heavier operations - // (such as file network downloading), so that, e.g., clients (UIs) can - // update its state to show progress to users. This may be a null callback. - // - // FileSystemOperationImpl::Copy calls this for same-filesystem copy case. - // - // This reports following error code via |callback|: - // - File::FILE_ERROR_NOT_FOUND if |src_url| - // or the parent directory of |dest_url| does not exist. - // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. - // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and - // is not a file. - // - File::FILE_ERROR_FAILED if |dest_url| does not exist and - // its parent path is a file. - // - virtual void CopyFileLocal( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - const CopyFileProgressCallback& progress_callback, - const StatusCallback& callback) = 0; - - // Moves a local file from |src_url| to |dest_url|. - // This must be called for files that belong to the same filesystem - // (i.e. type() and origin() of the |src_url| and |dest_url| must match). - // - // FileSystemOperationImpl::Move calls this for same-filesystem move case. - // - // This reports following error code via |callback|: - // - File::FILE_ERROR_NOT_FOUND if |src_url| - // or the parent directory of |dest_url| does not exist. - // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. - // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and - // is not a file. - // - File::FILE_ERROR_FAILED if |dest_url| does not exist and - // its parent path is a file. - // - virtual void MoveFileLocal( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - const StatusCallback& callback) = 0; - - // Copies in a single file from a different filesystem. - // - // FileSystemOperationImpl::Copy or Move calls this for cross-filesystem - // cases. - // - // This reports following error code via |callback|: - // - File::FILE_ERROR_NOT_FOUND if |src_file_path| - // or the parent directory of |dest_url| does not exist. - // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and - // is not a file. - // - File::FILE_ERROR_FAILED if |dest_url| does not exist and - // its parent path is a file. - // - virtual void CopyInForeignFile( - scoped_ptr<FileSystemOperationContext> context, - const base::FilePath& src_file_path, - const FileSystemURL& dest_url, - const StatusCallback& callback) = 0; - - // Deletes a single file. - // - // FileSystemOperationImpl::RemoveFile calls this. - // - // This reports following error code via |callback|: - // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. - // - File::FILE_ERROR_NOT_A_FILE if |url| is not a file. - // - virtual void DeleteFile( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const StatusCallback& callback) = 0; - - // Removes a single empty directory. - // - // FileSystemOperationImpl::RemoveDirectory calls this. - // - // This reports following error code via |callback|: - // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. - // - File::FILE_ERROR_NOT_A_DIRECTORY if |url| is not a directory. - // - File::FILE_ERROR_NOT_EMPTY if |url| is not empty. - // - virtual void DeleteDirectory( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const StatusCallback& callback) = 0; - - // Removes a single file or a single directory with its contents - // (i.e. files/subdirectories under the directory). - // - // FileSystemOperationImpl::Remove calls this. - // On some platforms, such as Chrome OS Drive File System, recursive file - // deletion can be implemented more efficiently than calling DeleteFile() and - // DeleteDirectory() for each files/directories. - // This method is optional, so if not supported, - // File::FILE_ERROR_INVALID_OPERATION should be returned via |callback|. - // - // This reports following error code via |callback|: - // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. - // - File::FILE_ERROR_INVALID_OPERATION if this operation is not supported. - virtual void DeleteRecursively( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const StatusCallback& callback) = 0; - - // Creates a local snapshot file for a given |url| and returns the - // metadata and platform path of the snapshot file via |callback|. - // In regular filesystem cases the implementation may simply return - // the metadata of the file itself (as well as GetMetadata does), - // while in non-regular filesystem case the backend may create a - // temporary snapshot file which holds the file data and return - // the metadata of the temporary file. - // - // In the callback, it returns: - // |file_info| is the metadata of the snapshot file created. - // |platform_path| is the full absolute platform path to the snapshot - // file created. If a file is not backed by a real local file in - // the implementor's FileSystem, the implementor must create a - // local snapshot file and return the path of the created file. - // - // If implementors creates a temporary file for snapshotting and wants - // FileAPI backend to take care of the lifetime of the file (so that - // it won't get deleted while JS layer has any references to the created - // File/Blob object), it should return non-empty |file_ref|. - // Via the |file_ref| implementors can schedule a file deletion - // or arbitrary callbacks when the last reference of File/Blob is dropped. - // - // FileSystemOperationImpl::CreateSnapshotFile calls this. - // - // This reports following error code via |callback|: - // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. - // - File::FILE_ERROR_NOT_A_FILE if |url| exists but is a directory. - // - // The field values of |file_info| are undefined (implementation - // dependent) in error cases, and the caller should always - // check the return code. - virtual void CreateSnapshotFile( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const CreateSnapshotFileCallback& callback) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(AsyncFileUtil); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_ASYNC_FILE_UTIL_H_ +#include "storage/browser/fileapi/async_file_util.h" diff --git a/webkit/browser/fileapi/async_file_util_adapter.h b/webkit/browser/fileapi/async_file_util_adapter.h index 1056035..f69908c 100644 --- a/webkit/browser/fileapi/async_file_util_adapter.h +++ b/webkit/browser/fileapi/async_file_util_adapter.h @@ -1,118 +1,5 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_ASYNC_FILE_UTIL_ADAPTER_H_ -#define WEBKIT_BROWSER_FILEAPI_ASYNC_FILE_UTIL_ADAPTER_H_ - -#include "base/memory/scoped_ptr.h" -#include "webkit/browser/fileapi/async_file_util.h" - -namespace storage { - -class FileSystemFileUtil; - -// An adapter class for FileSystemFileUtil classes to provide asynchronous -// interface. -// -// A filesystem can do either: -// - implement a synchronous version of FileUtil by extending -// FileSystemFileUtil and atach it to this adapter, or -// - directly implement AsyncFileUtil. -// -// This instance (as thus this->sync_file_util_) is guaranteed to be alive -// as far as FileSystemOperationContext given to each operation is kept alive. -class STORAGE_EXPORT AsyncFileUtilAdapter - : public NON_EXPORTED_BASE(AsyncFileUtil) { - public: - // Creates a new AsyncFileUtil for |sync_file_util|. This takes the - // ownership of |sync_file_util|. (This doesn't take scoped_ptr<> just - // to save extra make_scoped_ptr; in all use cases a new fresh FileUtil is - // created only for this adapter.) - explicit AsyncFileUtilAdapter(FileSystemFileUtil* sync_file_util); - - virtual ~AsyncFileUtilAdapter(); - - FileSystemFileUtil* sync_file_util() { - return sync_file_util_.get(); - } - - // AsyncFileUtil overrides. - virtual void CreateOrOpen( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - int file_flags, - const CreateOrOpenCallback& callback) OVERRIDE; - virtual void EnsureFileExists( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const EnsureFileExistsCallback& callback) OVERRIDE; - virtual void CreateDirectory( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - bool exclusive, - bool recursive, - const StatusCallback& callback) OVERRIDE; - virtual void GetFileInfo( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const GetFileInfoCallback& callback) OVERRIDE; - virtual void ReadDirectory( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const ReadDirectoryCallback& callback) OVERRIDE; - virtual void Touch( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const base::Time& last_access_time, - const base::Time& last_modified_time, - const StatusCallback& callback) OVERRIDE; - virtual void Truncate( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - int64 length, - const StatusCallback& callback) OVERRIDE; - virtual void CopyFileLocal( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - const CopyFileProgressCallback& progress_callback, - const StatusCallback& callback) OVERRIDE; - virtual void MoveFileLocal( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - const StatusCallback& callback) OVERRIDE; - virtual void CopyInForeignFile( - scoped_ptr<FileSystemOperationContext> context, - const base::FilePath& src_file_path, - const FileSystemURL& dest_url, - const StatusCallback& callback) OVERRIDE; - virtual void DeleteFile( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const StatusCallback& callback) OVERRIDE; - virtual void DeleteDirectory( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const StatusCallback& callback) OVERRIDE; - virtual void DeleteRecursively( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const StatusCallback& callback) OVERRIDE; - virtual void CreateSnapshotFile( - scoped_ptr<FileSystemOperationContext> context, - const FileSystemURL& url, - const CreateSnapshotFileCallback& callback) OVERRIDE; - - private: - scoped_ptr<FileSystemFileUtil> sync_file_util_; - - DISALLOW_COPY_AND_ASSIGN(AsyncFileUtilAdapter); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_ASYNC_FILE_UTIL_ADAPTER_H_ +#include "storage/browser/fileapi/async_file_util_adapter.h" diff --git a/webkit/browser/fileapi/copy_or_move_file_validator.h b/webkit/browser/fileapi/copy_or_move_file_validator.h index 9ade9e5..2d5c629 100644 --- a/webkit/browser/fileapi/copy_or_move_file_validator.h +++ b/webkit/browser/fileapi/copy_or_move_file_validator.h @@ -1,54 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_COPY_OR_MOVE_FILE_VALIDATOR_H_ -#define WEBKIT_BROWSER_FILEAPI_COPY_OR_MOVE_FILE_VALIDATOR_H_ - -#include "base/callback.h" -#include "base/files/file.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class FilePath; -} - -namespace storage { - -class FileSystemURL; - -class STORAGE_EXPORT CopyOrMoveFileValidator { - public: - // Callback that is invoked when validation completes. A result of - // base::File::FILE_OK means the file validated. - typedef base::Callback<void(base::File::Error result)> ResultCallback; - - virtual ~CopyOrMoveFileValidator() {} - - // Called on a source file before copying or moving to the final - // destination. - virtual void StartPreWriteValidation( - const ResultCallback& result_callback) = 0; - - // Called on a destination file after copying or moving to the final - // destination. Suitable for running Anti-Virus checks. - virtual void StartPostWriteValidation( - const base::FilePath& dest_platform_path, - const ResultCallback& result_callback) = 0; -}; - -class CopyOrMoveFileValidatorFactory { - public: - virtual ~CopyOrMoveFileValidatorFactory() {} - - // This method must always return a non-NULL validator. |src_url| is needed - // in addition to |platform_path| because in the obfuscated file system - // case, |platform_path| will be an obfuscated filename and extension. - virtual CopyOrMoveFileValidator* CreateCopyOrMoveFileValidator( - const FileSystemURL& src_url, - const base::FilePath& platform_path) = 0; -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_COPY_OR_MOVE_FILE_VALIDATOR_H_ +#include "storage/browser/fileapi/copy_or_move_file_validator.h" diff --git a/webkit/browser/fileapi/copy_or_move_operation_delegate.h b/webkit/browser/fileapi/copy_or_move_operation_delegate.h index e0a574d..558f83c 100644 --- a/webkit/browser/fileapi/copy_or_move_operation_delegate.h +++ b/webkit/browser/fileapi/copy_or_move_operation_delegate.h @@ -1,162 +1,5 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_COPY_OR_MOVE_OPERATION_DELEGATE_H_ -#define WEBKIT_BROWSER_FILEAPI_COPY_OR_MOVE_OPERATION_DELEGATE_H_ - -#include <set> -#include <stack> - -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/time/time.h" -#include "webkit/browser/fileapi/recursive_operation_delegate.h" - -namespace net { -class DrainableIOBuffer; -class IOBufferWithSize; -} - -namespace storage { -class FileStreamReader; -class ShareableFileReference; -} - -namespace storage { - -class CopyOrMoveFileValidator; -class FileStreamWriter; - -// A delegate class for recursive copy or move operations. -class CopyOrMoveOperationDelegate - : public RecursiveOperationDelegate { - public: - class CopyOrMoveImpl; - typedef FileSystemOperation::CopyProgressCallback CopyProgressCallback; - typedef FileSystemOperation::CopyOrMoveOption CopyOrMoveOption; - - enum OperationType { - OPERATION_COPY, - OPERATION_MOVE - }; - - // Helper to copy a file by reader and writer streams. - // Export for testing. - class STORAGE_EXPORT StreamCopyHelper { - public: - StreamCopyHelper( - scoped_ptr<storage::FileStreamReader> reader, - scoped_ptr<FileStreamWriter> writer, - bool need_flush, - int buffer_size, - const FileSystemOperation::CopyFileProgressCallback& - file_progress_callback, - const base::TimeDelta& min_progress_callback_invocation_span); - ~StreamCopyHelper(); - - void Run(const StatusCallback& callback); - - // Requests cancelling. After the cancelling is done, |callback| passed to - // Run will be called. - void Cancel(); - - private: - // Reads the content from the |reader_|. - void Read(const StatusCallback& callback); - void DidRead(const StatusCallback& callback, int result); - - // Writes the content in |buffer| to |writer_|. - void Write(const StatusCallback& callback, - scoped_refptr<net::DrainableIOBuffer> buffer); - void DidWrite(const StatusCallback& callback, - scoped_refptr<net::DrainableIOBuffer> buffer, int result); - - // Flushes the written content in |writer_|. - void Flush(const StatusCallback& callback, bool is_eof); - void DidFlush(const StatusCallback& callback, bool is_eof, int result); - - scoped_ptr<storage::FileStreamReader> reader_; - scoped_ptr<FileStreamWriter> writer_; - const bool need_flush_; - FileSystemOperation::CopyFileProgressCallback file_progress_callback_; - scoped_refptr<net::IOBufferWithSize> io_buffer_; - int64 num_copied_bytes_; - int64 previous_flush_offset_; - base::Time last_progress_callback_invocation_time_; - base::TimeDelta min_progress_callback_invocation_span_; - bool cancel_requested_; - base::WeakPtrFactory<StreamCopyHelper> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(StreamCopyHelper); - }; - - CopyOrMoveOperationDelegate( - FileSystemContext* file_system_context, - const FileSystemURL& src_root, - const FileSystemURL& dest_root, - OperationType operation_type, - CopyOrMoveOption option, - const CopyProgressCallback& progress_callback, - const StatusCallback& callback); - virtual ~CopyOrMoveOperationDelegate(); - - // RecursiveOperationDelegate overrides: - virtual void Run() OVERRIDE; - virtual void RunRecursively() OVERRIDE; - virtual void ProcessFile(const FileSystemURL& url, - const StatusCallback& callback) OVERRIDE; - virtual void ProcessDirectory(const FileSystemURL& url, - const StatusCallback& callback) OVERRIDE; - virtual void PostProcessDirectory(const FileSystemURL& url, - const StatusCallback& callback) OVERRIDE; - - - protected: - virtual void OnCancel() OVERRIDE; - - private: - void DidCopyOrMoveFile(const FileSystemURL& src_url, - const FileSystemURL& dest_url, - const StatusCallback& callback, - CopyOrMoveImpl* impl, - base::File::Error error); - void DidTryRemoveDestRoot(const StatusCallback& callback, - base::File::Error error); - void ProcessDirectoryInternal(const FileSystemURL& src_url, - const FileSystemURL& dest_url, - const StatusCallback& callback); - void DidCreateDirectory(const FileSystemURL& src_url, - const FileSystemURL& dest_url, - const StatusCallback& callback, - base::File::Error error); - void PostProcessDirectoryAfterGetMetadata( - const FileSystemURL& src_url, - const StatusCallback& callback, - base::File::Error error, - const base::File::Info& file_info); - void PostProcessDirectoryAfterTouchFile(const FileSystemURL& src_url, - const StatusCallback& callback, - base::File::Error error); - void DidRemoveSourceForMove(const StatusCallback& callback, - base::File::Error error); - - void OnCopyFileProgress(const FileSystemURL& src_url, int64 size); - FileSystemURL CreateDestURL(const FileSystemURL& src_url) const; - - FileSystemURL src_root_; - FileSystemURL dest_root_; - bool same_file_system_; - OperationType operation_type_; - CopyOrMoveOption option_; - CopyProgressCallback progress_callback_; - StatusCallback callback_; - - std::set<CopyOrMoveImpl*> running_copy_set_; - base::WeakPtrFactory<CopyOrMoveOperationDelegate> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(CopyOrMoveOperationDelegate); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_COPY_OR_MOVE_OPERATION_DELEGATE_H_ +#include "storage/browser/fileapi/copy_or_move_operation_delegate.h" diff --git a/webkit/browser/fileapi/dragged_file_util.h b/webkit/browser/fileapi/dragged_file_util.h index bc0da85..7a33fef 100644 --- a/webkit/browser/fileapi/dragged_file_util.h +++ b/webkit/browser/fileapi/dragged_file_util.h @@ -1,41 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_DRAGGED_FILE_UTIL_H_ -#define WEBKIT_BROWSER_FILEAPI_DRAGGED_FILE_UTIL_H_ - -#include "base/memory/scoped_ptr.h" -#include "webkit/browser/fileapi/local_file_util.h" -#include "webkit/browser/storage_browser_export.h" - -namespace storage { - -class FileSystemOperationContext; - -// Dragged file system is a specialized LocalFileUtil where read access to -// the virtual root directory (i.e. empty cracked path case) is allowed -// and single isolated context may be associated with multiple file paths. -class STORAGE_EXPORT_PRIVATE DraggedFileUtil - : public LocalFileUtil { - public: - DraggedFileUtil(); - virtual ~DraggedFileUtil() {} - - // FileSystemFileUtil overrides. - virtual base::File::Error GetFileInfo( - FileSystemOperationContext* context, - const FileSystemURL& url, - base::File::Info* file_info, - base::FilePath* platform_path) OVERRIDE; - virtual scoped_ptr<AbstractFileEnumerator> CreateFileEnumerator( - FileSystemOperationContext* context, - const FileSystemURL& root_url) OVERRIDE; - - private: - DISALLOW_COPY_AND_ASSIGN(DraggedFileUtil); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_DRAGGED_FILE_UTIL_H_ +#include "storage/browser/fileapi/dragged_file_util.h" diff --git a/webkit/browser/fileapi/external_mount_points.h b/webkit/browser/fileapi/external_mount_points.h index 842cba0..2cb7793 100644 --- a/webkit/browser/fileapi/external_mount_points.h +++ b/webkit/browser/fileapi/external_mount_points.h @@ -1,159 +1,5 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_EXTERNAL_MOUNT_POINTS_H_ -#define WEBKIT_BROWSER_FILEAPI_EXTERNAL_MOUNT_POINTS_H_ - -#include <map> -#include <string> -#include <vector> - -#include "base/memory/ref_counted.h" -#include "base/synchronization/lock.h" -#include "webkit/browser/fileapi/mount_points.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/fileapi/file_system_mount_option.h" -#include "webkit/common/fileapi/file_system_types.h" - -namespace base { -class FilePath; -} - -namespace storage { - -class FileSystemURL; - -// Manages external filesystem namespaces that are identified by 'mount name' -// and are persisted until RevokeFileSystem is called. -// Files in an external filesystem are identified by a filesystem URL like: -// -// filesystem:<origin>/external/<mount_name>/relative/path -// -class STORAGE_EXPORT ExternalMountPoints - : public base::RefCountedThreadSafe<ExternalMountPoints>, - public MountPoints { - public: - static ExternalMountPoints* GetSystemInstance(); - static scoped_refptr<ExternalMountPoints> CreateRefCounted(); - - // Registers a new named external filesystem. - // The |path| is registered as the root path of the mount point which - // is identified by a URL "filesystem:.../external/mount_name". - // - // For example, if the path "/media/removable" is registered with - // the mount_name "removable", a filesystem URL like - // "filesystem:.../external/removable/a/b" will be resolved as - // "/media/removable/a/b". - // - // The |mount_name| should NOT contain a path separator '/'. - // Returns false if the given name is already registered. - // - // Overlapping mount points in a single MountPoints instance are not allowed. - // Adding mount point whose path overlaps with an existing mount point will - // fail except for media galleries, which do not count toward registered - // paths for overlap calculation. - // - // If not empty, |path| must be absolute. It is allowed for the path to be - // empty, but |GetVirtualPath| will not work for those mount points. - // - // An external file system registered by this method can be revoked - // by calling RevokeFileSystem with |mount_name|. - bool RegisterFileSystem(const std::string& mount_name, - FileSystemType type, - const FileSystemMountOption& mount_option, - const base::FilePath& path); - - // MountPoints overrides. - virtual bool HandlesFileSystemMountType(FileSystemType type) const OVERRIDE; - virtual bool RevokeFileSystem(const std::string& mount_name) OVERRIDE; - virtual bool GetRegisteredPath(const std::string& mount_name, - base::FilePath* path) const OVERRIDE; - virtual bool CrackVirtualPath( - const base::FilePath& virtual_path, - std::string* mount_name, - FileSystemType* type, - std::string* cracked_id, - base::FilePath* path, - FileSystemMountOption* mount_option) const OVERRIDE; - virtual FileSystemURL CrackURL(const GURL& url) const OVERRIDE; - virtual FileSystemURL CreateCrackedFileSystemURL( - const GURL& origin, - FileSystemType type, - const base::FilePath& path) const OVERRIDE; - - // Returns a list of registered MountPointInfos (of <mount_name, path>). - void AddMountPointInfosTo(std::vector<MountPointInfo>* mount_points) const; - - // Converts a path on a registered file system to virtual path relative to the - // file system root. E.g. if 'Downloads' file system is mapped to - // '/usr/local/home/Downloads', and |absolute| path is set to - // '/usr/local/home/Downloads/foo', the method will set |virtual_path| to - // 'Downloads/foo'. - // Returns false if the path cannot be resolved (e.g. if the path is not - // part of any registered filesystem). - // - // Media gallery type file systems do not count for this calculation. i.e. - // if only a media gallery is registered for the path, false will be returned. - // If a media gallery and another file system are registered for related - // paths, only the other registration is taken into account. - // - // Returned virtual_path will have normalized path separators. - bool GetVirtualPath(const base::FilePath& absolute_path, - base::FilePath* virtual_path) const; - - // Returns the virtual root path that looks like /<mount_name>. - base::FilePath CreateVirtualRootPath(const std::string& mount_name) const; - - FileSystemURL CreateExternalFileSystemURL( - const GURL& origin, - const std::string& mount_name, - const base::FilePath& path) const; - - // Revoke all registered filesystems. Used only by testing (for clean-ups). - void RevokeAllFileSystems(); - - private: - friend class base::RefCountedThreadSafe<ExternalMountPoints>; - - // Represents each file system instance (defined in the .cc). - class Instance; - - typedef std::map<std::string, Instance*> NameToInstance; - - // Reverse map from registered path to its corresponding mount name. - typedef std::map<base::FilePath, std::string> PathToName; - - // Use |GetSystemInstance| of |CreateRefCounted| to get an instance. - ExternalMountPoints(); - virtual ~ExternalMountPoints(); - - // MountPoint overrides. - virtual FileSystemURL CrackFileSystemURL( - const FileSystemURL& url) const OVERRIDE; - - // Performs sanity checks on the new mount point. - // Checks the following: - // - there is no registered mount point with mount_name - // - path does not contain a reference to a parent - // - path is absolute - // - path does not overlap with an existing mount point path unless it is a - // media gallery type. - // - // |lock_| should be taken before calling this method. - bool ValidateNewMountPoint(const std::string& mount_name, - FileSystemType type, - const base::FilePath& path); - - // This lock needs to be obtained when accessing the instance_map_. - mutable base::Lock lock_; - - NameToInstance instance_map_; - PathToName path_to_name_map_; - - DISALLOW_COPY_AND_ASSIGN(ExternalMountPoints); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_EXTERNAL_MOUNT_POINTS_H_ +#include "storage/browser/fileapi/external_mount_points.h" diff --git a/webkit/browser/fileapi/file_observers.h b/webkit/browser/fileapi/file_observers.h index 2dfcc4e..a176f34 100644 --- a/webkit/browser/fileapi/file_observers.h +++ b/webkit/browser/fileapi/file_observers.h @@ -1,83 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_OBSERVERS_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_OBSERVERS_H_ - -#include "base/basictypes.h" -#include "webkit/browser/storage_browser_export.h" - -// TODO(kinuko): Split this file into per-observer multiple files. - -namespace storage { - -class FileSystemURL; - -// An abstract interface to observe update operations. -// -// OnStartUpdate and OnEndUpdate are called once for each target url -// before and after following operations regardless of whether the operation -// is made recursively or not (i.e. StartUpdate() will be called only once -// for destination url regardless of whether it is recursive copy or not): -// CreateFile(), CreateDirectory(), -// Copy() (destination only), -// Move() (both for source and destination), -// Remove(), Write(), Truncate(), TouchFile() -// -// OnUpdate() is called each time the |url| is updated but works only for -// sandboxed files (where usage is tracked). -class STORAGE_EXPORT FileUpdateObserver { - public: - FileUpdateObserver() {} - virtual ~FileUpdateObserver() {} - - virtual void OnStartUpdate(const FileSystemURL& url) = 0; - virtual void OnUpdate(const FileSystemURL& url, int64 delta) = 0; - virtual void OnEndUpdate(const FileSystemURL& url) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(FileUpdateObserver); -}; - -// An abstract interface to observe file access. -// OnAccess is called whenever an operation reads file contents or metadata. -// (It is called only once per operation regardless of whether the operation -// is recursive or not) -class STORAGE_EXPORT FileAccessObserver { - public: - FileAccessObserver() {} - virtual ~FileAccessObserver() {} - - virtual void OnAccess(const FileSystemURL& url) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(FileAccessObserver); -}; - -// An abstract interface to observe file changes. -// Each method of this class is called once per file/directory is created, -// removed or modified. For recursive operations each method is called for -// each subdirectory/subfile. Currently ChangeObserver is only supported -// by the local sandbox file system. -class STORAGE_EXPORT FileChangeObserver { - public: - FileChangeObserver() {} - virtual ~FileChangeObserver() {} - - virtual void OnCreateFile(const FileSystemURL& url) = 0; - virtual void OnCreateFileFrom(const FileSystemURL& url, - const FileSystemURL& src) = 0; - virtual void OnRemoveFile(const FileSystemURL& url) = 0; - virtual void OnModifyFile(const FileSystemURL& url) = 0; - - virtual void OnCreateDirectory(const FileSystemURL& url) = 0; - virtual void OnRemoveDirectory(const FileSystemURL& url) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(FileChangeObserver); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_OBSERVERS_H_ +#include "storage/browser/fileapi/file_observers.h" diff --git a/webkit/browser/fileapi/file_permission_policy.h b/webkit/browser/fileapi/file_permission_policy.h index 9cf0b1e..1ef299a 100644 --- a/webkit/browser/fileapi/file_permission_policy.h +++ b/webkit/browser/fileapi/file_permission_policy.h @@ -1,28 +1,5 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_PERMISSION_POLICY_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_PERMISSION_POLICY_H_ - -#include "webkit/browser/storage_browser_export.h" - -namespace storage { - -enum FilePermissionPolicy { - // Any access should be always denied. - FILE_PERMISSION_ALWAYS_DENY = 0x0, - - // Access is sandboxed, no extra permission check is necessary. - FILE_PERMISSION_SANDBOX = 1 << 0, - - // Access should be restricted to read-only. - FILE_PERMISSION_READ_ONLY = 1 << 1, - - // Access should be examined by per-file permission policy. - FILE_PERMISSION_USE_FILE_PERMISSION = 1 << 2, -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_PERMISSION_POLICY_H_ +#include "storage/browser/fileapi/file_permission_policy.h" diff --git a/webkit/browser/fileapi/file_stream_writer.h b/webkit/browser/fileapi/file_stream_writer.h index d2467b3..9a6e6f3 100644 --- a/webkit/browser/fileapi/file_stream_writer.h +++ b/webkit/browser/fileapi/file_stream_writer.h @@ -1,87 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_STREAM_WRITER_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_STREAM_WRITER_H_ - -#include "base/basictypes.h" -#include "net/base/completion_callback.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class FilePath; -class TaskRunner; -} - -namespace net { -class IOBuffer; -} - -namespace storage { - -// A generic interface for writing to a file-like object. -class FileStreamWriter { - public: - enum OpenOrCreate { OPEN_EXISTING_FILE, CREATE_NEW_FILE }; - - // Creates a writer for the existing file in the path |file_path| starting - // from |initial_offset|. Uses |task_runner| for async file operations. - STORAGE_EXPORT static FileStreamWriter* CreateForLocalFile( - base::TaskRunner* task_runner, - const base::FilePath& file_path, - int64 initial_offset, - OpenOrCreate open_or_create); - - // Closes the file. If there's an in-flight operation, it is canceled (i.e., - // the callback function associated with the operation is not called). - virtual ~FileStreamWriter() {} - - // Writes to the current cursor position asynchronously. - // - // Up to buf_len bytes will be written. (In other words, partial - // writes are allowed.) If the write completed synchronously, it returns - // the number of bytes written. If the operation could not be performed, it - // returns an error code. Otherwise, net::ERR_IO_PENDING is returned, and the - // callback will be run on the thread where Write() was called when the write - // has completed. - // - // This errors out (either synchronously or via callback) with: - // net::ERR_FILE_NOT_FOUND: When the target file is not found. - // net::ERR_ACCESS_DENIED: When the target file is a directory or - // the writer has no permission on the file. - // net::ERR_FILE_NO_SPACE: When the write will result in out of quota - // or there is not enough room left on the disk. - // - // It is invalid to call Write while there is an in-flight async operation. - virtual int Write(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) = 0; - - // Cancels an in-flight async operation. - // - // If the cancel is finished synchronously, it returns net::OK. If the - // cancel could not be performed, it returns an error code. Especially when - // there is no in-flight operation, net::ERR_UNEXPECTED is returned. - // Otherwise, net::ERR_IO_PENDING is returned, and the callback will be run on - // the thread where Cancel() was called when the cancel has completed. It is - // invalid to call Cancel() more than once on the same async operation. - // - // In either case, the callback function passed to the in-flight async - // operation is dismissed immediately when Cancel() is called, and thus - // will never be called. - virtual int Cancel(const net::CompletionCallback& callback) = 0; - - // Flushes the data written so far. - // - // If the flush finished synchronously, it return net::OK. If the flush could - // not be performed, it returns an error code. Otherwise, net::ERR_IO_PENDING - // is returned, and the callback will be run on the thread where Flush() was - // called when the flush has completed. - // - // It is invalid to call Flush while there is an in-flight async operation. - virtual int Flush(const net::CompletionCallback& callback) = 0; -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_STREAM_WRITER_H_ +#include "storage/browser/fileapi/file_stream_writer.h" diff --git a/webkit/browser/fileapi/file_system_backend.h b/webkit/browser/fileapi/file_system_backend.h index 43bc3af..266819e 100644 --- a/webkit/browser/fileapi/file_system_backend.h +++ b/webkit/browser/fileapi/file_system_backend.h @@ -1,169 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_BACKEND_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_BACKEND_H_ - -#include <string> -#include <vector> - -#include "base/callback_forward.h" -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" -#include "webkit/browser/fileapi/file_permission_policy.h" -#include "webkit/browser/fileapi/open_file_system_mode.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/fileapi/file_system_types.h" - -class GURL; - -namespace storage { - -class AsyncFileUtil; -class CopyOrMoveFileValidatorFactory; -class FileSystemURL; -class FileStreamReader; -class FileStreamWriter; -class FileSystemContext; -class FileSystemFileUtil; -class FileSystemOperation; -class FileSystemQuotaUtil; -class WatcherManager; - -// Callback to take GURL. -typedef base::Callback<void(const GURL& url)> URLCallback; - -// An interface for defining a file system backend. -// -// NOTE: when you implement a new FileSystemBackend for your own -// FileSystem module, please contact to kinuko@chromium.org. -// -class STORAGE_EXPORT FileSystemBackend { - public: - // Callback for InitializeFileSystem. - typedef base::Callback<void(const GURL& root_url, - const std::string& name, - base::File::Error error)> - OpenFileSystemCallback; - virtual ~FileSystemBackend() {} - - // Returns true if this filesystem backend can handle |type|. - // One filesystem backend may be able to handle multiple filesystem types. - virtual bool CanHandleType(FileSystemType type) const = 0; - - // This method is called right after the backend is registered in the - // FileSystemContext and before any other methods are called. Each backend can - // do additional initialization which depends on FileSystemContext here. - virtual void Initialize(FileSystemContext* context) = 0; - - // Resolves the filesystem root URL and the name for the given |url|. - // This verifies if it is allowed to request (or create) the filesystem and if - // it can access (or create) the root directory. - // If |mode| is CREATE_IF_NONEXISTENT calling this may also create the root - // directory (and/or related database entries etc) for the filesystem if it - // doesn't exist. - virtual void ResolveURL(const FileSystemURL& url, - OpenFileSystemMode mode, - const OpenFileSystemCallback& callback) = 0; - - // Returns the specialized AsyncFileUtil for this backend. - virtual AsyncFileUtil* GetAsyncFileUtil(FileSystemType type) = 0; - - // Returns the specialized WatcherManager for this backend. - virtual WatcherManager* GetWatcherManager(FileSystemType type) = 0; - - // Returns the specialized CopyOrMoveFileValidatorFactory for this backend - // and |type|. If |error_code| is File::FILE_OK and the result is NULL, - // then no validator is required. - virtual CopyOrMoveFileValidatorFactory* GetCopyOrMoveFileValidatorFactory( - FileSystemType type, base::File::Error* error_code) = 0; - - // Returns a new instance of the specialized FileSystemOperation for this - // backend based on the given triplet of |origin_url|, |file_system_type| - // and |virtual_path|. On failure to create a file system operation, set - // |error_code| correspondingly. - // This method is usually dispatched by - // FileSystemContext::CreateFileSystemOperation. - virtual FileSystemOperation* CreateFileSystemOperation( - const FileSystemURL& url, - FileSystemContext* context, - base::File::Error* error_code) const = 0; - - // Returns true if Blobs accessing |url| should use FileStreamReader. - // If false, Blobs are accessed using a snapshot file by calling - // AsyncFileUtil::CreateSnapshotFile. - virtual bool SupportsStreaming(const FileSystemURL& url) const = 0; - - // Returns true if specified |type| of filesystem can handle Copy() - // of the files in the same file system instead of streaming - // read/write implementation. - virtual bool HasInplaceCopyImplementation(FileSystemType type) const = 0; - - // Creates a new file stream reader for a given filesystem URL |url| with an - // offset |offset|. |expected_modification_time| specifies the expected last - // modification if the value is non-null, the reader will check the underlying - // file's actual modification time to see if the file has been modified, and - // if it does any succeeding read operations should fail with - // ERR_UPLOAD_FILE_CHANGED error. - // This method itself does *not* check if the given path exists and is a - // regular file. - // The |length| argument says how many bytes are going to be read using the - // instance of the file stream reader. If unknown, then equal to -1. - virtual scoped_ptr<storage::FileStreamReader> CreateFileStreamReader( - const FileSystemURL& url, - int64 offset, - const base::Time& expected_modification_time, - FileSystemContext* context) const = 0; - - // Creates a new file stream writer for a given filesystem URL |url| with an - // offset |offset|. - // This method itself does *not* check if the given path exists and is a - // regular file. - virtual scoped_ptr<FileStreamWriter> CreateFileStreamWriter( - const FileSystemURL& url, - int64 offset, - FileSystemContext* context) const = 0; - - // Returns the specialized FileSystemQuotaUtil for this backend. - // This could return NULL if this backend does not support quota. - virtual FileSystemQuotaUtil* GetQuotaUtil() = 0; -}; - -// An interface to control external file system access permissions. -// TODO(satorux): Move this out of 'webkit/browser/fileapi'. crbug.com/257279 -class ExternalFileSystemBackend : public FileSystemBackend { - public: - // Returns true if |url| is allowed to be accessed. - // This is supposed to perform ExternalFileSystem-specific security - // checks. - virtual bool IsAccessAllowed(const storage::FileSystemURL& url) const = 0; - // Returns the list of top level directories that are exposed by this - // provider. This list is used to set appropriate child process file access - // permissions. - virtual std::vector<base::FilePath> GetRootDirectories() const = 0; - // Grants access to all external file system from extension identified with - // |extension_id|. - virtual void GrantFullAccessToExtension(const std::string& extension_id) = 0; - // Grants access to |virtual_path| from |origin_url|. - virtual void GrantFileAccessToExtension( - const std::string& extension_id, - const base::FilePath& virtual_path) = 0; - // Revokes file access from extension identified with |extension_id|. - virtual void RevokeAccessForExtension( - const std::string& extension_id) = 0; - // Gets virtual path by known filesystem path. Returns false when filesystem - // path is not exposed by this provider. - virtual bool GetVirtualPath(const base::FilePath& file_system_path, - base::FilePath* virtual_path) = 0; - // Gets a redirect URL for contents. e.g. Google Drive URL for hosted - // documents. Returns empty URL if the entry does not have the redirect URL. - virtual void GetRedirectURLForContents( - const storage::FileSystemURL& url, - const storage::URLCallback& callback) = 0; -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_BACKEND_H_ +#include "storage/browser/fileapi/file_system_backend.h" diff --git a/webkit/browser/fileapi/file_system_context.h b/webkit/browser/fileapi/file_system_context.h index f410195..6b016b9 100644 --- a/webkit/browser/fileapi/file_system_context.h +++ b/webkit/browser/fileapi/file_system_context.h @@ -1,428 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_CONTEXT_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_CONTEXT_H_ - -#include <map> -#include <string> -#include <vector> - -#include "base/callback.h" -#include "base/files/file.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/scoped_vector.h" -#include "base/sequenced_task_runner_helpers.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/fileapi/open_file_system_mode.h" -#include "webkit/browser/fileapi/plugin_private_file_system_backend.h" -#include "webkit/browser/fileapi/sandbox_file_system_backend_delegate.h" -#include "webkit/browser/fileapi/task_runner_bound_observer_list.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/fileapi/file_system_types.h" - -namespace base { -class FilePath; -class SequencedTaskRunner; -class SingleThreadTaskRunner; -} - -namespace chrome { -class NativeMediaFileUtilTest; -} - -namespace storage { -class QuotaManagerProxy; -class SpecialStoragePolicy; -} - -namespace net { -class URLRequest; -} - -namespace storage { -class BlobURLRequestJobTest; -class FileStreamReader; -} - -namespace storage { - -class AsyncFileUtil; -class CopyOrMoveFileValidatorFactory; -class ExternalFileSystemBackend; -class ExternalMountPoints; -class FileStreamWriter; -class FileSystemBackend; -class FileSystemFileUtil; -class FileSystemOperation; -class FileSystemOperationRunner; -class FileSystemOptions; -class FileSystemQuotaUtil; -class FileSystemURL; -class IsolatedFileSystemBackend; -class MountPoints; -class QuotaReservation; -class SandboxFileSystemBackend; -class WatchManager; - -struct DefaultContextDeleter; -struct FileSystemInfo; - -// An auto mount handler will attempt to mount the file system requested in -// |url_request|. If the URL is for this auto mount handler, it returns true -// and calls |callback| when the attempt is complete. If the auto mounter -// does not recognize the URL, it returns false and does not call |callback|. -// Called on the IO thread. -typedef base::Callback<bool( - const net::URLRequest* url_request, - const FileSystemURL& filesystem_url, - const std::string& storage_domain, - const base::Callback<void(base::File::Error result)>& callback)> - URLRequestAutoMountHandler; - -// This class keeps and provides a file system context for FileSystem API. -// An instance of this class is created and owned by profile. -class STORAGE_EXPORT FileSystemContext - : public base::RefCountedThreadSafe<FileSystemContext, - DefaultContextDeleter> { - public: - // Returns file permission policy we should apply for the given |type|. - // The return value must be bitwise-or'd of FilePermissionPolicy. - // - // Note: if a part of a filesystem is returned via 'Isolated' mount point, - // its per-filesystem permission overrides the underlying filesystem's - // permission policy. - static int GetPermissionPolicy(FileSystemType type); - - // file_task_runner is used as default TaskRunner. - // Unless a FileSystemBackend is overridden in CreateFileSystemOperation, - // it is used for all file operations and file related meta operations. - // The code assumes that file_task_runner->RunsTasksOnCurrentThread() - // returns false if the current task is not running on the thread that allows - // blocking file operations (like SequencedWorkerPool implementation does). - // - // |external_mount_points| contains non-system external mount points available - // in the context. If not NULL, it will be used during URL cracking. - // |external_mount_points| may be NULL only on platforms different from - // ChromeOS (i.e. platforms that don't use external_mount_point_provider). - // - // |additional_backends| are added to the internal backend map - // to serve filesystem requests for non-regular types. - // If none is given, this context only handles HTML5 Sandbox FileSystem - // and Drag-and-drop Isolated FileSystem requests. - // - // |auto_mount_handlers| are used to resolve calls to - // AttemptAutoMountForURLRequest. Only external filesystems are auto mounted - // when a filesystem: URL request is made. - FileSystemContext( - base::SingleThreadTaskRunner* io_task_runner, - base::SequencedTaskRunner* file_task_runner, - ExternalMountPoints* external_mount_points, - storage::SpecialStoragePolicy* special_storage_policy, - storage::QuotaManagerProxy* quota_manager_proxy, - ScopedVector<FileSystemBackend> additional_backends, - const std::vector<URLRequestAutoMountHandler>& auto_mount_handlers, - const base::FilePath& partition_path, - const FileSystemOptions& options); - - bool DeleteDataForOriginOnFileTaskRunner(const GURL& origin_url); - - // Creates a new QuotaReservation for the given |origin_url| and |type|. - // Returns NULL if |type| does not support quota or reservation fails. - // This should be run on |default_file_task_runner_| and the returned value - // should be destroyed on the runner. - scoped_refptr<QuotaReservation> CreateQuotaReservationOnFileTaskRunner( - const GURL& origin_url, - FileSystemType type); - - storage::QuotaManagerProxy* quota_manager_proxy() const { - return quota_manager_proxy_.get(); - } - - // Discards inflight operations in the operation runner. - void Shutdown(); - - // Returns a quota util for a given filesystem type. This may - // return NULL if the type does not support the usage tracking or - // it is not a quota-managed storage. - FileSystemQuotaUtil* GetQuotaUtil(FileSystemType type) const; - - // Returns the appropriate AsyncFileUtil instance for the given |type|. - AsyncFileUtil* GetAsyncFileUtil(FileSystemType type) const; - - // Returns the appropriate CopyOrMoveFileValidatorFactory for the given - // |type|. If |error_code| is File::FILE_OK and the result is NULL, - // then no validator is required. - CopyOrMoveFileValidatorFactory* GetCopyOrMoveFileValidatorFactory( - FileSystemType type, base::File::Error* error_code) const; - - // Returns the file system backend instance for the given |type|. - // This may return NULL if it is given an invalid or unsupported filesystem - // type. - FileSystemBackend* GetFileSystemBackend( - FileSystemType type) const; - - // Returns the watcher manager for the given |type|. - // This may return NULL if the type does not support watching. - WatcherManager* GetWatcherManager(FileSystemType type) const; - - // Returns true for sandboxed filesystems. Currently this does - // the same as GetQuotaUtil(type) != NULL. (In an assumption that - // all sandboxed filesystems must cooperate with QuotaManager so that - // they can get deleted) - bool IsSandboxFileSystem(FileSystemType type) const; - - // Returns observers for the given filesystem type. - const UpdateObserverList* GetUpdateObservers(FileSystemType type) const; - const ChangeObserverList* GetChangeObservers(FileSystemType type) const; - const AccessObserverList* GetAccessObservers(FileSystemType type) const; - - // Returns all registered filesystem types. - void GetFileSystemTypes(std::vector<FileSystemType>* types) const; - - // Returns a FileSystemBackend instance for external filesystem - // type, which is used only by chromeos for now. This is equivalent to - // calling GetFileSystemBackend(kFileSystemTypeExternal). - ExternalFileSystemBackend* external_backend() const; - - // Used for OpenFileSystem. - typedef base::Callback<void(const GURL& root, - const std::string& name, - base::File::Error result)> - OpenFileSystemCallback; - - // Used for ResolveURL. - enum ResolvedEntryType { - RESOLVED_ENTRY_FILE, - RESOLVED_ENTRY_DIRECTORY, - RESOLVED_ENTRY_NOT_FOUND, - }; - typedef base::Callback<void(base::File::Error result, - const FileSystemInfo& info, - const base::FilePath& file_path, - ResolvedEntryType type)> ResolveURLCallback; - - // Used for DeleteFileSystem and OpenPluginPrivateFileSystem. - typedef base::Callback<void(base::File::Error result)> StatusCallback; - - // Opens the filesystem for the given |origin_url| and |type|, and dispatches - // |callback| on completion. - // If |create| is true this may actually set up a filesystem instance - // (e.g. by creating the root directory or initializing the database - // entry etc). - void OpenFileSystem( - const GURL& origin_url, - FileSystemType type, - OpenFileSystemMode mode, - const OpenFileSystemCallback& callback); - - // Opens the filesystem for the given |url| as read-only, if the filesystem - // backend referred by the URL allows opening by resolveURL. Otherwise it - // fails with FILE_ERROR_SECURITY. The entry pointed by the URL can be - // absent; in that case RESOLVED_ENTRY_NOT_FOUND type is returned to the - // callback for indicating the absence. Can be called from any thread with - // a message loop. |callback| is invoked on the caller thread. - void ResolveURL( - const FileSystemURL& url, - const ResolveURLCallback& callback); - - // Attempts to mount the filesystem needed to satisfy |url_request| made - // from |storage_domain|. If an appropriate file system is not found, - // callback will return an error. - void AttemptAutoMountForURLRequest(const net::URLRequest* url_request, - const std::string& storage_domain, - const StatusCallback& callback); - - // Deletes the filesystem for the given |origin_url| and |type|. This should - // be called on the IO thread. - void DeleteFileSystem( - const GURL& origin_url, - FileSystemType type, - const StatusCallback& callback); - - // Creates new FileStreamReader instance to read a file pointed by the given - // filesystem URL |url| starting from |offset|. |expected_modification_time| - // specifies the expected last modification if the value is non-null, the - // reader will check the underlying file's actual modification time to see if - // the file has been modified, and if it does any succeeding read operations - // should fail with ERR_UPLOAD_FILE_CHANGED error. - // This method internally cracks the |url|, get an appropriate - // FileSystemBackend for the URL and call the backend's CreateFileReader. - // The resolved FileSystemBackend could perform further specialization - // depending on the filesystem type pointed by the |url|. - scoped_ptr<storage::FileStreamReader> CreateFileStreamReader( - const FileSystemURL& url, - int64 offset, - const base::Time& expected_modification_time); - - // Creates new FileStreamWriter instance to write into a file pointed by - // |url| from |offset|. - scoped_ptr<FileStreamWriter> CreateFileStreamWriter( - const FileSystemURL& url, - int64 offset); - - // Creates a new FileSystemOperationRunner. - scoped_ptr<FileSystemOperationRunner> CreateFileSystemOperationRunner(); - - base::SequencedTaskRunner* default_file_task_runner() { - return default_file_task_runner_.get(); - } - - FileSystemOperationRunner* operation_runner() { - return operation_runner_.get(); - } - - const base::FilePath& partition_path() const { return partition_path_; } - - // Same as |CrackFileSystemURL|, but cracks FileSystemURL created from |url|. - FileSystemURL CrackURL(const GURL& url) const; - // Same as |CrackFileSystemURL|, but cracks FileSystemURL created from method - // arguments. - FileSystemURL CreateCrackedFileSystemURL(const GURL& origin, - FileSystemType type, - const base::FilePath& path) const; - -#if defined(OS_CHROMEOS) - // Used only on ChromeOS for now. - void EnableTemporaryFileSystemInIncognito(); -#endif - - SandboxFileSystemBackendDelegate* sandbox_delegate() { - return sandbox_delegate_.get(); - } - - // Returns true if the requested url is ok to be served. - // (E.g. this returns false if the context is created for incognito mode) - bool CanServeURLRequest(const FileSystemURL& url) const; - - // Returns true if a file in the file system should be flushed for each write - // completion. - bool ShouldFlushOnWriteCompletion(FileSystemType type) const; - - // This must be used to open 'plugin private' filesystem. - // See "plugin_private_file_system_backend.h" for more details. - void OpenPluginPrivateFileSystem( - const GURL& origin_url, - FileSystemType type, - const std::string& filesystem_id, - const std::string& plugin_id, - OpenFileSystemMode mode, - const StatusCallback& callback); - - private: - typedef std::map<FileSystemType, FileSystemBackend*> - FileSystemBackendMap; - - // For CreateFileSystemOperation. - friend class FileSystemOperationRunner; - - // For sandbox_backend(). - friend class content::SandboxFileSystemTestHelper; - - // For plugin_private_backend(). - friend class content::PluginPrivateFileSystemBackendTest; - - // Deleters. - friend struct DefaultContextDeleter; - friend class base::DeleteHelper<FileSystemContext>; - friend class base::RefCountedThreadSafe<FileSystemContext, - DefaultContextDeleter>; - ~FileSystemContext(); - - void DeleteOnCorrectThread() const; - - // Creates a new FileSystemOperation instance by getting an appropriate - // FileSystemBackend for |url| and calling the backend's corresponding - // CreateFileSystemOperation method. - // The resolved FileSystemBackend could perform further specialization - // depending on the filesystem type pointed by the |url|. - // - // Called by FileSystemOperationRunner. - FileSystemOperation* CreateFileSystemOperation( - const FileSystemURL& url, - base::File::Error* error_code); - - // For non-cracked isolated and external mount points, returns a FileSystemURL - // created by cracking |url|. The url is cracked using MountPoints registered - // as |url_crackers_|. If the url cannot be cracked, returns invalid - // FileSystemURL. - // - // If the original url does not point to an isolated or external filesystem, - // returns the original url, without attempting to crack it. - FileSystemURL CrackFileSystemURL(const FileSystemURL& url) const; - - // For initial backend_map construction. This must be called only from - // the constructor. - void RegisterBackend(FileSystemBackend* backend); - - void DidOpenFileSystemForResolveURL( - const FileSystemURL& url, - const ResolveURLCallback& callback, - const GURL& filesystem_root, - const std::string& filesystem_name, - base::File::Error error); - - // Returns a FileSystemBackend, used only by test code. - SandboxFileSystemBackend* sandbox_backend() const { - return sandbox_backend_.get(); - } - - // Used only by test code. - PluginPrivateFileSystemBackend* plugin_private_backend() const { - return plugin_private_backend_.get(); - } - - scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_; - scoped_refptr<base::SequencedTaskRunner> default_file_task_runner_; - - scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy_; - - scoped_ptr<SandboxFileSystemBackendDelegate> sandbox_delegate_; - - // Regular file system backends. - scoped_ptr<SandboxFileSystemBackend> sandbox_backend_; - scoped_ptr<IsolatedFileSystemBackend> isolated_backend_; - - // Additional file system backends. - scoped_ptr<PluginPrivateFileSystemBackend> plugin_private_backend_; - ScopedVector<FileSystemBackend> additional_backends_; - - std::vector<URLRequestAutoMountHandler> auto_mount_handlers_; - - // Registered file system backends. - // The map must be constructed in the constructor since it can be accessed - // on multiple threads. - // This map itself doesn't retain each backend's ownership; ownerships - // of the backends are held by additional_backends_ or other scoped_ptr - // backend fields. - FileSystemBackendMap backend_map_; - - // External mount points visible in the file system context (excluding system - // external mount points). - scoped_refptr<ExternalMountPoints> external_mount_points_; - - // MountPoints used to crack FileSystemURLs. The MountPoints are ordered - // in order they should try to crack a FileSystemURL. - std::vector<MountPoints*> url_crackers_; - - // The base path of the storage partition for this context. - const base::FilePath partition_path_; - - bool is_incognito_; - - scoped_ptr<FileSystemOperationRunner> operation_runner_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(FileSystemContext); -}; - -struct DefaultContextDeleter { - static void Destruct(const FileSystemContext* context) { - context->DeleteOnCorrectThread(); - } -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_CONTEXT_H_ +#include "storage/browser/fileapi/file_system_context.h" diff --git a/webkit/browser/fileapi/file_system_dir_url_request_job.h b/webkit/browser/fileapi/file_system_dir_url_request_job.h index 081792d..ad3285d 100644 --- a/webkit/browser/fileapi/file_system_dir_url_request_job.h +++ b/webkit/browser/fileapi/file_system_dir_url_request_job.h @@ -1,69 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_DIR_URL_REQUEST_JOB_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_DIR_URL_REQUEST_JOB_H_ - -#include <string> -#include <vector> - -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/memory/weak_ptr.h" -#include "base/message_loop/message_loop_proxy.h" -#include "net/url_request/url_request_job.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/storage_browser_export.h" - -namespace storage { - -class FileSystemContext; -struct DirectoryEntry; - -// A request job that handles reading filesystem: URLs for directories. -class STORAGE_EXPORT_PRIVATE FileSystemDirURLRequestJob - : public net::URLRequestJob { - public: - FileSystemDirURLRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const std::string& storage_domain, - FileSystemContext* file_system_context); - - // URLRequestJob methods: - virtual void Start() OVERRIDE; - virtual void Kill() OVERRIDE; - virtual bool ReadRawData(net::IOBuffer* buf, - int buf_size, - int* bytes_read) OVERRIDE; - virtual bool GetCharset(std::string* charset) OVERRIDE; - - // FilterContext methods (via URLRequestJob): - virtual bool GetMimeType(std::string* mime_type) const OVERRIDE; - // TODO(adamk): Implement GetResponseInfo and GetResponseCode to simulate - // an HTTP response. - - private: - class CallbackDispatcher; - - virtual ~FileSystemDirURLRequestJob(); - - void StartAsync(); - void DidAttemptAutoMount(base::File::Error result); - void DidReadDirectory(base::File::Error result, - const std::vector<DirectoryEntry>& entries, - bool has_more); - - std::string data_; - FileSystemURL url_; - const std::string storage_domain_; - FileSystemContext* file_system_context_; - base::WeakPtrFactory<FileSystemDirURLRequestJob> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(FileSystemDirURLRequestJob); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_DIR_URL_REQUEST_JOB_H_ +#include "storage/browser/fileapi/file_system_dir_url_request_job.h" diff --git a/webkit/browser/fileapi/file_system_file_stream_reader.h b/webkit/browser/fileapi/file_system_file_stream_reader.h index 8845aa0..3290fa0 100644 --- a/webkit/browser/fileapi/file_system_file_stream_reader.h +++ b/webkit/browser/fileapi/file_system_file_stream_reader.h @@ -1,79 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_FILE_STREAM_READER_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_FILE_STREAM_READER_H_ - -#include "base/bind.h" -#include "base/files/file.h" -#include "base/memory/ref_counted.h" -#include "base/time/time.h" -#include "webkit/browser/blob/file_stream_reader.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/blob/shareable_file_reference.h" - -namespace base { -class FilePath; -class SequencedTaskRunner; -} - -namespace content { -class FileSystemFileStreamReaderTest; -} - -namespace storage { - -class FileSystemContext; - -// Generic FileStreamReader implementation for FileSystem files. -// Note: This generic implementation would work for any filesystems but -// remote filesystem should implement its own reader rather than relying -// on FileSystemOperation::GetSnapshotFile() which may force downloading -// the entire contents for remote files. -class STORAGE_EXPORT_PRIVATE FileSystemFileStreamReader - : public NON_EXPORTED_BASE(storage::FileStreamReader) { - public: - virtual ~FileSystemFileStreamReader(); - - // FileStreamReader overrides. - virtual int Read(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) OVERRIDE; - virtual int64 GetLength( - const net::Int64CompletionCallback& callback) OVERRIDE; - - private: - friend class storage::FileStreamReader; - friend class content::FileSystemFileStreamReaderTest; - - FileSystemFileStreamReader(FileSystemContext* file_system_context, - const FileSystemURL& url, - int64 initial_offset, - const base::Time& expected_modification_time); - - int CreateSnapshot(const base::Closure& callback, - const net::CompletionCallback& error_callback); - void DidCreateSnapshot( - const base::Closure& callback, - const net::CompletionCallback& error_callback, - base::File::Error file_error, - const base::File::Info& file_info, - const base::FilePath& platform_path, - const scoped_refptr<storage::ShareableFileReference>& file_ref); - - scoped_refptr<FileSystemContext> file_system_context_; - FileSystemURL url_; - const int64 initial_offset_; - const base::Time expected_modification_time_; - scoped_ptr<storage::FileStreamReader> local_file_reader_; - scoped_refptr<storage::ShareableFileReference> snapshot_ref_; - bool has_pending_create_snapshot_; - base::WeakPtrFactory<FileSystemFileStreamReader> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(FileSystemFileStreamReader); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_FILE_STREAM_READER_H_ +#include "storage/browser/fileapi/file_system_file_stream_reader.h" diff --git a/webkit/browser/fileapi/file_system_file_util.h b/webkit/browser/fileapi/file_system_file_util.h index 2a93787..5aa3676 100644 --- a/webkit/browser/fileapi/file_system_file_util.h +++ b/webkit/browser/fileapi/file_system_file_util.h @@ -1,186 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_FILE_UTIL_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_FILE_UTIL_H_ - -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" -#include "webkit/browser/fileapi/file_system_operation.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/blob/scoped_file.h" - -namespace base { -class Time; -} - -namespace storage { - -class FileSystemOperationContext; -class FileSystemURL; - -// A file utility interface that provides basic file utility methods for -// FileSystem API. -// -// Layering structure of the FileSystemFileUtil was split out. -// See http://crbug.com/128136 if you need it. -class STORAGE_EXPORT FileSystemFileUtil { - public: - typedef FileSystemOperation::CopyOrMoveOption CopyOrMoveOption; - - // It will be implemented by each subclass such as FileSystemFileEnumerator. - class STORAGE_EXPORT AbstractFileEnumerator { - public: - virtual ~AbstractFileEnumerator() {} - - // Returns an empty string if there are no more results. - virtual base::FilePath Next() = 0; - - // These methods return metadata for the file most recently returned by - // Next(). If Next() has never been called, or if Next() most recently - // returned an empty string, then return the default values of 0, - // "null time", and false, respectively. - virtual int64 Size() = 0; - virtual base::Time LastModifiedTime() = 0; - virtual bool IsDirectory() = 0; - }; - - class STORAGE_EXPORT EmptyFileEnumerator - : public AbstractFileEnumerator { - virtual base::FilePath Next() OVERRIDE; - virtual int64 Size() OVERRIDE; - virtual base::Time LastModifiedTime() OVERRIDE; - virtual bool IsDirectory() OVERRIDE; - }; - - virtual ~FileSystemFileUtil() {} - - // Creates or opens a file with the given flags. - // See header comments for AsyncFileUtil::CreateOrOpen() for more details. - // This is used only by Pepper/NaCl File API. - virtual base::File CreateOrOpen( - FileSystemOperationContext* context, - const FileSystemURL& url, - int file_flags) = 0; - - // Ensures that the given |url| exist. This creates a empty new file - // at |url| if the |url| does not exist. - // See header comments for AsyncFileUtil::EnsureFileExists() for more details. - virtual base::File::Error EnsureFileExists( - FileSystemOperationContext* context, - const FileSystemURL& url, bool* created) = 0; - - // Creates directory at given url. - // See header comments for AsyncFileUtil::CreateDirectory() for more details. - virtual base::File::Error CreateDirectory( - FileSystemOperationContext* context, - const FileSystemURL& url, - bool exclusive, - bool recursive) = 0; - - // Retrieves the information about a file. - // See header comments for AsyncFileUtil::GetFileInfo() for more details. - virtual base::File::Error GetFileInfo( - FileSystemOperationContext* context, - const FileSystemURL& url, - base::File::Info* file_info, - base::FilePath* platform_path) = 0; - - // Returns a pointer to a new instance of AbstractFileEnumerator which is - // implemented for each FileSystemFileUtil subclass. The instance needs to be - // freed by the caller, and its lifetime should not extend past when the - // current call returns to the main FILE message loop. - // - // The supplied context must remain valid at least lifetime of the enumerator - // instance. - virtual scoped_ptr<AbstractFileEnumerator> CreateFileEnumerator( - FileSystemOperationContext* context, - const FileSystemURL& root_url) = 0; - - // Maps |file_system_url| given |context| into |local_file_path| - // which represents physical file location on the host OS. - // This may not always make sense for all subclasses. - virtual base::File::Error GetLocalFilePath( - FileSystemOperationContext* context, - const FileSystemURL& file_system_url, - base::FilePath* local_file_path) = 0; - - // Updates the file metadata information. - // See header comments for AsyncFileUtil::Touch() for more details. - virtual base::File::Error Touch( - FileSystemOperationContext* context, - const FileSystemURL& url, - const base::Time& last_access_time, - const base::Time& last_modified_time) = 0; - - // Truncates a file to the given length. - // See header comments for AsyncFileUtil::Truncate() for more details. - virtual base::File::Error Truncate( - FileSystemOperationContext* context, - const FileSystemURL& url, - int64 length) = 0; - - // Copies or moves a single file from |src_url| to |dest_url|. - // The filesystem type of |src_url| and |dest_url| MUST be same. - // For |option|, please see file_system_operation.h - // - // This returns: - // - File::FILE_ERROR_NOT_FOUND if |src_url| - // or the parent directory of |dest_url| does not exist. - // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. - // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and - // is not a file. - // - File::FILE_ERROR_FAILED if |dest_url| does not exist and - // its parent path is a file. - // - virtual base::File::Error CopyOrMoveFile( - FileSystemOperationContext* context, - const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - bool copy) = 0; - - // Copies in a single file from a different filesystem. - // See header comments for AsyncFileUtil::CopyInForeignFile() for - // more details. - virtual base::File::Error CopyInForeignFile( - FileSystemOperationContext* context, - const base::FilePath& src_file_path, - const FileSystemURL& dest_url) = 0; - - // Deletes a single file. - // See header comments for AsyncFileUtil::DeleteFile() for more details. - virtual base::File::Error DeleteFile( - FileSystemOperationContext* context, - const FileSystemURL& url) = 0; - - // Deletes a single empty directory. - // See header comments for AsyncFileUtil::DeleteDirectory() for more details. - virtual base::File::Error DeleteDirectory( - FileSystemOperationContext* context, - const FileSystemURL& url) = 0; - - // Creates a local snapshot file for a given |url| and returns the - // metadata and platform path of the snapshot file via |callback|. - // - // See header comments for AsyncFileUtil::CreateSnapshotFile() for - // more details. - virtual storage::ScopedFile CreateSnapshotFile( - FileSystemOperationContext* context, - const FileSystemURL& url, - base::File::Error* error, - base::File::Info* file_info, - base::FilePath* platform_path) = 0; - - protected: - FileSystemFileUtil() {} - - private: - DISALLOW_COPY_AND_ASSIGN(FileSystemFileUtil); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_FILE_UTIL_H_ +#include "storage/browser/fileapi/file_system_file_util.h" diff --git a/webkit/browser/fileapi/file_system_operation.h b/webkit/browser/fileapi/file_system_operation.h index 7972a79..0eeb7b2 100644 --- a/webkit/browser/fileapi/file_system_operation.h +++ b/webkit/browser/fileapi/file_system_operation.h @@ -1,485 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_H_ - -#include <vector> - -#include "base/callback.h" -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/process/process.h" -#include "webkit/browser/fileapi/file_system_operation_context.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/fileapi/directory_entry.h" - -namespace base { -class Time; -} - -namespace net { -class URLRequest; -} - -namespace storage { -class ShareableFileReference; -} - -class GURL; - -namespace storage { - -class FileSystemContext; -class FileSystemURL; -class FileWriterDelegate; - -// The interface class for FileSystemOperation implementations. -// -// This interface defines file system operations required to implement -// "File API: Directories and System" -// http://www.w3.org/TR/file-system-api/ -// -// DESIGN NOTES -// -// This class is designed to -// -// 1) Serve one-time file system operation per instance. Only one -// method(CreateFile, CreateDirectory, Copy, Move, DirectoryExists, -// GetMetadata, ReadDirectory and Remove) may be called during the -// lifetime of this object and it should be called no more than once. -// -// 2) Deliver the results of operations to the client via the callback function -// passed as the last parameter of the method. -// -// Note that it is valid to delete an operation while it is running. -// The callback will NOT be fired if the operation is deleted before -// it gets called. -class FileSystemOperation { - public: - STORAGE_EXPORT static FileSystemOperation* Create( - const FileSystemURL& url, - FileSystemContext* file_system_context, - scoped_ptr<FileSystemOperationContext> operation_context); - - virtual ~FileSystemOperation() {} - - // Used for CreateFile(), etc. |result| is the return code of the operation. - typedef base::Callback<void(base::File::Error result)> StatusCallback; - - // Used for GetMetadata(). |result| is the return code of the operation, - // |file_info| is the obtained file info. - typedef base::Callback< - void(base::File::Error result, - const base::File::Info& file_info)> GetMetadataCallback; - - // Used for OpenFile(). |on_close_callback| will be called after the file is - // closed in the child process. It can be null, if no operation is needed on - // closing a file. - typedef base::Callback< - void(base::File file, - const base::Closure& on_close_callback)> OpenFileCallback; - - // Used for ReadDirectoryCallback. - typedef std::vector<DirectoryEntry> FileEntryList; - - // Used for ReadDirectory(). |result| is the return code of the operation, - // |file_list| is the list of files read, and |has_more| is true if some files - // are yet to be read. - typedef base::Callback< - void(base::File::Error result, - const FileEntryList& file_list, - bool has_more)> ReadDirectoryCallback; - - // Used for CreateSnapshotFile(). (Please see the comment at - // CreateSnapshotFile() below for how the method is called) - // |result| is the return code of the operation. - // |file_info| is the metadata of the snapshot file created. - // |platform_path| is the path to the snapshot file created. - // - // The snapshot file could simply be of the local file pointed by the given - // filesystem URL in local filesystem cases; remote filesystems - // may want to download the file into a temporary snapshot file and then - // return the metadata of the temporary file. - // - // |file_ref| is used to manage the lifetime of the returned - // snapshot file. It can be set to let the chromium backend take - // care of the life time of the snapshot file. Otherwise (if the returned - // file does not require any handling) the implementation can just - // return NULL. In a more complex case, the implementaiton can manage - // the lifetime of the snapshot file on its own (e.g. by its cache system) - // but also can be notified via the reference when the file becomes no - // longer necessary in the javascript world. - // Please see the comment for ShareableFileReference for details. - // - typedef base::Callback< - void(base::File::Error result, - const base::File::Info& file_info, - const base::FilePath& platform_path, - const scoped_refptr<storage::ShareableFileReference>& file_ref)> - SnapshotFileCallback; - - // Used for progress update callback for Copy(). - // - // BEGIN_COPY_ENTRY is fired for each copy creation beginning (for both - // file and directory). - // The |source_url| is the URL of the source entry. |size| should not be - // used. - // - // END_COPY_ENTRY is fired for each copy creation finishing (for both - // file and directory). - // The |source_url| is the URL of the source entry. The |destination_url| is - // the URL of the destination entry. |size| should not be used. - // - // PROGRESS is fired periodically during file copying (not fired for - // directory copy). - // The |source_url| is the URL of the source file. |size| is the number - // of cumulative copied bytes for the currently copied file. - // Both at beginning and ending of file copying, PROGRESS event should be - // called. At beginning, |size| should be 0. At ending, |size| should be - // the size of the file. - // - // Here is an example callback sequence of recursive copy. Suppose - // there are a/b/c.txt (100 bytes) and a/b/d.txt (200 bytes), and trying to - // copy a to x recursively, then the progress update sequence will be: - // - // BEGIN_COPY_ENTRY a (starting create "a" directory in x/). - // END_COPY_ENTRY a x/a (creating "a" directory in x/ is finished). - // - // BEGIN_COPY_ENTRY a/b (starting create "b" directory in x/a). - // END_COPY_ENTRY a/b x/a/b (creating "b" directory in x/a/ is finished). - // - // BEGIN_COPY_ENTRY a/b/c.txt (starting to copy "c.txt" in x/a/b/). - // PROGRESS a/b/c.txt 0 (The first PROGRESS's |size| should be 0). - // PROGRESS a/b/c.txt 10 - // : - // PROGRESS a/b/c.txt 90 - // PROGRESS a/b/c.txt 100 (The last PROGRESS's |size| should be the size of - // the file). - // END_COPY_ENTRY a/b/c.txt x/a/b/c.txt (copying "c.txt" is finished). - // - // BEGIN_COPY_ENTRY a/b/d.txt (starting to copy "d.txt" in x/a/b). - // PROGRESS a/b/d.txt 0 (The first PROGRESS's |size| should be 0). - // PROGRESS a/b/d.txt 10 - // : - // PROGRESS a/b/d.txt 190 - // PROGRESS a/b/d.txt 200 (The last PROGRESS's |size| should be the size of - // the file). - // END_COPY_ENTRY a/b/d.txt x/a/b/d.txt (copy "d.txt" is finished). - // - // Note that event sequence of a/b/c.txt and a/b/d.txt can be interlaced, - // because they can be done in parallel. Also PROGRESS events are optional, - // so they may not be appeared. - // All the progress callback invocation should be done before StatusCallback - // given to the Copy is called. Especially if an error is found before first - // progres callback invocation, the progress callback may NOT invoked for the - // copy. - // - // Note for future extension. Currently this callback is only supported on - // Copy(). We can extend this to Move(), because Move() is sometimes - // implemented as "copy then delete." - // In more precise, Move() usually can be implemented either 1) by updating - // the metadata of resource (e.g. root of moving directory tree), or 2) by - // copying directory tree and them removing the source tree. - // For 1)'s case, we can simply add BEGIN_MOVE_ENTRY and END_MOVE_ENTRY - // for root directory. - // For 2)'s case, we can add BEGIN_DELETE_ENTRY and END_DELETE_ENTRY for each - // entry. - // For both cases, we probably won't need to use PROGRESS event because - // these operations should be done quickly (at least much faster than copying - // usually). - enum CopyProgressType { - BEGIN_COPY_ENTRY, - END_COPY_ENTRY, - PROGRESS, - }; - typedef base::Callback<void(CopyProgressType type, - const FileSystemURL& source_url, - const FileSystemURL& destination_url, - int64 size)> - CopyProgressCallback; - - // Used for CopyFileLocal() to report progress update. - // |size| is the cumulative copied bytes for the copy. - // At the beginning the progress callback should be called with |size| = 0, - // and also at the ending the progress callback should be called with |size| - // set to the copied file size. - typedef base::Callback<void(int64 size)> CopyFileProgressCallback; - - // The option for copy or move operation. - enum CopyOrMoveOption { - // No additional operation. - OPTION_NONE, - - // Preserves last modified time if possible. If the operation to update - // last modified time is not supported on the file system for the - // destination file, this option would be simply ignored (i.e. Copy would - // be successfully done without preserving last modified time). - OPTION_PRESERVE_LAST_MODIFIED, - }; - - // Used for Write(). - typedef base::Callback<void(base::File::Error result, - int64 bytes, - bool complete)> WriteCallback; - - // Creates a file at |path|. If |exclusive| is true, an error is raised - // in case a file is already present at the URL. - virtual void CreateFile(const FileSystemURL& path, - bool exclusive, - const StatusCallback& callback) = 0; - - // Creates a directory at |path|. If |exclusive| is true, an error is - // raised in case a directory is already present at the URL. If - // |recursive| is true, create parent directories as needed just like - // mkdir -p does. - virtual void CreateDirectory(const FileSystemURL& path, - bool exclusive, - bool recursive, - const StatusCallback& callback) = 0; - - // Copies a file or directory from |src_path| to |dest_path|. If - // |src_path| is a directory, the contents of |src_path| are copied to - // |dest_path| recursively. A new file or directory is created at - // |dest_path| as needed. - // |option| specifies the minor behavior of Copy(). See CopyOrMoveOption's - // comment for details. - // |progress_callback| is periodically called to report the progress - // update. See also the comment of CopyProgressCallback. This callback is - // optional. - // - // For recursive case this internally creates new FileSystemOperations and - // calls: - // - ReadDirectory, CopyFileLocal and CreateDirectory - // for same-filesystem case, or - // - ReadDirectory and CreateSnapshotFile on source filesystem and - // CopyInForeignFile and CreateDirectory on dest filesystem - // for cross-filesystem case. - // - virtual void Copy(const FileSystemURL& src_path, - const FileSystemURL& dest_path, - CopyOrMoveOption option, - const CopyProgressCallback& progress_callback, - const StatusCallback& callback) = 0; - - // Moves a file or directory from |src_path| to |dest_path|. A new file - // or directory is created at |dest_path| as needed. - // |option| specifies the minor behavior of Copy(). See CopyOrMoveOption's - // comment for details. - // - // For recursive case this internally creates new FileSystemOperations and - // calls: - // - ReadDirectory, MoveFileLocal, CreateDirectory and Remove - // for same-filesystem case, or - // - ReadDirectory, CreateSnapshotFile and Remove on source filesystem and - // CopyInForeignFile and CreateDirectory on dest filesystem - // for cross-filesystem case. - // - virtual void Move(const FileSystemURL& src_path, - const FileSystemURL& dest_path, - CopyOrMoveOption option, - const StatusCallback& callback) = 0; - - // Checks if a directory is present at |path|. - virtual void DirectoryExists(const FileSystemURL& path, - const StatusCallback& callback) = 0; - - // Checks if a file is present at |path|. - virtual void FileExists(const FileSystemURL& path, - const StatusCallback& callback) = 0; - - // Gets the metadata of a file or directory at |path|. - virtual void GetMetadata(const FileSystemURL& path, - const GetMetadataCallback& callback) = 0; - - // Reads contents of a directory at |path|. - virtual void ReadDirectory(const FileSystemURL& path, - const ReadDirectoryCallback& callback) = 0; - - // Removes a file or directory at |path|. If |recursive| is true, remove - // all files and directories under the directory at |path| recursively. - virtual void Remove(const FileSystemURL& path, bool recursive, - const StatusCallback& callback) = 0; - - // Writes the data read from |blob_request| using |writer_delegate|. - virtual void Write( - const FileSystemURL& url, - scoped_ptr<FileWriterDelegate> writer_delegate, - scoped_ptr<net::URLRequest> blob_request, - const WriteCallback& callback) = 0; - - // Truncates a file at |path| to |length|. If |length| is larger than - // the original file size, the file will be extended, and the extended - // part is filled with null bytes. - virtual void Truncate(const FileSystemURL& path, int64 length, - const StatusCallback& callback) = 0; - - // Tries to cancel the current operation [we support cancelling write or - // truncate only]. Reports failure for the current operation, then reports - // success for the cancel operation itself via the |cancel_dispatcher|. - // - // E.g. a typical cancel implementation would look like: - // - // virtual void SomeOperationImpl::Cancel( - // const StatusCallback& cancel_callback) { - // // Abort the current inflight operation first. - // ... - // - // // Dispatch ABORT error for the current operation by invoking - // // the callback function for the ongoing operation, - // operation_callback.Run(base::File::FILE_ERROR_ABORT, ...); - // - // // Dispatch 'success' for the cancel (or dispatch appropriate - // // error code with DidFail() if the cancel has somehow failed). - // cancel_callback.Run(base::File::FILE_OK); - // } - // - // Note that, for reporting failure, the callback function passed to a - // cancellable operations are kept around with the operation instance - // (as |operation_callback_| in the code example). - virtual void Cancel(const StatusCallback& cancel_callback) = 0; - - // Modifies timestamps of a file or directory at |path| with - // |last_access_time| and |last_modified_time|. The function DOES NOT - // create a file unlike 'touch' command on Linux. - // - // This function is used only by Pepper as of writing. - virtual void TouchFile(const FileSystemURL& path, - const base::Time& last_access_time, - const base::Time& last_modified_time, - const StatusCallback& callback) = 0; - - // Opens a file at |path| with |file_flags|, where flags are OR'ed - // values of base::File::Flags. - // - // This function is used only by Pepper as of writing. - virtual void OpenFile(const FileSystemURL& path, - int file_flags, - const OpenFileCallback& callback) = 0; - - // Creates a local snapshot file for a given |path| and returns the - // metadata and platform path of the snapshot file via |callback|. - // In local filesystem cases the implementation may simply return - // the metadata of the file itself (as well as GetMetadata does), - // while in remote filesystem case the backend may want to download the file - // into a temporary snapshot file and return the metadata of the - // temporary file. Or if the implementaiton already has the local cache - // data for |path| it can simply return the path to the cache. - virtual void CreateSnapshotFile(const FileSystemURL& path, - const SnapshotFileCallback& callback) = 0; - - // Copies in a single file from a different filesystem. - // - // This returns: - // - File::FILE_ERROR_NOT_FOUND if |src_file_path| - // or the parent directory of |dest_url| does not exist. - // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and - // is not a file. - // - File::FILE_ERROR_FAILED if |dest_url| does not exist and - // its parent path is a file. - // - virtual void CopyInForeignFile(const base::FilePath& src_local_disk_path, - const FileSystemURL& dest_url, - const StatusCallback& callback) = 0; - - // Removes a single file. - // - // This returns: - // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. - // - File::FILE_ERROR_NOT_A_FILE if |url| is not a file. - // - virtual void RemoveFile(const FileSystemURL& url, - const StatusCallback& callback) = 0; - - // Removes a single empty directory. - // - // This returns: - // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. - // - File::FILE_ERROR_NOT_A_DIRECTORY if |url| is not a directory. - // - File::FILE_ERROR_NOT_EMPTY if |url| is not empty. - // - virtual void RemoveDirectory(const FileSystemURL& url, - const StatusCallback& callback) = 0; - - // Copies a file from |src_url| to |dest_url|. - // This must be called for files that belong to the same filesystem - // (i.e. type() and origin() of the |src_url| and |dest_url| must match). - // |option| specifies the minor behavior of Copy(). See CopyOrMoveOption's - // comment for details. - // |progress_callback| is periodically called to report the progress - // update. See also the comment of CopyFileProgressCallback. This callback is - // optional. - // - // This returns: - // - File::FILE_ERROR_NOT_FOUND if |src_url| - // or the parent directory of |dest_url| does not exist. - // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. - // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and - // is not a file. - // - File::FILE_ERROR_FAILED if |dest_url| does not exist and - // its parent path is a file. - // - virtual void CopyFileLocal(const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - const CopyFileProgressCallback& progress_callback, - const StatusCallback& callback) = 0; - - // Moves a local file from |src_url| to |dest_url|. - // This must be called for files that belong to the same filesystem - // (i.e. type() and origin() of the |src_url| and |dest_url| must match). - // |option| specifies the minor behavior of Copy(). See CopyOrMoveOption's - // comment for details. - // - // This returns: - // - File::FILE_ERROR_NOT_FOUND if |src_url| - // or the parent directory of |dest_url| does not exist. - // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. - // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and - // is not a file. - // - File::FILE_ERROR_FAILED if |dest_url| does not exist and - // its parent path is a file. - // - virtual void MoveFileLocal(const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - const StatusCallback& callback) = 0; - - // Synchronously gets the platform path for the given |url|. - // This may fail if the given |url|'s filesystem type is neither - // temporary nor persistent. - // In such a case, base::File::FILE_ERROR_INVALID_OPERATION will be - // returned. - virtual base::File::Error SyncGetPlatformPath( - const FileSystemURL& url, - base::FilePath* platform_path) = 0; - - protected: - // Used only for internal assertions. - enum OperationType { - kOperationNone, - kOperationCreateFile, - kOperationCreateDirectory, - kOperationCreateSnapshotFile, - kOperationCopy, - kOperationCopyInForeignFile, - kOperationMove, - kOperationDirectoryExists, - kOperationFileExists, - kOperationGetMetadata, - kOperationReadDirectory, - kOperationRemove, - kOperationWrite, - kOperationTruncate, - kOperationTouchFile, - kOperationOpenFile, - kOperationCloseFile, - kOperationGetLocalPath, - kOperationCancel, - }; -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_H_ +#include "storage/browser/fileapi/file_system_operation.h" diff --git a/webkit/browser/fileapi/file_system_operation_context.h b/webkit/browser/fileapi/file_system_operation_context.h index fe0a313..093389e 100644 --- a/webkit/browser/fileapi/file_system_operation_context.h +++ b/webkit/browser/fileapi/file_system_operation_context.h @@ -1,97 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_CONTEXT_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_CONTEXT_H_ - -#include "base/files/file_path.h" -#include "base/supports_user_data.h" -#include "base/threading/thread_checker.h" -#include "webkit/browser/fileapi/task_runner_bound_observer_list.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/quota/quota_types.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace storage { - -class FileSystemContext; - -// A context class which is carried around by FileSystemOperation and -// its delegated tasks. It is valid to reuse one context instance across -// multiple operations as far as those operations are supposed to share -// the same context (e.g. use the same task runner, share the quota etc). -// Note that the remaining quota bytes (allowed_bytes_growth) may be -// updated during the execution of write operations. -class STORAGE_EXPORT_PRIVATE FileSystemOperationContext - : public base::SupportsUserData { - public: - explicit FileSystemOperationContext(FileSystemContext* context); - - // Specifies |task_runner| which the operation is performed on. - // The backend of |task_runner| must outlive the IO thread. - FileSystemOperationContext(FileSystemContext* context, - base::SequencedTaskRunner* task_runner); - - virtual ~FileSystemOperationContext(); - - FileSystemContext* file_system_context() const { - return file_system_context_.get(); - } - - // Updates the current remaining quota. - // This can be called to update the remaining quota during the operation. - void set_allowed_bytes_growth(const int64& allowed_bytes_growth) { - allowed_bytes_growth_ = allowed_bytes_growth; - } - - // Returns the current remaining quota. - int64 allowed_bytes_growth() const { return allowed_bytes_growth_; } - storage::QuotaLimitType quota_limit_type() const { return quota_limit_type_; } - base::SequencedTaskRunner* task_runner() const { return task_runner_.get(); } - - ChangeObserverList* change_observers() { return &change_observers_; } - UpdateObserverList* update_observers() { return &update_observers_; } - - // Following setters should be called only on the same thread as the - // FileSystemOperationContext is created (i.e. are not supposed be updated - // after the context's passed onto other task runners). - void set_change_observers(const ChangeObserverList& list) { - DCHECK(setter_thread_checker_.CalledOnValidThread()); - change_observers_ = list; - } - void set_update_observers(const UpdateObserverList& list) { - DCHECK(setter_thread_checker_.CalledOnValidThread()); - update_observers_ = list; - } - void set_quota_limit_type(storage::QuotaLimitType limit_type) { - DCHECK(setter_thread_checker_.CalledOnValidThread()); - quota_limit_type_ = limit_type; - } - - private: - scoped_refptr<FileSystemContext> file_system_context_; - scoped_refptr<base::SequencedTaskRunner> task_runner_; - - // The current remaining quota, used by ObfuscatedFileUtil. - int64 allowed_bytes_growth_; - - // The current quota limit type, used by ObfuscatedFileUtil. - storage::QuotaLimitType quota_limit_type_; - - // Observers attached to this context. - ChangeObserverList change_observers_; - UpdateObserverList update_observers_; - - // Used to check its setters are not called on arbitrary thread. - base::ThreadChecker setter_thread_checker_; - - DISALLOW_COPY_AND_ASSIGN(FileSystemOperationContext); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_CONTEXT_H_ +#include "storage/browser/fileapi/file_system_operation_context.h" diff --git a/webkit/browser/fileapi/file_system_operation_impl.h b/webkit/browser/fileapi/file_system_operation_impl.h index ae6abb0..ceae604 100644 --- a/webkit/browser/fileapi/file_system_operation_impl.h +++ b/webkit/browser/fileapi/file_system_operation_impl.h @@ -1,206 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_IMPL_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_IMPL_H_ - -#include <vector> - -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "webkit/browser/fileapi/file_system_operation.h" -#include "webkit/browser/fileapi/file_system_operation_context.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/fileapi/file_writer_delegate.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/blob/scoped_file.h" -#include "webkit/common/quota/quota_types.h" - -namespace storage { - -class AsyncFileUtil; -class FileSystemContext; -class RecursiveOperationDelegate; - -// The default implementation of FileSystemOperation for file systems. -class STORAGE_EXPORT FileSystemOperationImpl - : public NON_EXPORTED_BASE(FileSystemOperation) { - public: - virtual ~FileSystemOperationImpl(); - - // FileSystemOperation overrides. - virtual void CreateFile(const FileSystemURL& url, - bool exclusive, - const StatusCallback& callback) OVERRIDE; - virtual void CreateDirectory(const FileSystemURL& url, - bool exclusive, - bool recursive, - const StatusCallback& callback) OVERRIDE; - virtual void Copy(const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - const CopyProgressCallback& progress_callback, - const StatusCallback& callback) OVERRIDE; - virtual void Move(const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - const StatusCallback& callback) OVERRIDE; - virtual void DirectoryExists(const FileSystemURL& url, - const StatusCallback& callback) OVERRIDE; - virtual void FileExists(const FileSystemURL& url, - const StatusCallback& callback) OVERRIDE; - virtual void GetMetadata(const FileSystemURL& url, - const GetMetadataCallback& callback) OVERRIDE; - virtual void ReadDirectory(const FileSystemURL& url, - const ReadDirectoryCallback& callback) OVERRIDE; - virtual void Remove(const FileSystemURL& url, bool recursive, - const StatusCallback& callback) OVERRIDE; - virtual void Write(const FileSystemURL& url, - scoped_ptr<FileWriterDelegate> writer_delegate, - scoped_ptr<net::URLRequest> blob_request, - const WriteCallback& callback) OVERRIDE; - virtual void Truncate(const FileSystemURL& url, int64 length, - const StatusCallback& callback) OVERRIDE; - virtual void TouchFile(const FileSystemURL& url, - const base::Time& last_access_time, - const base::Time& last_modified_time, - const StatusCallback& callback) OVERRIDE; - virtual void OpenFile(const FileSystemURL& url, - int file_flags, - const OpenFileCallback& callback) OVERRIDE; - virtual void Cancel(const StatusCallback& cancel_callback) OVERRIDE; - virtual void CreateSnapshotFile( - const FileSystemURL& path, - const SnapshotFileCallback& callback) OVERRIDE; - virtual void CopyInForeignFile(const base::FilePath& src_local_disk_path, - const FileSystemURL& dest_url, - const StatusCallback& callback) OVERRIDE; - virtual void RemoveFile(const FileSystemURL& url, - const StatusCallback& callback) OVERRIDE; - virtual void RemoveDirectory(const FileSystemURL& url, - const StatusCallback& callback) OVERRIDE; - virtual void CopyFileLocal(const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - const CopyFileProgressCallback& progress_callback, - const StatusCallback& callback) OVERRIDE; - virtual void MoveFileLocal(const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - const StatusCallback& callback) OVERRIDE; - virtual base::File::Error SyncGetPlatformPath( - const FileSystemURL& url, - base::FilePath* platform_path) OVERRIDE; - - FileSystemContext* file_system_context() const { - return file_system_context_.get(); - } - - private: - friend class FileSystemOperation; - - FileSystemOperationImpl( - const FileSystemURL& url, - FileSystemContext* file_system_context, - scoped_ptr<FileSystemOperationContext> operation_context); - - // Queries the quota and usage and then runs the given |task|. - // If an error occurs during the quota query it runs |error_callback| instead. - void GetUsageAndQuotaThenRunTask( - const FileSystemURL& url, - const base::Closure& task, - const base::Closure& error_callback); - - // Called after the quota info is obtained from the quota manager - // (which is triggered by GetUsageAndQuotaThenRunTask). - // Sets the quota info in the operation_context_ and then runs the given - // |task| if the returned quota status is successful, otherwise runs - // |error_callback|. - void DidGetUsageAndQuotaAndRunTask(const base::Closure& task, - const base::Closure& error_callback, - storage::QuotaStatusCode status, - int64 usage, - int64 quota); - - // The 'body' methods that perform the actual work (i.e. posting the - // file task on proxy_) after the quota check. - void DoCreateFile(const FileSystemURL& url, - const StatusCallback& callback, bool exclusive); - void DoCreateDirectory(const FileSystemURL& url, - const StatusCallback& callback, - bool exclusive, - bool recursive); - void DoCopyFileLocal(const FileSystemURL& src, - const FileSystemURL& dest, - CopyOrMoveOption option, - const CopyFileProgressCallback& progress_callback, - const StatusCallback& callback); - void DoMoveFileLocal(const FileSystemURL& src, - const FileSystemURL& dest, - CopyOrMoveOption option, - const StatusCallback& callback); - void DoCopyInForeignFile(const base::FilePath& src_local_disk_file_path, - const FileSystemURL& dest, - const StatusCallback& callback); - void DoTruncate(const FileSystemURL& url, - const StatusCallback& callback, int64 length); - void DoOpenFile(const FileSystemURL& url, - const OpenFileCallback& callback, int file_flags); - - // Callback for CreateFile for |exclusive|=true cases. - void DidEnsureFileExistsExclusive(const StatusCallback& callback, - base::File::Error rv, - bool created); - - // Callback for CreateFile for |exclusive|=false cases. - void DidEnsureFileExistsNonExclusive(const StatusCallback& callback, - base::File::Error rv, - bool created); - - void DidFinishOperation(const StatusCallback& callback, - base::File::Error rv); - void DidDirectoryExists(const StatusCallback& callback, - base::File::Error rv, - const base::File::Info& file_info); - void DidFileExists(const StatusCallback& callback, - base::File::Error rv, - const base::File::Info& file_info); - void DidDeleteRecursively(const FileSystemURL& url, - const StatusCallback& callback, - base::File::Error rv); - void DidWrite(const FileSystemURL& url, - const WriteCallback& callback, - base::File::Error rv, - int64 bytes, - FileWriterDelegate::WriteProgressStatus write_status); - void DidOpenFile(const OpenFileCallback& callback, - base::File file, - const base::Closure& on_close_callback); - - // Used only for internal assertions. - // Returns false if there's another inflight pending operation. - bool SetPendingOperationType(OperationType type); - - scoped_refptr<FileSystemContext> file_system_context_; - - scoped_ptr<FileSystemOperationContext> operation_context_; - AsyncFileUtil* async_file_util_; // Not owned. - - scoped_ptr<FileWriterDelegate> file_writer_delegate_; - scoped_ptr<RecursiveOperationDelegate> recursive_operation_delegate_; - - StatusCallback cancel_callback_; - - // A flag to make sure we call operation only once per instance. - OperationType pending_operation_; - - base::WeakPtrFactory<FileSystemOperationImpl> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(FileSystemOperationImpl); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_IMPL_H_ +#include "storage/browser/fileapi/file_system_operation_impl.h" diff --git a/webkit/browser/fileapi/file_system_operation_runner.h b/webkit/browser/fileapi/file_system_operation_runner.h index cd30d7b..783f9a3 100644 --- a/webkit/browser/fileapi/file_system_operation_runner.h +++ b/webkit/browser/fileapi/file_system_operation_runner.h @@ -1,322 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_RUNNER_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_RUNNER_H_ - -#include <map> -#include <set> -#include <vector> - -#include "base/basictypes.h" -#include "base/id_map.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "webkit/browser/blob/blob_data_handle.h" -#include "webkit/browser/fileapi/file_system_operation.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/storage_browser_export.h" - -namespace net { -class URLRequestContext; -} - -namespace storage { - -class FileSystemURL; -class FileSystemContext; - -// A central interface for running FileSystem API operations. -// All operation methods take callback and returns OperationID, which is -// an integer value which can be used for cancelling an operation. -// All operation methods return kErrorOperationID if running (posting) an -// operation fails, in addition to dispatching the callback with an error -// code (therefore in most cases the caller does not need to check the -// returned operation ID). -class STORAGE_EXPORT FileSystemOperationRunner - : public base::SupportsWeakPtr<FileSystemOperationRunner> { - public: - typedef FileSystemOperation::GetMetadataCallback GetMetadataCallback; - typedef FileSystemOperation::ReadDirectoryCallback ReadDirectoryCallback; - typedef FileSystemOperation::SnapshotFileCallback SnapshotFileCallback; - typedef FileSystemOperation::StatusCallback StatusCallback; - typedef FileSystemOperation::WriteCallback WriteCallback; - typedef FileSystemOperation::OpenFileCallback OpenFileCallback; - typedef FileSystemOperation::CopyProgressCallback CopyProgressCallback; - typedef FileSystemOperation::CopyFileProgressCallback - CopyFileProgressCallback; - typedef FileSystemOperation::CopyOrMoveOption CopyOrMoveOption; - - typedef int OperationID; - - virtual ~FileSystemOperationRunner(); - - // Cancels all inflight operations. - void Shutdown(); - - // Creates a file at |url|. If |exclusive| is true, an error is raised - // in case a file is already present at the URL. - OperationID CreateFile(const FileSystemURL& url, - bool exclusive, - const StatusCallback& callback); - - OperationID CreateDirectory(const FileSystemURL& url, - bool exclusive, - bool recursive, - const StatusCallback& callback); - - // Copies a file or directory from |src_url| to |dest_url|. If - // |src_url| is a directory, the contents of |src_url| are copied to - // |dest_url| recursively. A new file or directory is created at - // |dest_url| as needed. - // For |option| and |progress_callback|, see file_system_operation.h for - // details. - OperationID Copy(const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - const CopyProgressCallback& progress_callback, - const StatusCallback& callback); - - // Moves a file or directory from |src_url| to |dest_url|. A new file - // or directory is created at |dest_url| as needed. - // For |option|, see file_system_operation.h for details. - OperationID Move(const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - const StatusCallback& callback); - - // Checks if a directory is present at |url|. - OperationID DirectoryExists(const FileSystemURL& url, - const StatusCallback& callback); - - // Checks if a file is present at |url|. - OperationID FileExists(const FileSystemURL& url, - const StatusCallback& callback); - - // Gets the metadata of a file or directory at |url|. - OperationID GetMetadata(const FileSystemURL& url, - const GetMetadataCallback& callback); - - // Reads contents of a directory at |url|. - OperationID ReadDirectory(const FileSystemURL& url, - const ReadDirectoryCallback& callback); - - // Removes a file or directory at |url|. If |recursive| is true, remove - // all files and directories under the directory at |url| recursively. - OperationID Remove(const FileSystemURL& url, bool recursive, - const StatusCallback& callback); - - // Writes contents of |blob_url| to |url| at |offset|. - // |url_request_context| is used to read contents in |blob|. - OperationID Write(const net::URLRequestContext* url_request_context, - const FileSystemURL& url, - scoped_ptr<storage::BlobDataHandle> blob, - int64 offset, - const WriteCallback& callback); - - // Truncates a file at |url| to |length|. If |length| is larger than - // the original file size, the file will be extended, and the extended - // part is filled with null bytes. - OperationID Truncate(const FileSystemURL& url, int64 length, - const StatusCallback& callback); - - // Tries to cancel the operation |id| [we support cancelling write or - // truncate only]. Reports failure for the current operation, then reports - // success for the cancel operation itself via the |callback|. - void Cancel(OperationID id, const StatusCallback& callback); - - // Modifies timestamps of a file or directory at |url| with - // |last_access_time| and |last_modified_time|. The function DOES NOT - // create a file unlike 'touch' command on Linux. - // - // This function is used only by Pepper as of writing. - OperationID TouchFile(const FileSystemURL& url, - const base::Time& last_access_time, - const base::Time& last_modified_time, - const StatusCallback& callback); - - // Opens a file at |url| with |file_flags|, where flags are OR'ed - // values of base::PlatformFileFlags. - // - // |peer_handle| is the process handle of a pepper plugin process, which - // is necessary for underlying IPC calls with Pepper plugins. - // - // This function is used only by Pepper as of writing. - OperationID OpenFile(const FileSystemURL& url, - int file_flags, - const OpenFileCallback& callback); - - // Creates a local snapshot file for a given |url| and returns the - // metadata and platform url of the snapshot file via |callback|. - // In local filesystem cases the implementation may simply return - // the metadata of the file itself (as well as GetMetadata does), - // while in remote filesystem case the backend may want to download the file - // into a temporary snapshot file and return the metadata of the - // temporary file. Or if the implementaiton already has the local cache - // data for |url| it can simply return the url to the cache. - OperationID CreateSnapshotFile(const FileSystemURL& url, - const SnapshotFileCallback& callback); - - // Copies in a single file from a different filesystem. - // - // This returns: - // - File::FILE_ERROR_NOT_FOUND if |src_file_path| - // or the parent directory of |dest_url| does not exist. - // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and - // is not a file. - // - File::FILE_ERROR_FAILED if |dest_url| does not exist and - // its parent path is a file. - // - OperationID CopyInForeignFile(const base::FilePath& src_local_disk_path, - const FileSystemURL& dest_url, - const StatusCallback& callback); - - // Removes a single file. - // - // This returns: - // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. - // - File::FILE_ERROR_NOT_A_FILE if |url| is not a file. - // - OperationID RemoveFile(const FileSystemURL& url, - const StatusCallback& callback); - - // Removes a single empty directory. - // - // This returns: - // - File::FILE_ERROR_NOT_FOUND if |url| does not exist. - // - File::FILE_ERROR_NOT_A_DIRECTORY if |url| is not a directory. - // - File::FILE_ERROR_NOT_EMPTY if |url| is not empty. - // - OperationID RemoveDirectory(const FileSystemURL& url, - const StatusCallback& callback); - - // Copies a file from |src_url| to |dest_url|. - // This must be called for files that belong to the same filesystem - // (i.e. type() and origin() of the |src_url| and |dest_url| must match). - // For |option| and |progress_callback|, see file_system_operation.h for - // details. - // - // This returns: - // - File::FILE_ERROR_NOT_FOUND if |src_url| - // or the parent directory of |dest_url| does not exist. - // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. - // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and - // is not a file. - // - File::FILE_ERROR_FAILED if |dest_url| does not exist and - // its parent path is a file. - // - OperationID CopyFileLocal(const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - const CopyFileProgressCallback& progress_callback, - const StatusCallback& callback); - - // Moves a local file from |src_url| to |dest_url|. - // This must be called for files that belong to the same filesystem - // (i.e. type() and origin() of the |src_url| and |dest_url| must match). - // For |option|, see file_system_operation.h for details. - // - // This returns: - // - File::FILE_ERROR_NOT_FOUND if |src_url| - // or the parent directory of |dest_url| does not exist. - // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. - // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and - // is not a file. - // - File::FILE_ERROR_FAILED if |dest_url| does not exist and - // its parent path is a file. - // - OperationID MoveFileLocal(const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - const StatusCallback& callback); - - // This is called only by pepper plugin as of writing to synchronously get - // the underlying platform path to upload a file in the sandboxed filesystem - // (e.g. TEMPORARY or PERSISTENT). - base::File::Error SyncGetPlatformPath(const FileSystemURL& url, - base::FilePath* platform_path); - - private: - class BeginOperationScoper; - - struct OperationHandle { - OperationID id; - base::WeakPtr<BeginOperationScoper> scope; - - OperationHandle(); - ~OperationHandle(); - }; - - friend class FileSystemContext; - explicit FileSystemOperationRunner(FileSystemContext* file_system_context); - - void DidFinish(const OperationHandle& handle, - const StatusCallback& callback, - base::File::Error rv); - void DidGetMetadata(const OperationHandle& handle, - const GetMetadataCallback& callback, - base::File::Error rv, - const base::File::Info& file_info); - void DidReadDirectory(const OperationHandle& handle, - const ReadDirectoryCallback& callback, - base::File::Error rv, - const std::vector<DirectoryEntry>& entries, - bool has_more); - void DidWrite(const OperationHandle& handle, - const WriteCallback& callback, - base::File::Error rv, - int64 bytes, - bool complete); - void DidOpenFile( - const OperationHandle& handle, - const OpenFileCallback& callback, - base::File file, - const base::Closure& on_close_callback); - void DidCreateSnapshot( - const OperationHandle& handle, - const SnapshotFileCallback& callback, - base::File::Error rv, - const base::File::Info& file_info, - const base::FilePath& platform_path, - const scoped_refptr<storage::ShareableFileReference>& file_ref); - - void OnCopyProgress( - const OperationHandle& handle, - const CopyProgressCallback& callback, - FileSystemOperation::CopyProgressType type, - const FileSystemURL& source_url, - const FileSystemURL& dest_url, - int64 size); - - void PrepareForWrite(OperationID id, const FileSystemURL& url); - void PrepareForRead(OperationID id, const FileSystemURL& url); - - // These must be called at the beginning and end of any async operations. - OperationHandle BeginOperation(FileSystemOperation* operation, - base::WeakPtr<BeginOperationScoper> scope); - void FinishOperation(OperationID id); - - // Not owned; file_system_context owns this. - FileSystemContext* file_system_context_; - - // IDMap<FileSystemOperation, IDMapOwnPointer> operations_; - IDMap<FileSystemOperation, IDMapOwnPointer> operations_; - - // We keep track of the file to be modified by each operation so that - // we can notify observers when we're done. - typedef std::map<OperationID, FileSystemURLSet> OperationToURLSet; - OperationToURLSet write_target_urls_; - - // Operations that are finished but not yet fire their callbacks. - std::set<OperationID> finished_operations_; - - // Callbacks for stray cancels whose target operation is already finished. - std::map<OperationID, StatusCallback> stray_cancel_callbacks_; - - DISALLOW_COPY_AND_ASSIGN(FileSystemOperationRunner); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_RUNNER_H_ +#include "storage/browser/fileapi/file_system_operation_runner.h" diff --git a/webkit/browser/fileapi/file_system_options.h b/webkit/browser/fileapi/file_system_options.h index 23048d9..c05e8d1 100644 --- a/webkit/browser/fileapi/file_system_options.h +++ b/webkit/browser/fileapi/file_system_options.h @@ -1,62 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPTIONS_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPTIONS_H_ - -#include <string> -#include <vector> - -#include "webkit/browser/storage_browser_export.h" - -namespace leveldb { -class Env; -} - -namespace storage { - -// Provides runtime options that may change FileSystem API behavior. -// This object is copyable. -class STORAGE_EXPORT FileSystemOptions { - public: - enum ProfileMode { - PROFILE_MODE_NORMAL = 0, - PROFILE_MODE_INCOGNITO - }; - - // |profile_mode| specifies if the profile (for this filesystem) - // is running in incognito mode (PROFILE_MODE_INCOGNITO) or no - // (PROFILE_MODE_NORMAL). - // |additional_allowed_schemes| specifies schemes that are allowed - // to access FileSystem API in addition to "http" and "https". - // Non-NULL |env_override| overrides internal LevelDB environment. - FileSystemOptions( - ProfileMode profile_mode, - const std::vector<std::string>& additional_allowed_schemes, - leveldb::Env* env_override); - - ~FileSystemOptions(); - - // Returns true if it is running in the incognito mode. - bool is_incognito() const { return profile_mode_ == PROFILE_MODE_INCOGNITO; } - - // Returns the schemes that must be allowed to access FileSystem API - // in addition to standard "http" and "https". - // (e.g. If the --allow-file-access-from-files option is given in chrome - // "file" scheme will also need to be allowed). - const std::vector<std::string>& additional_allowed_schemes() const { - return additional_allowed_schemes_; - } - - leveldb::Env* env_override() const { return env_override_; } - - private: - const ProfileMode profile_mode_; - const std::vector<std::string> additional_allowed_schemes_; - leveldb::Env* env_override_; -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_OPTIONS_H_ +#include "storage/browser/fileapi/file_system_options.h" diff --git a/webkit/browser/fileapi/file_system_quota_client.h b/webkit/browser/fileapi/file_system_quota_client.h index 7709b6d..578a2dc 100644 --- a/webkit/browser/fileapi/file_system_quota_client.h +++ b/webkit/browser/fileapi/file_system_quota_client.h @@ -1,70 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_QUOTA_CLIENT_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_QUOTA_CLIENT_H_ - -#include <set> -#include <string> -#include <utility> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/files/file_path.h" -#include "base/memory/ref_counted.h" -#include "webkit/browser/fileapi/file_system_quota_util.h" -#include "webkit/browser/quota/quota_client.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/fileapi/file_system_types.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace storage { - -class FileSystemContext; - -// An instance of this class is created per-profile. This class -// is self-destructed and will delete itself when OnQuotaManagerDestroyed -// is called. -// All of the public methods of this class are called by the quota manager -// (except for the constructor/destructor). -class STORAGE_EXPORT_PRIVATE FileSystemQuotaClient - : public NON_EXPORTED_BASE(storage::QuotaClient) { - public: - FileSystemQuotaClient( - FileSystemContext* file_system_context, - bool is_incognito); - virtual ~FileSystemQuotaClient(); - - // QuotaClient methods. - virtual storage::QuotaClient::ID id() const OVERRIDE; - virtual void OnQuotaManagerDestroyed() OVERRIDE; - virtual void GetOriginUsage(const GURL& origin_url, - storage::StorageType type, - const GetUsageCallback& callback) OVERRIDE; - virtual void GetOriginsForType(storage::StorageType type, - const GetOriginsCallback& callback) OVERRIDE; - virtual void GetOriginsForHost(storage::StorageType type, - const std::string& host, - const GetOriginsCallback& callback) OVERRIDE; - virtual void DeleteOriginData(const GURL& origin, - storage::StorageType type, - const DeletionCallback& callback) OVERRIDE; - virtual bool DoesSupport(storage::StorageType type) const OVERRIDE; - - private: - base::SequencedTaskRunner* file_task_runner() const; - - scoped_refptr<FileSystemContext> file_system_context_; - - bool is_incognito_; - - DISALLOW_COPY_AND_ASSIGN(FileSystemQuotaClient); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_QUOTA_CLIENT_H_ +#include "storage/browser/fileapi/file_system_quota_client.h" diff --git a/webkit/browser/fileapi/file_system_quota_util.h b/webkit/browser/fileapi/file_system_quota_util.h index 045c36d..f42e6d8 100644 --- a/webkit/browser/fileapi/file_system_quota_util.h +++ b/webkit/browser/fileapi/file_system_quota_util.h @@ -1,91 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_QUOTA_UTIL_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_QUOTA_UTIL_H_ - -#include <set> -#include <string> - -#include "base/basictypes.h" -#include "base/files/file.h" -#include "url/gurl.h" -#include "webkit/browser/fileapi/task_runner_bound_observer_list.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/fileapi/file_system_types.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace storage { -class QuotaManagerProxy; -} - -namespace storage { - -class FileSystemContext; -class QuotaReservation; - -// An abstract interface that provides common quota-related utility functions -// for file_system_quota_client. -// All the methods of this class are synchronous and need to be called on -// the thread that the method name implies. -class STORAGE_EXPORT FileSystemQuotaUtil { - public: - virtual ~FileSystemQuotaUtil() {} - - // Deletes the data on the origin and reports the amount of deleted data - // to the quota manager via |proxy|. - virtual base::File::Error DeleteOriginDataOnFileTaskRunner( - FileSystemContext* context, - storage::QuotaManagerProxy* proxy, - const GURL& origin_url, - FileSystemType type) = 0; - - virtual void GetOriginsForTypeOnFileTaskRunner(storage::FileSystemType type, - std::set<GURL>* origins) = 0; - - virtual void GetOriginsForHostOnFileTaskRunner(storage::FileSystemType type, - const std::string& host, - std::set<GURL>* origins) = 0; - - // Returns the amount of data used for the origin for usage tracking. - virtual int64 GetOriginUsageOnFileTaskRunner( - storage::FileSystemContext* file_system_context, - const GURL& origin_url, - storage::FileSystemType type) = 0; - - // Creates new reservation object for the origin and the type. - virtual scoped_refptr<QuotaReservation> - CreateQuotaReservationOnFileTaskRunner( - const GURL& origin_url, - FileSystemType type) = 0; - - virtual void AddFileUpdateObserver( - FileSystemType type, - FileUpdateObserver* observer, - base::SequencedTaskRunner* task_runner) = 0; - virtual void AddFileChangeObserver( - FileSystemType type, - FileChangeObserver* observer, - base::SequencedTaskRunner* task_runner) = 0; - virtual void AddFileAccessObserver( - FileSystemType type, - FileAccessObserver* observer, - base::SequencedTaskRunner* task_runner) = 0; - - // Returns the observer list for |type|, or returns NULL if any observers - // have not been registered on |type|. - virtual const UpdateObserverList* GetUpdateObservers( - FileSystemType type) const = 0; - virtual const ChangeObserverList* GetChangeObservers( - FileSystemType type) const = 0; - virtual const AccessObserverList* GetAccessObservers( - FileSystemType type) const = 0; -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_QUOTA_UTIL_H_ +#include "storage/browser/fileapi/file_system_quota_util.h" diff --git a/webkit/browser/fileapi/file_system_url.h b/webkit/browser/fileapi/file_system_url.h index fe65c1b..5a6316e 100644 --- a/webkit/browser/fileapi/file_system_url.h +++ b/webkit/browser/fileapi/file_system_url.h @@ -1,180 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_URL_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_URL_H_ - -#include <set> -#include <string> - -#include "base/files/file_path.h" -#include "url/gurl.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/fileapi/file_system_mount_option.h" -#include "webkit/common/fileapi/file_system_types.h" - -namespace storage { - -// A class representing a filesystem URL which consists of origin URL, -// type and an internal path used inside the filesystem. -// -// When a FileSystemURL instance is created for a GURL (for filesystem: scheme), -// each accessor method would return following values: -// -// Example: For a URL 'filesystem:http://foo.com/temporary/foo/bar': -// origin() returns 'http://foo.com', -// mount_type() returns kFileSystemTypeTemporary, -// virtual_path() returns 'foo/bar', -// type() returns the same value as mount_type(), -// path() returns the same value as virtual_path(), -// -// All other accessors return empty or invalid value. -// -// FileSystemURL can also be created to represent a 'cracked' filesystem URL if -// the original URL's type/path is pointing to a mount point which can be -// further resolved to a lower filesystem type/path. -// -// Example: Assume a path '/media/removable' is mounted at mount name -// 'mount_name' with type kFileSystemTypeFoo as an external file system. -// -// The original URL would look like: -// 'filesystem:http://bar.com/external/mount_name/foo/bar': -// -// FileSystemURL('http://bar.com', -// kFileSystemTypeExternal, -// 'mount_name/foo/bar' -// 'mount_name', -// kFileSystemTypeFoo, -// '/media/removable/foo/bar'); -// would create a FileSystemURL whose accessors return: -// -// origin() returns 'http://bar.com', -// mount_type() returns kFileSystemTypeExternal, -// virtual_path() returns 'mount_name/foo/bar', -// type() returns the kFileSystemTypeFoo, -// path() returns '/media/removable/foo/bar', -// -// Note that in either case virtual_path() always returns the path part after -// 'type' part in the original URL, and mount_type() always returns the 'type' -// part in the original URL. -// -// Additionally, following accessors would return valid values: -// filesystem_id() returns 'mount_name'. -// -// It is impossible to directly create a valid FileSystemURL instance (except by -// using CreatedForTest methods, which should not be used in production code). -// To get a valid FileSystemURL, one of the following methods can be used: -// <Friend>::CrackURL, <Friend>::CreateCrackedFileSystemURL, where <Friend> is -// one of the friended classes. -// -// TODO(ericu): Look into making virtual_path() [and all FileSystem API virtual -// paths] just an std::string, to prevent platform-specific base::FilePath -// behavior from getting invoked by accident. Currently the base::FilePath -// returned here needs special treatment, as it may contain paths that are -// illegal on the current platform. -// To avoid problems, use VirtualPath::BaseName and -// VirtualPath::GetComponents instead of the base::FilePath methods. -class STORAGE_EXPORT FileSystemURL { - public: - FileSystemURL(); - ~FileSystemURL(); - - // Methods for creating FileSystemURL without attempting to crack them. - // Should be used only in tests. - static FileSystemURL CreateForTest(const GURL& url); - static FileSystemURL CreateForTest(const GURL& origin, - FileSystemType mount_type, - const base::FilePath& virtual_path); - - // Returns true if this instance represents a valid FileSystem URL. - bool is_valid() const { return is_valid_; } - - // Returns the origin part of this URL. See the class comment for details. - const GURL& origin() const { return origin_; } - - // Returns the type part of this URL. See the class comment for details. - FileSystemType type() const { return type_; } - - // Returns the cracked path of this URL. See the class comment for details. - const base::FilePath& path() const { return path_; } - - // Returns the original path part of this URL. - // See the class comment for details. - // TODO(kinuko): this must return std::string. - const base::FilePath& virtual_path() const { return virtual_path_; } - - // Returns the filesystem ID/mount name for isolated/external filesystem URLs. - // See the class comment for details. - const std::string& filesystem_id() const { return filesystem_id_; } - const std::string& mount_filesystem_id() const { - return mount_filesystem_id_; - } - - FileSystemType mount_type() const { return mount_type_; } - - const FileSystemMountOption& mount_option() const { return mount_option_; } - - // Returns the formatted URL of this instance. - GURL ToGURL() const; - - std::string DebugString() const; - - // Returns true if this URL is a strict parent of the |child|. - bool IsParent(const FileSystemURL& child) const; - - bool IsInSameFileSystem(const FileSystemURL& other) const; - - bool operator==(const FileSystemURL& that) const; - - bool operator!=(const FileSystemURL& that) const { - return !(*this == that); - } - - struct STORAGE_EXPORT Comparator { - bool operator() (const FileSystemURL& lhs, const FileSystemURL& rhs) const; - }; - - private: - friend class FileSystemContext; - friend class ExternalMountPoints; - friend class IsolatedContext; - - explicit FileSystemURL(const GURL& filesystem_url); - FileSystemURL(const GURL& origin, - FileSystemType mount_type, - const base::FilePath& virtual_path); - // Creates a cracked FileSystemURL. - FileSystemURL(const GURL& origin, - FileSystemType mount_type, - const base::FilePath& virtual_path, - const std::string& mount_filesystem_id, - FileSystemType cracked_type, - const base::FilePath& cracked_path, - const std::string& filesystem_id, - const FileSystemMountOption& mount_option); - - bool is_valid_; - - // Values parsed from the original URL. - GURL origin_; - FileSystemType mount_type_; - base::FilePath virtual_path_; - - // Values obtained by cracking URLs. - // |mount_filesystem_id_| is retrieved from the first round of cracking, - // and the rest of the fields are from recursive cracking. Permission - // checking on the top-level mount information should be done with the former, - // and the low-level file operation should be implemented with the latter. - std::string mount_filesystem_id_; - FileSystemType type_; - base::FilePath path_; - std::string filesystem_id_; - FileSystemMountOption mount_option_; -}; - -typedef std::set<FileSystemURL, FileSystemURL::Comparator> FileSystemURLSet; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_URL_H_ +#include "storage/browser/fileapi/file_system_url.h" diff --git a/webkit/browser/fileapi/file_system_url_request_job.h b/webkit/browser/fileapi/file_system_url_request_job.h index 1d29914..30174d5 100644 --- a/webkit/browser/fileapi/file_system_url_request_job.h +++ b/webkit/browser/fileapi/file_system_url_request_job.h @@ -1,85 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_URL_REQUEST_JOB_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_URL_REQUEST_JOB_H_ - -#include <string> - -#include "base/files/file.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "net/http/http_byte_range.h" -#include "net/url_request/url_request_job.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/storage_browser_export.h" - -class GURL; - -namespace base { -class FilePath; -} - -namespace storage { -class FileStreamReader; -} - -namespace storage { -class FileSystemContext; - -// A request job that handles reading filesystem: URLs -class STORAGE_EXPORT_PRIVATE FileSystemURLRequestJob - : public net::URLRequestJob { - public: - FileSystemURLRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const std::string& storage_domain, - FileSystemContext* file_system_context); - - // URLRequestJob methods: - virtual void Start() OVERRIDE; - virtual void Kill() OVERRIDE; - virtual bool ReadRawData(net::IOBuffer* buf, - int buf_size, - int* bytes_read) OVERRIDE; - virtual bool IsRedirectResponse(GURL* location, - int* http_status_code) OVERRIDE; - virtual void SetExtraRequestHeaders( - const net::HttpRequestHeaders& headers) OVERRIDE; - virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE; - virtual int GetResponseCode() const OVERRIDE; - - // FilterContext methods (via URLRequestJob): - virtual bool GetMimeType(std::string* mime_type) const OVERRIDE; - - private: - class CallbackDispatcher; - - virtual ~FileSystemURLRequestJob(); - - void StartAsync(); - void DidAttemptAutoMount(base::File::Error result); - void DidGetMetadata(base::File::Error error_code, - const base::File::Info& file_info); - void DidRead(int result); - void NotifyFailed(int rv); - - const std::string storage_domain_; - FileSystemContext* file_system_context_; - scoped_ptr<storage::FileStreamReader> reader_; - FileSystemURL url_; - bool is_directory_; - scoped_ptr<net::HttpResponseInfo> response_info_; - int64 remaining_bytes_; - net::HttpByteRange byte_range_; - base::WeakPtrFactory<FileSystemURLRequestJob> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(FileSystemURLRequestJob); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_URL_REQUEST_JOB_H_ +#include "storage/browser/fileapi/file_system_url_request_job.h" diff --git a/webkit/browser/fileapi/file_system_url_request_job_factory.h b/webkit/browser/fileapi/file_system_url_request_job_factory.h index df97d21..05b9aba 100644 --- a/webkit/browser/fileapi/file_system_url_request_job_factory.h +++ b/webkit/browser/fileapi/file_system_url_request_job_factory.h @@ -1,31 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_URL_REQUEST_JOB_FACTORY_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_URL_REQUEST_JOB_FACTORY_H_ - -#include <string> - -#include "net/url_request/url_request_job_factory.h" - -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class MessageLoopProxy; -} // namespace base - -namespace storage { - -class FileSystemContext; - -// |context|'s lifetime should exceed the lifetime of the ProtocolHandler. -// Currently, this is only used by ProfileIOData which owns |context| and the -// ProtocolHandler. -STORAGE_EXPORT net::URLRequestJobFactory::ProtocolHandler* - CreateFileSystemProtocolHandler(const std::string& storage_domain, - FileSystemContext* context); - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_URL_REQUEST_JOB_FACTORY_H_ +#include "storage/browser/fileapi/file_system_url_request_job_factory.h" diff --git a/webkit/browser/fileapi/file_system_usage_cache.h b/webkit/browser/fileapi/file_system_usage_cache.h index 7cea495..89c8c43 100644 --- a/webkit/browser/fileapi/file_system_usage_cache.h +++ b/webkit/browser/fileapi/file_system_usage_cache.h @@ -1,105 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_USAGE_CACHE_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_USAGE_CACHE_H_ - -#include <map> - -#include "base/basictypes.h" -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/sequenced_task_runner.h" -#include "webkit/browser/storage_browser_export.h" - -namespace storage { - -class TimedTaskHelper; - -class STORAGE_EXPORT_PRIVATE FileSystemUsageCache { - public: - explicit FileSystemUsageCache(base::SequencedTaskRunner* task_runner); - ~FileSystemUsageCache(); - - // Gets the size described in the .usage file even if dirty > 0 or - // is_valid == false. Returns true if the .usage file is available. - bool GetUsage(const base::FilePath& usage_file_path, int64* usage); - - // Gets the dirty count in the .usage file. - // Returns true if the .usage file is available. - bool GetDirty(const base::FilePath& usage_file_path, uint32* dirty); - - // Increments or decrements the "dirty" entry in the .usage file. - // Returns false if no .usage is available. - bool IncrementDirty(const base::FilePath& usage_file_path); - bool DecrementDirty(const base::FilePath& usage_file_path); - - // Notifies quota system that it needs to recalculate the usage cache of the - // origin. Returns false if no .usage is available. - bool Invalidate(const base::FilePath& usage_file_path); - bool IsValid(const base::FilePath& usage_file_path); - - // Updates the size described in the .usage file. - bool UpdateUsage(const base::FilePath& usage_file_path, int64 fs_usage); - - // Updates the size described in the .usage file by delta with keeping dirty - // even if dirty > 0. - bool AtomicUpdateUsageByDelta(const base::FilePath& usage_file_path, - int64 delta); - - bool Exists(const base::FilePath& usage_file_path); - bool Delete(const base::FilePath& usage_file_path); - - void CloseCacheFiles(); - - static const base::FilePath::CharType kUsageFileName[]; - static const char kUsageFileHeader[]; - static const int kUsageFileSize; - static const int kUsageFileHeaderSize; - - private: - typedef std::map<base::FilePath, base::File*> CacheFiles; - - // Read the size, validity and the "dirty" entry described in the .usage file. - // Returns less than zero if no .usage file is available. - bool Read(const base::FilePath& usage_file_path, - bool* is_valid, - uint32* dirty, - int64* usage); - - bool Write(const base::FilePath& usage_file_path, - bool is_valid, - int32 dirty, - int64 fs_usage); - - base::File* GetFile(const base::FilePath& file_path); - - bool ReadBytes(const base::FilePath& file_path, - char* buffer, - int64 buffer_size); - bool WriteBytes(const base::FilePath& file_path, - const char* buffer, - int64 buffer_size); - bool FlushFile(const base::FilePath& file_path); - void ScheduleCloseTimer(); - - bool HasCacheFileHandle(const base::FilePath& file_path); - - bool CalledOnValidThread(); - - scoped_ptr<TimedTaskHelper> timer_; - CacheFiles cache_files_; - - scoped_refptr<base::SequencedTaskRunner> task_runner_; - - base::WeakPtrFactory<FileSystemUsageCache> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(FileSystemUsageCache); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_SYSTEM_USAGE_CACHE_H_ +#include "storage/browser/fileapi/file_system_usage_cache.h" diff --git a/webkit/browser/fileapi/file_writer_delegate.h b/webkit/browser/fileapi/file_writer_delegate.h index f37dcf5..55fb98f 100644 --- a/webkit/browser/fileapi/file_writer_delegate.h +++ b/webkit/browser/fileapi/file_writer_delegate.h @@ -1,110 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_FILE_WRITER_DELEGATE_H_ -#define WEBKIT_BROWSER_FILEAPI_FILE_WRITER_DELEGATE_H_ - -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/time/time.h" -#include "net/base/file_stream.h" -#include "net/base/io_buffer.h" -#include "net/url_request/url_request.h" -#include "webkit/browser/storage_browser_export.h" - -namespace storage { - -class FileStreamWriter; - -class STORAGE_EXPORT_PRIVATE FileWriterDelegate - : public net::URLRequest::Delegate { - public: - enum FlushPolicy { - FLUSH_ON_COMPLETION, - NO_FLUSH_ON_COMPLETION, - }; - - enum WriteProgressStatus { - SUCCESS_IO_PENDING, - SUCCESS_COMPLETED, - ERROR_WRITE_STARTED, - ERROR_WRITE_NOT_STARTED, - }; - - typedef base::Callback<void(base::File::Error result, - int64 bytes, - WriteProgressStatus write_status)> - DelegateWriteCallback; - - FileWriterDelegate(scoped_ptr<FileStreamWriter> file_writer, - FlushPolicy flush_policy); - virtual ~FileWriterDelegate(); - - void Start(scoped_ptr<net::URLRequest> request, - const DelegateWriteCallback& write_callback); - - // Cancels the current write operation. This will synchronously or - // asynchronously call the given write callback (which may result in - // deleting this). - void Cancel(); - - virtual void OnReceivedRedirect(net::URLRequest* request, - const net::RedirectInfo& redirect_info, - bool* defer_redirect) OVERRIDE; - virtual void OnAuthRequired(net::URLRequest* request, - net::AuthChallengeInfo* auth_info) OVERRIDE; - virtual void OnCertificateRequested( - net::URLRequest* request, - net::SSLCertRequestInfo* cert_request_info) OVERRIDE; - virtual void OnSSLCertificateError(net::URLRequest* request, - const net::SSLInfo& ssl_info, - bool fatal) OVERRIDE; - virtual void OnResponseStarted(net::URLRequest* request) OVERRIDE; - virtual void OnReadCompleted(net::URLRequest* request, - int bytes_read) OVERRIDE; - - private: - void OnGetFileInfoAndStartRequest( - scoped_ptr<net::URLRequest> request, - base::File::Error error, - const base::File::Info& file_info); - void Read(); - void OnDataReceived(int bytes_read); - void Write(); - void OnDataWritten(int write_response); - void OnError(base::File::Error error); - void OnProgress(int bytes_read, bool done); - void OnWriteCancelled(int status); - void MaybeFlushForCompletion(base::File::Error error, - int bytes_written, - WriteProgressStatus progress_status); - void OnFlushed(base::File::Error error, - int bytes_written, - WriteProgressStatus progress_status, - int flush_error); - - WriteProgressStatus GetCompletionStatusOnError() const; - - DelegateWriteCallback write_callback_; - scoped_ptr<FileStreamWriter> file_stream_writer_; - base::Time last_progress_event_time_; - bool writing_started_; - FlushPolicy flush_policy_; - int bytes_written_backlog_; - int bytes_written_; - int bytes_read_; - scoped_refptr<net::IOBufferWithSize> io_buffer_; - scoped_refptr<net::DrainableIOBuffer> cursor_; - scoped_ptr<net::URLRequest> request_; - - base::WeakPtrFactory<FileWriterDelegate> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(FileWriterDelegate); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_FILE_WRITER_DELEGATE_H_ +#include "storage/browser/fileapi/file_writer_delegate.h" diff --git a/webkit/browser/fileapi/isolated_context.h b/webkit/browser/fileapi/isolated_context.h index 14a80ad..15917f4 100644 --- a/webkit/browser/fileapi/isolated_context.h +++ b/webkit/browser/fileapi/isolated_context.h @@ -1,201 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_ISOLATED_CONTEXT_H_ -#define WEBKIT_BROWSER_FILEAPI_ISOLATED_CONTEXT_H_ - -#include <map> -#include <set> -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/files/file_path.h" -#include "base/lazy_instance.h" -#include "base/memory/singleton.h" -#include "base/synchronization/lock.h" -#include "webkit/browser/fileapi/mount_points.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/fileapi/file_system_types.h" - -namespace storage { -class FileSystemURL; -} - -namespace storage { - -// Manages isolated filesystem mount points which have no well-known names -// and are identified by a string 'filesystem ID', which usually just looks -// like random value. -// This type of filesystem can be created on the fly and may go away when it has -// no references from renderers. -// Files in an isolated filesystem are registered with corresponding names and -// identified by a filesystem URL like: -// -// filesystem:<origin>/isolated/<filesystem_id>/<name>/relative/path -// -// Some methods of this class are virtual just for mocking. -// -class STORAGE_EXPORT IsolatedContext : public MountPoints { - public: - class STORAGE_EXPORT FileInfoSet { - public: - FileInfoSet(); - ~FileInfoSet(); - - // Add the given |path| to the set and populates |registered_name| with - // the registered name assigned for the path. |path| needs to be - // absolute and should not contain parent references. - // Return false if the |path| is not valid and could not be added. - bool AddPath(const base::FilePath& path, std::string* registered_name); - - // Add the given |path| with the |name|. - // Return false if the |name| is already registered in the set or - // is not valid and could not be added. - bool AddPathWithName(const base::FilePath& path, const std::string& name); - - const std::set<MountPointInfo>& fileset() const { return fileset_; } - - private: - std::set<MountPointInfo> fileset_; - }; - - // The instance is lazily created per browser process. - static IsolatedContext* GetInstance(); - - // Returns true if the given filesystem type is managed by IsolatedContext - // (i.e. if the given |type| is Isolated or External). - // TODO(kinuko): needs a better function name. - static bool IsIsolatedType(FileSystemType type); - - // Registers a new isolated filesystem with the given FileInfoSet |files| - // and returns the new filesystem_id. The files are registered with their - // register_name as their keys so that later we can resolve the full paths - // for the given name. We only expose the name and the ID for the - // newly created filesystem to the renderer for the sake of security. - // - // The renderer will be sending filesystem requests with a virtual path like - // '/<filesystem_id>/<registered_name>/<relative_path_from_the_dropped_path>' - // for which we could crack in the browser process by calling - // CrackIsolatedPath to get the full path. - // - // For example: if a dropped file has a path like '/a/b/foo' and we register - // the path with the name 'foo' in the newly created filesystem. - // Later if the context is asked to crack a virtual path like '/<fsid>/foo' - // it can properly return the original path '/a/b/foo' by looking up the - // internal mapping. Similarly if a dropped entry is a directory and its - // path is like '/a/b/dir' a virtual path like '/<fsid>/dir/foo' can be - // cracked into '/a/b/dir/foo'. - // - // Note that the path in |fileset| that contains '..' or is not an - // absolute path is skipped and is not registered. - std::string RegisterDraggedFileSystem(const FileInfoSet& files); - - // Registers a new isolated filesystem for a given |path| of filesystem - // |type| filesystem with |filesystem_id| and returns a new filesystem ID. - // |path| must be an absolute path which has no parent references ('..'). - // If |register_name| is non-null and has non-empty string the path is - // registered as the given |register_name|, otherwise it is populated - // with the name internally assigned to the path. - std::string RegisterFileSystemForPath(FileSystemType type, - const std::string& filesystem_id, - const base::FilePath& path, - std::string* register_name); - - // Registers a virtual filesystem. This is different from - // RegisterFileSystemForPath because register_name is required, and - // cracked_path_prefix is allowed to be non-absolute. - // |register_name| is required, since we cannot infer one from the path. - // |cracked_path_prefix| has no parent references, but can be relative. - std::string RegisterFileSystemForVirtualPath( - FileSystemType type, - const std::string& register_name, - const base::FilePath& cracked_path_prefix); - - // Revokes all filesystem(s) registered for the given path. - // This is assumed to be called when the registered path becomes - // globally invalid, e.g. when a device for the path is detached. - // - // Note that this revokes the filesystem no matter how many references it has. - // It is ok to call this for the path that has no associated filesystems. - // Note that this only works for the filesystems registered by - // |RegisterFileSystemForPath|. - void RevokeFileSystemByPath(const base::FilePath& path); - - // Adds a reference to a filesystem specified by the given filesystem_id. - void AddReference(const std::string& filesystem_id); - - // Removes a reference to a filesystem specified by the given filesystem_id. - // If the reference count reaches 0 the isolated context gets destroyed. - // It is OK to call this on the filesystem that has been already deleted - // (e.g. by RevokeFileSystemByPath). - void RemoveReference(const std::string& filesystem_id); - - // Returns a set of dragged MountPointInfos registered for the - // |filesystem_id|. - // The filesystem_id must be pointing to a dragged file system - // (i.e. must be the one registered by RegisterDraggedFileSystem). - // Returns false if the |filesystem_id| is not valid. - bool GetDraggedFileInfo(const std::string& filesystem_id, - std::vector<MountPointInfo>* files) const; - - // MountPoints overrides. - virtual bool HandlesFileSystemMountType(FileSystemType type) const OVERRIDE; - virtual bool RevokeFileSystem(const std::string& filesystem_id) OVERRIDE; - virtual bool GetRegisteredPath(const std::string& filesystem_id, - base::FilePath* path) const OVERRIDE; - virtual bool CrackVirtualPath( - const base::FilePath& virtual_path, - std::string* filesystem_id, - FileSystemType* type, - std::string* cracked_id, - base::FilePath* path, - FileSystemMountOption* mount_option) const OVERRIDE; - virtual FileSystemURL CrackURL(const GURL& url) const OVERRIDE; - virtual FileSystemURL CreateCrackedFileSystemURL( - const GURL& origin, - FileSystemType type, - const base::FilePath& path) const OVERRIDE; - - // Returns the virtual root path that looks like /<filesystem_id>. - base::FilePath CreateVirtualRootPath(const std::string& filesystem_id) const; - - private: - friend struct base::DefaultLazyInstanceTraits<IsolatedContext>; - - // Represents each file system instance (defined in the .cc). - class Instance; - - typedef std::map<std::string, Instance*> IDToInstance; - - // Reverse map from registered path to IDs. - typedef std::map<base::FilePath, std::set<std::string> > PathToID; - - // Obtain an instance of this class via GetInstance(). - IsolatedContext(); - virtual ~IsolatedContext(); - - // MountPoints overrides. - virtual FileSystemURL CrackFileSystemURL( - const FileSystemURL& url) const OVERRIDE; - - // Unregisters a file system of given |filesystem_id|. Must be called with - // lock_ held. Returns true if the file system is unregistered. - bool UnregisterFileSystem(const std::string& filesystem_id); - - // Returns a new filesystem_id. Called with lock. - std::string GetNewFileSystemId() const; - - // This lock needs to be obtained when accessing the instance_map_. - mutable base::Lock lock_; - - IDToInstance instance_map_; - PathToID path_to_id_map_; - - DISALLOW_COPY_AND_ASSIGN(IsolatedContext); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_ISOLATED_CONTEXT_H_ +#include "storage/browser/fileapi/isolated_context.h" diff --git a/webkit/browser/fileapi/isolated_file_system_backend.h b/webkit/browser/fileapi/isolated_file_system_backend.h index b252845..5a66c39 100644 --- a/webkit/browser/fileapi/isolated_file_system_backend.h +++ b/webkit/browser/fileapi/isolated_file_system_backend.h @@ -1,57 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_ISOLATED_FILE_SYSTEM_BACKEND_H_ -#define WEBKIT_BROWSER_FILEAPI_ISOLATED_FILE_SYSTEM_BACKEND_H_ - -#include "base/memory/scoped_ptr.h" -#include "webkit/browser/fileapi/file_system_backend.h" - -namespace storage { - -class AsyncFileUtilAdapter; - -class IsolatedFileSystemBackend : public FileSystemBackend { - public: - IsolatedFileSystemBackend(); - virtual ~IsolatedFileSystemBackend(); - - // FileSystemBackend implementation. - virtual bool CanHandleType(FileSystemType type) const OVERRIDE; - virtual void Initialize(FileSystemContext* context) OVERRIDE; - virtual void ResolveURL(const FileSystemURL& url, - OpenFileSystemMode mode, - const OpenFileSystemCallback& callback) OVERRIDE; - virtual AsyncFileUtil* GetAsyncFileUtil(FileSystemType type) OVERRIDE; - virtual WatcherManager* GetWatcherManager(FileSystemType type) OVERRIDE; - virtual CopyOrMoveFileValidatorFactory* GetCopyOrMoveFileValidatorFactory( - FileSystemType type, - base::File::Error* error_code) OVERRIDE; - virtual FileSystemOperation* CreateFileSystemOperation( - const FileSystemURL& url, - FileSystemContext* context, - base::File::Error* error_code) const OVERRIDE; - virtual bool SupportsStreaming(const FileSystemURL& url) const OVERRIDE; - virtual bool HasInplaceCopyImplementation( - storage::FileSystemType type) const OVERRIDE; - virtual scoped_ptr<storage::FileStreamReader> CreateFileStreamReader( - const FileSystemURL& url, - int64 offset, - const base::Time& expected_modification_time, - FileSystemContext* context) const OVERRIDE; - virtual scoped_ptr<FileStreamWriter> CreateFileStreamWriter( - const FileSystemURL& url, - int64 offset, - FileSystemContext* context) const OVERRIDE; - virtual FileSystemQuotaUtil* GetQuotaUtil() OVERRIDE; - - private: - scoped_ptr<AsyncFileUtilAdapter> isolated_file_util_; - scoped_ptr<AsyncFileUtilAdapter> dragged_file_util_; - scoped_ptr<AsyncFileUtilAdapter> transient_file_util_; -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_ISOLATED_FILE_SYSTEM_BACKEND_H_ +#include "storage/browser/fileapi/isolated_file_system_backend.h" diff --git a/webkit/browser/fileapi/local_file_stream_writer.h b/webkit/browser/fileapi/local_file_stream_writer.h index 0456614..8afb666 100644 --- a/webkit/browser/fileapi/local_file_stream_writer.h +++ b/webkit/browser/fileapi/local_file_stream_writer.h @@ -1,100 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_LOCAL_FILE_STREAM_WRITER_H_ -#define WEBKIT_BROWSER_FILEAPI_LOCAL_FILE_STREAM_WRITER_H_ - -#include <utility> - -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/files/file_path.h" -#include "base/gtest_prod_util.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/task_runner.h" -#include "webkit/browser/fileapi/file_stream_writer.h" -#include "webkit/browser/storage_browser_export.h" - -namespace content { -class LocalFileStreamWriterTest; -} - -namespace net { -class FileStream; -} - -namespace storage { - -// This class is a thin wrapper around net::FileStream for writing local files. -class STORAGE_EXPORT LocalFileStreamWriter - : public NON_EXPORTED_BASE(FileStreamWriter) { - public: - virtual ~LocalFileStreamWriter(); - - // FileStreamWriter overrides. - virtual int Write(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) OVERRIDE; - virtual int Cancel(const net::CompletionCallback& callback) OVERRIDE; - virtual int Flush(const net::CompletionCallback& callback) OVERRIDE; - - private: - friend class content::LocalFileStreamWriterTest; - friend class FileStreamWriter; - LocalFileStreamWriter(base::TaskRunner* task_runner, - const base::FilePath& file_path, - int64 initial_offset, - OpenOrCreate open_or_create); - - // Opens |file_path_| and if it succeeds, proceeds to InitiateSeek(). - // If failed, the error code is returned by calling |error_callback|. - int InitiateOpen(const net::CompletionCallback& error_callback, - const base::Closure& main_operation); - void DidOpen(const net::CompletionCallback& error_callback, - const base::Closure& main_operation, - int result); - - // Seeks to |initial_offset_| and proceeds to |main_operation| if it succeeds. - // If failed, the error code is returned by calling |error_callback|. - void InitiateSeek(const net::CompletionCallback& error_callback, - const base::Closure& main_operation); - void DidSeek(const net::CompletionCallback& error_callback, - const base::Closure& main_operation, - int64 result); - - // Passed as the |main_operation| of InitiateOpen() function. - void ReadyToWrite(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback); - - // Writes asynchronously to the file. - int InitiateWrite(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback); - void DidWrite(const net::CompletionCallback& callback, int result); - - // Flushes asynchronously to the file. - int InitiateFlush(const net::CompletionCallback& callback); - void DidFlush(const net::CompletionCallback& callback, int result); - - // Stops the in-flight operation and calls |cancel_callback_| if it has been - // set by Cancel() for the current operation. - bool CancelIfRequested(); - - // Initialization parameters. - const base::FilePath file_path_; - OpenOrCreate open_or_create_; - const int64 initial_offset_; - scoped_refptr<base::TaskRunner> task_runner_; - - // Current states of the operation. - bool has_pending_operation_; - scoped_ptr<net::FileStream> stream_impl_; - net::CompletionCallback cancel_callback_; - - base::WeakPtrFactory<LocalFileStreamWriter> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(LocalFileStreamWriter); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_LOCAL_FILE_STREAM_WRITER_H_ +#include "storage/browser/fileapi/local_file_stream_writer.h" diff --git a/webkit/browser/fileapi/local_file_util.h b/webkit/browser/fileapi/local_file_util.h index 25b363d..dea7424d 100644 --- a/webkit/browser/fileapi/local_file_util.h +++ b/webkit/browser/fileapi/local_file_util.h @@ -1,94 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_LOCAL_FILE_UTIL_H_ -#define WEBKIT_BROWSER_FILEAPI_LOCAL_FILE_UTIL_H_ - -#include "base/compiler_specific.h" -#include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" -#include "webkit/browser/fileapi/file_system_file_util.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class Time; -} - -class GURL; - -namespace storage { - -class FileSystemOperationContext; -class FileSystemURL; - -// An instance of this class is created and owned by *FileSystemBackend. -class STORAGE_EXPORT LocalFileUtil - : public FileSystemFileUtil { - public: - LocalFileUtil(); - virtual ~LocalFileUtil(); - - virtual base::File CreateOrOpen( - FileSystemOperationContext* context, - const FileSystemURL& url, - int file_flags) OVERRIDE; - virtual base::File::Error EnsureFileExists( - FileSystemOperationContext* context, - const FileSystemURL& url, bool* created) OVERRIDE; - virtual base::File::Error CreateDirectory( - FileSystemOperationContext* context, - const FileSystemURL& url, - bool exclusive, - bool recursive) OVERRIDE; - virtual base::File::Error GetFileInfo( - FileSystemOperationContext* context, - const FileSystemURL& url, - base::File::Info* file_info, - base::FilePath* platform_file) OVERRIDE; - virtual scoped_ptr<AbstractFileEnumerator> CreateFileEnumerator( - FileSystemOperationContext* context, - const FileSystemURL& root_url) OVERRIDE; - virtual base::File::Error GetLocalFilePath( - FileSystemOperationContext* context, - const FileSystemURL& file_system_url, - base::FilePath* local_file_path) OVERRIDE; - virtual base::File::Error Touch( - FileSystemOperationContext* context, - const FileSystemURL& url, - const base::Time& last_access_time, - const base::Time& last_modified_time) OVERRIDE; - virtual base::File::Error Truncate( - FileSystemOperationContext* context, - const FileSystemURL& url, - int64 length) OVERRIDE; - virtual base::File::Error CopyOrMoveFile( - FileSystemOperationContext* context, - const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - bool copy) OVERRIDE; - virtual base::File::Error CopyInForeignFile( - FileSystemOperationContext* context, - const base::FilePath& src_file_path, - const FileSystemURL& dest_url) OVERRIDE; - virtual base::File::Error DeleteFile( - FileSystemOperationContext* context, - const FileSystemURL& url) OVERRIDE; - virtual base::File::Error DeleteDirectory( - FileSystemOperationContext* context, - const FileSystemURL& url) OVERRIDE; - virtual storage::ScopedFile CreateSnapshotFile( - FileSystemOperationContext* context, - const FileSystemURL& url, - base::File::Error* error, - base::File::Info* file_info, - base::FilePath* platform_path) OVERRIDE; - - private: - DISALLOW_COPY_AND_ASSIGN(LocalFileUtil); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_LOCAL_FILE_UTIL_H_ +#include "storage/browser/fileapi/local_file_util.h" diff --git a/webkit/browser/fileapi/mount_points.h b/webkit/browser/fileapi/mount_points.h index 8d71503..1803ac6 100644 --- a/webkit/browser/fileapi/mount_points.h +++ b/webkit/browser/fileapi/mount_points.h @@ -1,108 +1,5 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_MOUNT_POINTS_H_ -#define WEBKIT_BROWSER_FILEAPI_MOUNT_POINTS_H_ - -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/files/file_path.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/fileapi/file_system_util.h" - -class GURL; - -namespace storage { -class FileSystemMountOption; -class FileSystemURL; -} - -namespace storage { - -// Represents a set of mount points for File API. -class STORAGE_EXPORT MountPoints { - public: - struct STORAGE_EXPORT MountPointInfo { - MountPointInfo(); - MountPointInfo(const std::string& name, const base::FilePath& path); - - // The name to be used to register the path. The registered file can - // be referred by a virtual path /<filesystem_id>/<name>. - // The name should NOT contain a path separator '/'. - std::string name; - - // The path of the file. - base::FilePath path; - - // For STL operation. - bool operator<(const MountPointInfo& that) const { - return name < that.name; - } - }; - - MountPoints() {} - virtual ~MountPoints() {} - - // Revokes a mount point identified by |mount_name|. - // Returns false if the |mount_name| is not (no longer) registered. - // TODO(kinuko): Probably this should be rather named RevokeMountPoint. - virtual bool RevokeFileSystem(const std::string& mount_name) = 0; - - // Returns true if the MountPoints implementation handles filesystems with - // the given mount type. - virtual bool HandlesFileSystemMountType(FileSystemType type) const = 0; - - // Same as CreateCrackedFileSystemURL, but cracks FileSystemURL created - // from |url|. - virtual FileSystemURL CrackURL(const GURL& url) const = 0; - - // Creates a FileSystemURL with the given origin, type and path and tries to - // crack it as a part of one of the registered mount points. - // If the the URL is not valid or does not belong to any of the mount points - // registered in this context, returns empty, invalid FileSystemURL. - virtual FileSystemURL CreateCrackedFileSystemURL( - const GURL& origin, - storage::FileSystemType type, - const base::FilePath& path) const = 0; - - // Returns the mount point root path registered for a given |mount_name|. - // Returns false if the given |mount_name| is not valid. - virtual bool GetRegisteredPath(const std::string& mount_name, - base::FilePath* path) const = 0; - - // Cracks the given |virtual_path| (which is the path part of a filesystem URL - // without '/external' or '/isolated' prefix part) and populates the - // |mount_name|, |type|, and |path| if the <mount_name> part embedded in - // the |virtual_path| (i.e. the first component of the |virtual_path|) is a - // valid registered filesystem ID or mount name for an existing mount point. - // - // Returns false if the given virtual_path cannot be cracked. - // - // Note that |path| is set to empty paths if the filesystem type is isolated - // and |virtual_path| has no <relative_path> part (i.e. pointing to the - // virtual root). - virtual bool CrackVirtualPath(const base::FilePath& virtual_path, - std::string* mount_name, - FileSystemType* type, - std::string* cracked_id, - base::FilePath* path, - FileSystemMountOption* mount_option) const = 0; - - protected: - friend class FileSystemContext; - - // Same as CrackURL and CreateCrackedFileSystemURL, but cracks the url already - // instantiated as the FileSystemURL class. This is internally used for nested - // URL cracking in FileSystemContext. - virtual FileSystemURL CrackFileSystemURL(const FileSystemURL& url) const = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(MountPoints); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_MOUNT_POINTS_H_ +#include "storage/browser/fileapi/mount_points.h" diff --git a/webkit/browser/fileapi/native_file_util.h b/webkit/browser/fileapi/native_file_util.h index 645cff6..dea1335 100644 --- a/webkit/browser/fileapi/native_file_util.h +++ b/webkit/browser/fileapi/native_file_util.h @@ -1,73 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_NATIVE_FILE_UTIL_H_ -#define WEBKIT_BROWSER_FILEAPI_NATIVE_FILE_UTIL_H_ - -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/files/file_util_proxy.h" -#include "base/memory/scoped_ptr.h" -#include "webkit/browser/fileapi/file_system_file_util.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class Time; -} - -namespace storage { - -// A thin wrapper class for accessing the OS native filesystem. -// This performs common error checks necessary to implement FileUtil family -// in addition to perform native filesystem operations. -// -// For the error checks it performs please see the comment for -// FileSystemFileUtil interface -// (webkit/browser/fileapi/file_system_file_util.h). -// -// Note that all the methods of this class are static and this does NOT -// inherit from FileSystemFileUtil. -class STORAGE_EXPORT_PRIVATE NativeFileUtil { - public: - enum CopyOrMoveMode { - COPY_NOSYNC, - COPY_SYNC, - MOVE - }; - static CopyOrMoveMode CopyOrMoveModeForDestination( - const FileSystemURL& dest_url, bool copy); - - static base::File CreateOrOpen(const base::FilePath& path, int file_flags); - static base::File::Error EnsureFileExists(const base::FilePath& path, - bool* created); - static base::File::Error CreateDirectory(const base::FilePath& path, - bool exclusive, - bool recursive); - static base::File::Error GetFileInfo(const base::FilePath& path, - base::File::Info* file_info); - static scoped_ptr<FileSystemFileUtil::AbstractFileEnumerator> - CreateFileEnumerator(const base::FilePath& root_path, - bool recursive); - static base::File::Error Touch(const base::FilePath& path, - const base::Time& last_access_time, - const base::Time& last_modified_time); - static base::File::Error Truncate(const base::FilePath& path, - int64 length); - static bool PathExists(const base::FilePath& path); - static bool DirectoryExists(const base::FilePath& path); - static base::File::Error CopyOrMoveFile( - const base::FilePath& src_path, - const base::FilePath& dest_path, - FileSystemOperation::CopyOrMoveOption option, - CopyOrMoveMode mode); - static base::File::Error DeleteFile(const base::FilePath& path); - static base::File::Error DeleteDirectory(const base::FilePath& path); - - private: - DISALLOW_IMPLICIT_CONSTRUCTORS(NativeFileUtil); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_NATIVE_FILE_UTIL_H_ +#include "storage/browser/fileapi/native_file_util.h" diff --git a/webkit/browser/fileapi/obfuscated_file_util.h b/webkit/browser/fileapi/obfuscated_file_util.h index aff2c7c..17d99c3 100644 --- a/webkit/browser/fileapi/obfuscated_file_util.h +++ b/webkit/browser/fileapi/obfuscated_file_util.h @@ -1,359 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_OBFUSCATED_FILE_UTIL_H_ -#define WEBKIT_BROWSER_FILEAPI_OBFUSCATED_FILE_UTIL_H_ - -#include <map> -#include <set> -#include <string> -#include <vector> - -#include "base/callback_forward.h" -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/files/file_util_proxy.h" -#include "base/gtest_prod_util.h" -#include "base/memory/scoped_ptr.h" -#include "webkit/browser/fileapi/file_system_file_util.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/fileapi/sandbox_directory_database.h" -#include "webkit/browser/fileapi/sandbox_file_system_backend_delegate.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/blob/shareable_file_reference.h" -#include "webkit/common/fileapi/file_system_types.h" - -namespace base { -class SequencedTaskRunner; -class TimeTicks; -} - -namespace content { -class ObfuscatedFileUtilTest; -class QuotaBackendImplTest; -} - -namespace storage { -class SpecialStoragePolicy; -} - -class GURL; - -namespace storage { - -class FileSystemOperationContext; -class SandboxOriginDatabaseInterface; -class TimedTaskHelper; - -// This file util stores directory information in LevelDB to obfuscate -// and to neutralize virtual file paths given by arbitrary apps. -// Files are stored with two-level isolation: per-origin and per-type. -// The isolation is done by storing data in separate directory partitions. -// For example, a file in Temporary file system for origin 'www.example.com' -// is stored in a different partition for a file in Persistent file system -// for the same origin, or for Temporary file system for another origin. -// -// * Per-origin directory name information is stored in a separate LevelDB, -// which is maintained by SandboxOriginDatabase. -// * Per-type directory name information is given by -// GetTypeStringForURLCallback that is given in CTOR. -// We use a small static mapping (e.g. 't' for Temporary type) for -// regular sandbox filesystems. -// -// The overall implementation philosophy of this class is that partial failures -// should leave us with an intact database; we'd prefer to leak the occasional -// backing file than have a database entry whose backing file is missing. When -// doing FSCK operations, if you find a loose backing file with no reference, -// you may safely delete it. -// -// This class must be deleted on the FILE thread, because that's where -// DropDatabases needs to be called. -class STORAGE_EXPORT_PRIVATE ObfuscatedFileUtil - : public FileSystemFileUtil { - public: - // Origin enumerator interface. - // An instance of this interface is assumed to be called on the file thread. - class AbstractOriginEnumerator { - public: - virtual ~AbstractOriginEnumerator() {} - - // Returns the next origin. Returns empty if there are no more origins. - virtual GURL Next() = 0; - - // Returns the current origin's information. - // |type_string| must be ascii string. - virtual bool HasTypeDirectory(const std::string& type_string) const = 0; - }; - - typedef base::Callback<std::string(const FileSystemURL&)> - GetTypeStringForURLCallback; - - // |get_type_string_for_url| is user-defined callback that should return - // a type string for the given FileSystemURL. The type string is used - // to provide per-type isolation in the sandboxed filesystem directory. - // Note that this method is called on file_task_runner. - // - // |known_type_strings| are known type string names that this file system - // should care about. - // This info is used to determine whether we could delete the entire - // origin directory or not in DeleteDirectoryForOriginAndType. If no directory - // for any known type exists the origin directory may get deleted when - // one origin/type pair is deleted. - // - ObfuscatedFileUtil(storage::SpecialStoragePolicy* special_storage_policy, - const base::FilePath& file_system_directory, - leveldb::Env* env_override, - base::SequencedTaskRunner* file_task_runner, - const GetTypeStringForURLCallback& get_type_string_for_url, - const std::set<std::string>& known_type_strings, - SandboxFileSystemBackendDelegate* sandbox_delegate); - virtual ~ObfuscatedFileUtil(); - - // FileSystemFileUtil overrides. - virtual base::File CreateOrOpen( - FileSystemOperationContext* context, - const FileSystemURL& url, - int file_flags) OVERRIDE; - virtual base::File::Error EnsureFileExists( - FileSystemOperationContext* context, - const FileSystemURL& url, bool* created) OVERRIDE; - virtual base::File::Error CreateDirectory( - FileSystemOperationContext* context, - const FileSystemURL& url, - bool exclusive, - bool recursive) OVERRIDE; - virtual base::File::Error GetFileInfo( - FileSystemOperationContext* context, - const FileSystemURL& url, - base::File::Info* file_info, - base::FilePath* platform_file) OVERRIDE; - virtual scoped_ptr<AbstractFileEnumerator> CreateFileEnumerator( - FileSystemOperationContext* context, - const FileSystemURL& root_url) OVERRIDE; - virtual base::File::Error GetLocalFilePath( - FileSystemOperationContext* context, - const FileSystemURL& file_system_url, - base::FilePath* local_path) OVERRIDE; - virtual base::File::Error Touch( - FileSystemOperationContext* context, - const FileSystemURL& url, - const base::Time& last_access_time, - const base::Time& last_modified_time) OVERRIDE; - virtual base::File::Error Truncate( - FileSystemOperationContext* context, - const FileSystemURL& url, - int64 length) OVERRIDE; - virtual base::File::Error CopyOrMoveFile( - FileSystemOperationContext* context, - const FileSystemURL& src_url, - const FileSystemURL& dest_url, - CopyOrMoveOption option, - bool copy) OVERRIDE; - virtual base::File::Error CopyInForeignFile( - FileSystemOperationContext* context, - const base::FilePath& src_file_path, - const FileSystemURL& dest_url) OVERRIDE; - virtual base::File::Error DeleteFile( - FileSystemOperationContext* context, - const FileSystemURL& url) OVERRIDE; - virtual base::File::Error DeleteDirectory( - FileSystemOperationContext* context, - const FileSystemURL& url) OVERRIDE; - virtual storage::ScopedFile CreateSnapshotFile( - FileSystemOperationContext* context, - const FileSystemURL& url, - base::File::Error* error, - base::File::Info* file_info, - base::FilePath* platform_path) OVERRIDE; - - // Same as the other CreateFileEnumerator, but with recursive support. - scoped_ptr<AbstractFileEnumerator> CreateFileEnumerator( - FileSystemOperationContext* context, - const FileSystemURL& root_url, - bool recursive); - - // Returns true if the directory |url| is empty. - bool IsDirectoryEmpty( - FileSystemOperationContext* context, - const FileSystemURL& url); - - // Gets the topmost directory specific to this origin and type. This will - // contain both the directory database's files and all the backing file - // subdirectories. - // Returns the topmost origin directory if |type_string| is empty. - // Returns an empty path if the directory is undefined. - // If the directory is defined, it will be returned, even if - // there is a file system error (e.g. the directory doesn't exist on disk and - // |create| is false). Callers should always check |error_code| to make sure - // the returned path is usable. - base::FilePath GetDirectoryForOriginAndType( - const GURL& origin, - const std::string& type_string, - bool create, - base::File::Error* error_code); - - // Deletes the topmost directory specific to this origin and type. This will - // delete its directory database. - // Deletes the topmost origin directory if |type_string| is empty. - bool DeleteDirectoryForOriginAndType( - const GURL& origin, - const std::string& type_string); - - // This method and all methods of its returned class must be called only on - // the FILE thread. The caller is responsible for deleting the returned - // object. - AbstractOriginEnumerator* CreateOriginEnumerator(); - - // Deletes a directory database from the database list in the ObfuscatedFSFU - // and destroys the database on the disk. - bool DestroyDirectoryDatabase(const GURL& origin, - const std::string& type_string); - - // Computes a cost for storing a given file in the obfuscated FSFU. - // As the cost of a file is independent of the cost of its parent directories, - // this ignores all but the BaseName of the supplied path. In order to - // compute the cost of adding a multi-segment directory recursively, call this - // on each path segment and add the results. - static int64 ComputeFilePathCost(const base::FilePath& path); - - // Tries to prepopulate directory database for the given type strings. - // This tries from the first one in the given type_strings and stops - // once it succeeds to do so for one database (i.e. it prepopulates - // at most one database). - void MaybePrepopulateDatabase( - const std::vector<std::string>& type_strings_to_prepopulate); - - private: - typedef SandboxDirectoryDatabase::FileId FileId; - typedef SandboxDirectoryDatabase::FileInfo FileInfo; - - friend class ObfuscatedFileEnumerator; - friend class content::ObfuscatedFileUtilTest; - friend class content::QuotaBackendImplTest; - - // Helper method to create an obfuscated file util for regular - // (temporary, persistent) file systems. Used only for testing. - // Note: this is implemented in sandbox_file_system_backend_delegate.cc. - static ObfuscatedFileUtil* CreateForTesting( - storage::SpecialStoragePolicy* special_storage_policy, - const base::FilePath& file_system_directory, - leveldb::Env* env_override, - base::SequencedTaskRunner* file_task_runner); - - base::FilePath GetDirectoryForURL( - const FileSystemURL& url, - bool create, - base::File::Error* error_code); - - // This just calls get_type_string_for_url_ callback that is given in ctor. - std::string CallGetTypeStringForURL(const FileSystemURL& url); - - base::File::Error GetFileInfoInternal( - SandboxDirectoryDatabase* db, - FileSystemOperationContext* context, - const FileSystemURL& url, - FileId file_id, - FileInfo* local_info, - base::File::Info* file_info, - base::FilePath* platform_file_path); - - // Creates a new file, both the underlying backing file and the entry in the - // database. |dest_file_info| is an in-out parameter. Supply the name and - // parent_id; data_path is ignored. On success, data_path will - // always be set to the relative path [from the root of the type-specific - // filesystem directory] of a NEW backing file. Returns the new file. - base::File CreateAndOpenFile( - FileSystemOperationContext* context, - const FileSystemURL& dest_url, - FileInfo* dest_file_info, - int file_flags); - - // The same as CreateAndOpenFile except that a file is not returned and if a - // path is provided in |source_path|, it will be used as a source from which - // to COPY data. - base::File::Error CreateFile( - FileSystemOperationContext* context, - const base::FilePath& source_file_path, - const FileSystemURL& dest_url, - FileInfo* dest_file_info); - - // Updates |db| and |dest_file_info| at the end of creating a new file. - base::File::Error CommitCreateFile( - const base::FilePath& root, - const base::FilePath& local_path, - SandboxDirectoryDatabase* db, - FileInfo* dest_file_info); - - // This converts from a relative path [as is stored in the FileInfo.data_path - // field] to an absolute platform path that can be given to the native - // filesystem. - base::FilePath DataPathToLocalPath( - const FileSystemURL& url, - const base::FilePath& data_file_path); - - std::string GetDirectoryDatabaseKey(const GURL& origin, - const std::string& type_string); - - // This returns NULL if |create| flag is false and a filesystem does not - // exist for the given |url|. - // For read operations |create| should be false. - SandboxDirectoryDatabase* GetDirectoryDatabase(const FileSystemURL& url, - bool create); - - // Gets the topmost directory specific to this origin. This will - // contain both the filesystem type subdirectories. - base::FilePath GetDirectoryForOrigin(const GURL& origin, - bool create, - base::File::Error* error_code); - - void InvalidateUsageCache(FileSystemOperationContext* context, - const GURL& origin, - FileSystemType type); - - void MarkUsed(); - void DropDatabases(); - - // Initializes the origin database. |origin_hint| may be used as a hint - // for initializing database if it's not empty. - bool InitOriginDatabase(const GURL& origin_hint, bool create); - - base::File::Error GenerateNewLocalPath( - SandboxDirectoryDatabase* db, - FileSystemOperationContext* context, - const FileSystemURL& url, - base::FilePath* root, - base::FilePath* local_path); - - base::File CreateOrOpenInternal( - FileSystemOperationContext* context, - const FileSystemURL& url, - int file_flags); - - bool HasIsolatedStorage(const GURL& origin); - - typedef std::map<std::string, SandboxDirectoryDatabase*> DirectoryMap; - DirectoryMap directories_; - scoped_ptr<SandboxOriginDatabaseInterface> origin_database_; - scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy_; - base::FilePath file_system_directory_; - leveldb::Env* env_override_; - - // Used to delete database after a certain period of inactivity. - int64 db_flush_delay_seconds_; - - scoped_refptr<base::SequencedTaskRunner> file_task_runner_; - scoped_ptr<TimedTaskHelper> timer_; - - GetTypeStringForURLCallback get_type_string_for_url_; - std::set<std::string> known_type_strings_; - - // Not owned. - SandboxFileSystemBackendDelegate* sandbox_delegate_; - - DISALLOW_COPY_AND_ASSIGN(ObfuscatedFileUtil); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_OBFUSCATED_FILE_UTIL_H_ +#include "storage/browser/fileapi/obfuscated_file_util.h" diff --git a/webkit/browser/fileapi/open_file_system_mode.h b/webkit/browser/fileapi/open_file_system_mode.h index 3bc352f..40e9fd9 100644 --- a/webkit/browser/fileapi/open_file_system_mode.h +++ b/webkit/browser/fileapi/open_file_system_mode.h @@ -1,22 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_OPEN_FILE_SYSTEM_MODE_H_ -#define WEBKIT_BROWSER_FILEAPI_OPEN_FILE_SYSTEM_MODE_H_ - -namespace storage { - -// Determines the behavior on OpenFileSystem when a specified -// FileSystem does not exist. -// Specifying CREATE_IF_NONEXISTENT may make actual modification on -// disk (e.g. creating a root directory, setting up a metadata database etc) -// if the filesystem hasn't been initialized. -enum OpenFileSystemMode { - OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, - OPEN_FILE_SYSTEM_FAIL_IF_NONEXISTENT, -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_OPEN_FILE_SYSTEM_MODE_H_ +#include "storage/browser/fileapi/open_file_system_mode.h" diff --git a/webkit/browser/fileapi/plugin_private_file_system_backend.h b/webkit/browser/fileapi/plugin_private_file_system_backend.h index bd95bc9..86b19a4 100644 --- a/webkit/browser/fileapi/plugin_private_file_system_backend.h +++ b/webkit/browser/fileapi/plugin_private_file_system_backend.h @@ -1,149 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_PLUGIN_PRIVATE_FILE_SYSTEM_BACKEND_H_ -#define WEBKIT_BROWSER_FILEAPI_PLUGIN_PRIVATE_FILE_SYSTEM_BACKEND_H_ - -#include <set> -#include <string> - -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "webkit/browser/fileapi/file_system_backend.h" -#include "webkit/browser/fileapi/file_system_options.h" -#include "webkit/browser/fileapi/file_system_quota_util.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace content { -class PluginPrivateFileSystemBackendTest; -} - -namespace storage { -class SpecialStoragePolicy; -} - -namespace storage { - -class ObfuscatedFileUtil; -class WatcherManager; - -class STORAGE_EXPORT PluginPrivateFileSystemBackend - : public FileSystemBackend, - public FileSystemQuotaUtil { - public: - class FileSystemIDToPluginMap; - typedef base::Callback<void(base::File::Error result)> StatusCallback; - - PluginPrivateFileSystemBackend( - base::SequencedTaskRunner* file_task_runner, - const base::FilePath& profile_path, - storage::SpecialStoragePolicy* special_storage_policy, - const FileSystemOptions& file_system_options); - virtual ~PluginPrivateFileSystemBackend(); - - // This must be used to open 'private' filesystem instead of regular - // OpenFileSystem. - // |plugin_id| must be an identifier string for per-plugin - // isolation, e.g. name, MIME type etc. - // NOTE: |plugin_id| must be sanitized ASCII string that doesn't - // include *any* dangerous character like '/'. - void OpenPrivateFileSystem( - const GURL& origin_url, - FileSystemType type, - const std::string& filesystem_id, - const std::string& plugin_id, - OpenFileSystemMode mode, - const StatusCallback& callback); - - // FileSystemBackend overrides. - virtual bool CanHandleType(FileSystemType type) const OVERRIDE; - virtual void Initialize(FileSystemContext* context) OVERRIDE; - virtual void ResolveURL(const FileSystemURL& url, - OpenFileSystemMode mode, - const OpenFileSystemCallback& callback) OVERRIDE; - virtual AsyncFileUtil* GetAsyncFileUtil(FileSystemType type) OVERRIDE; - virtual WatcherManager* GetWatcherManager(FileSystemType type) OVERRIDE; - virtual CopyOrMoveFileValidatorFactory* GetCopyOrMoveFileValidatorFactory( - FileSystemType type, - base::File::Error* error_code) OVERRIDE; - virtual FileSystemOperation* CreateFileSystemOperation( - const FileSystemURL& url, - FileSystemContext* context, - base::File::Error* error_code) const OVERRIDE; - virtual bool SupportsStreaming(const FileSystemURL& url) const OVERRIDE; - virtual bool HasInplaceCopyImplementation( - storage::FileSystemType type) const OVERRIDE; - virtual scoped_ptr<storage::FileStreamReader> CreateFileStreamReader( - const FileSystemURL& url, - int64 offset, - const base::Time& expected_modification_time, - FileSystemContext* context) const OVERRIDE; - virtual scoped_ptr<FileStreamWriter> CreateFileStreamWriter( - const FileSystemURL& url, - int64 offset, - FileSystemContext* context) const OVERRIDE; - virtual FileSystemQuotaUtil* GetQuotaUtil() OVERRIDE; - - // FileSystemQuotaUtil overrides. - virtual base::File::Error DeleteOriginDataOnFileTaskRunner( - FileSystemContext* context, - storage::QuotaManagerProxy* proxy, - const GURL& origin_url, - FileSystemType type) OVERRIDE; - virtual void GetOriginsForTypeOnFileTaskRunner( - FileSystemType type, - std::set<GURL>* origins) OVERRIDE; - virtual void GetOriginsForHostOnFileTaskRunner( - FileSystemType type, - const std::string& host, - std::set<GURL>* origins) OVERRIDE; - virtual int64 GetOriginUsageOnFileTaskRunner( - FileSystemContext* context, - const GURL& origin_url, - FileSystemType type) OVERRIDE; - virtual scoped_refptr<QuotaReservation> - CreateQuotaReservationOnFileTaskRunner( - const GURL& origin_url, - FileSystemType type) OVERRIDE; - virtual void AddFileUpdateObserver( - FileSystemType type, - FileUpdateObserver* observer, - base::SequencedTaskRunner* task_runner) OVERRIDE; - virtual void AddFileChangeObserver( - FileSystemType type, - FileChangeObserver* observer, - base::SequencedTaskRunner* task_runner) OVERRIDE; - virtual void AddFileAccessObserver( - FileSystemType type, - FileAccessObserver* observer, - base::SequencedTaskRunner* task_runner) OVERRIDE; - virtual const UpdateObserverList* GetUpdateObservers( - FileSystemType type) const OVERRIDE; - virtual const ChangeObserverList* GetChangeObservers( - FileSystemType type) const OVERRIDE; - virtual const AccessObserverList* GetAccessObservers( - FileSystemType type) const OVERRIDE; - - private: - friend class content::PluginPrivateFileSystemBackendTest; - - ObfuscatedFileUtil* obfuscated_file_util(); - const base::FilePath& base_path() const { return base_path_; } - - scoped_refptr<base::SequencedTaskRunner> file_task_runner_; - const FileSystemOptions file_system_options_; - const base::FilePath base_path_; - scoped_ptr<AsyncFileUtil> file_util_; - FileSystemIDToPluginMap* plugin_map_; // Owned by file_util_. - base::WeakPtrFactory<PluginPrivateFileSystemBackend> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(PluginPrivateFileSystemBackend); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_PLUGIN_PRIVATE_FILE_SYSTEM_BACKEND_H_ +#include "storage/browser/fileapi/plugin_private_file_system_backend.h" diff --git a/webkit/browser/fileapi/quota/open_file_handle.h b/webkit/browser/fileapi/quota/open_file_handle.h index d54c033..361b86e 100644 --- a/webkit/browser/fileapi/quota/open_file_handle.h +++ b/webkit/browser/fileapi/quota/open_file_handle.h @@ -1,70 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_QUOTA_OPEN_FILE_HANDLE_H_ -#define WEBKIT_BROWSER_FILEAPI_QUOTA_OPEN_FILE_HANDLE_H_ - -#include "base/basictypes.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class FilePath; -} - -namespace storage { - -class QuotaReservation; -class OpenFileHandleContext; -class QuotaReservationBuffer; - -// Represents an open file like a file descriptor. -// This should be alive while a consumer keeps a file opened and should be -// deleted when the plugin closes the file. -class STORAGE_EXPORT OpenFileHandle { - public: - ~OpenFileHandle(); - - // Updates cached file size and consumes quota for that. - // Both this and AddAppendModeWriteAmount should be called for each modified - // file before calling QuotaReservation::RefreshQuota and before closing the - // file. - void UpdateMaxWrittenOffset(int64 offset); - - // Notifies that |amount| of data is written to the file in append mode, and - // consumes quota for that. - // Both this and UpdateMaxWrittenOffset should be called for each modified - // file before calling QuotaReservation::RefreshQuota and before closing the - // file. - void AddAppendModeWriteAmount(int64 amount); - - // Returns the estimated file size for the quota consumption calculation. - // The client must consume its reserved quota when it writes data to the file - // beyond the estimated file size. - // The estimated file size is greater than or equal to actual file size after - // all clients report their file usage, and is monotonically increasing over - // OpenFileHandle object life cycle, so that client may cache the value. - int64 GetEstimatedFileSize() const; - - int64 GetMaxWrittenOffset() const; - const base::FilePath& platform_path() const; - - private: - friend class QuotaReservationBuffer; - - OpenFileHandle(QuotaReservation* reservation, - OpenFileHandleContext* context); - - scoped_refptr<QuotaReservation> reservation_; - scoped_refptr<OpenFileHandleContext> context_; - - base::SequenceChecker sequence_checker_; - - DISALLOW_COPY_AND_ASSIGN(OpenFileHandle); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_QUOTA_OPEN_FILE_HANDLE_H_ +#include "storage/browser/fileapi/quota/open_file_handle.h" diff --git a/webkit/browser/fileapi/quota/open_file_handle_context.h b/webkit/browser/fileapi/quota/open_file_handle_context.h index 86ecab2..f6543cd 100644 --- a/webkit/browser/fileapi/quota/open_file_handle_context.h +++ b/webkit/browser/fileapi/quota/open_file_handle_context.h @@ -1,61 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_OPEN_FILE_HANDLE_CONTEXT_H_ -#define WEBKIT_BROWSER_FILEAPI_OPEN_FILE_HANDLE_CONTEXT_H_ - -#include <map> - -#include "base/basictypes.h" -#include "base/files/file_path.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "url/gurl.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/fileapi/file_system_types.h" - -namespace storage { - -class QuotaReservationBuffer; - -// This class represents a underlying file of a managed FileSystem file. -// The instance keeps alive while at least one consumer keeps an open file -// handle. -// This class is usually manipulated only via OpenFileHandle. -class OpenFileHandleContext : public base::RefCounted<OpenFileHandleContext> { - public: - OpenFileHandleContext(const base::FilePath& platform_path, - QuotaReservationBuffer* reservation_buffer); - - // Updates the max written offset and returns the amount of growth. - int64 UpdateMaxWrittenOffset(int64 offset); - - void AddAppendModeWriteAmount(int64 amount); - - const base::FilePath& platform_path() const { - return platform_path_; - } - - int64 GetEstimatedFileSize() const; - int64 GetMaxWrittenOffset() const; - - private: - friend class base::RefCounted<OpenFileHandleContext>; - virtual ~OpenFileHandleContext(); - - int64 initial_file_size_; - int64 maximum_written_offset_; - int64 append_mode_write_amount_; - base::FilePath platform_path_; - - scoped_refptr<QuotaReservationBuffer> reservation_buffer_; - - base::SequenceChecker sequence_checker_; - - DISALLOW_COPY_AND_ASSIGN(OpenFileHandleContext); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_OPEN_FILE_HANDLE_CONTEXT_H_ +#include "storage/browser/fileapi/quota/open_file_handle_context.h" diff --git a/webkit/browser/fileapi/quota/quota_backend_impl.h b/webkit/browser/fileapi/quota/quota_backend_impl.h index 033a61a..b6a153e 100644 --- a/webkit/browser/fileapi/quota/quota_backend_impl.h +++ b/webkit/browser/fileapi/quota/quota_backend_impl.h @@ -1,106 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_QUOTA_QUOTA_BACKEND_IMPL_H_ -#define WEBKIT_BROWSER_FILEAPI_QUOTA_QUOTA_BACKEND_IMPL_H_ - -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "webkit/browser/fileapi/quota/quota_reservation_manager.h" -#include "webkit/browser/fileapi/sandbox_file_system_backend_delegate.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/quota/quota_status_code.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace content { -class QuotaBackendImplTest; -} - -namespace storage { -class QuotaManagerProxy; -} - -namespace storage { - -class FileSystemUsageCache; -class ObfuscatedFileUtil; - -// An instance of this class is owned by QuotaReservationManager. -class STORAGE_EXPORT QuotaBackendImpl - : public QuotaReservationManager::QuotaBackend { - public: - typedef QuotaReservationManager::ReserveQuotaCallback - ReserveQuotaCallback; - - QuotaBackendImpl(base::SequencedTaskRunner* file_task_runner, - ObfuscatedFileUtil* obfuscated_file_util, - FileSystemUsageCache* file_system_usage_cache, - storage::QuotaManagerProxy* quota_manager_proxy); - virtual ~QuotaBackendImpl(); - - // QuotaReservationManager::QuotaBackend overrides. - virtual void ReserveQuota( - const GURL& origin, - FileSystemType type, - int64 delta, - const ReserveQuotaCallback& callback) OVERRIDE; - virtual void ReleaseReservedQuota( - const GURL& origin, - FileSystemType type, - int64 size) OVERRIDE; - virtual void CommitQuotaUsage( - const GURL& origin, - FileSystemType type, - int64 delta) OVERRIDE; - virtual void IncrementDirtyCount( - const GURL& origin, - FileSystemType type) OVERRIDE; - virtual void DecrementDirtyCount( - const GURL& origin, - FileSystemType type) OVERRIDE; - - private: - friend class content::QuotaBackendImplTest; - - struct QuotaReservationInfo { - QuotaReservationInfo(const GURL& origin, FileSystemType type, int64 delta); - ~QuotaReservationInfo(); - - GURL origin; - FileSystemType type; - int64 delta; - }; - - void DidGetUsageAndQuotaForReserveQuota(const QuotaReservationInfo& info, - const ReserveQuotaCallback& callback, - storage::QuotaStatusCode status, - int64 usage, - int64 quota); - - void ReserveQuotaInternal( - const QuotaReservationInfo& info); - base::File::Error GetUsageCachePath( - const GURL& origin, - FileSystemType type, - base::FilePath* usage_file_path); - - scoped_refptr<base::SequencedTaskRunner> file_task_runner_; - - // Owned by SandboxFileSystemBackendDelegate. - ObfuscatedFileUtil* obfuscated_file_util_; - FileSystemUsageCache* file_system_usage_cache_; - - scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy_; - - base::WeakPtrFactory<QuotaBackendImpl> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(QuotaBackendImpl); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_QUOTA_QUOTA_BACKEND_IMPL_H_ +#include "storage/browser/fileapi/quota/quota_backend_impl.h" diff --git a/webkit/browser/fileapi/quota/quota_reservation.h b/webkit/browser/fileapi/quota/quota_reservation.h index edde151..f44071c 100644 --- a/webkit/browser/fileapi/quota/quota_reservation.h +++ b/webkit/browser/fileapi/quota/quota_reservation.h @@ -1,95 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_H_ -#define WEBKIT_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_H_ - -#include "base/basictypes.h" -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "webkit/browser/fileapi/quota/quota_reservation_manager.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/fileapi/file_system_types.h" - -class GURL; - -namespace storage { - -class QuotaReservationBuffer; -class OpenFileHandle; - -// Represents a unit of quota reservation. -class STORAGE_EXPORT QuotaReservation - : public base::RefCounted<QuotaReservation> { - public: - typedef base::Callback<void(base::File::Error error)> StatusCallback; - - // Reclaims unused quota and reserves another |size| of quota. So that the - // resulting new |remaining_quota_| will be same as |size| as far as available - // space is enough. |remaining_quota_| may be less than |size| if there is - // not enough space available. - // Invokes |callback| upon completion. - void RefreshReservation(int64 size, const StatusCallback& callback); - - // Associates |platform_path| to the QuotaReservation instance. - // Returns an OpenFileHandle instance that represents a quota managed file. - scoped_ptr<OpenFileHandle> GetOpenFileHandle( - const base::FilePath& platform_path); - - // Should be called when the associated client is crashed. - // This implies the client can no longer report its consumption of the - // reserved quota. - // QuotaReservation puts all remaining quota to the QuotaReservationBuffer, so - // that the remaining quota will be reclaimed after all open files associated - // to the origin and type. - void OnClientCrash(); - - // Consumes |size| of reserved quota for a associated file. - // Consumed quota is sent to associated QuotaReservationBuffer for staging. - void ConsumeReservation(int64 size); - - // Returns amount of unused reserved quota. - int64 remaining_quota() const { return remaining_quota_; } - - QuotaReservationManager* reservation_manager(); - const GURL& origin() const; - FileSystemType type() const; - - private: - friend class QuotaReservationBuffer; - - // Use QuotaReservationManager as the entry point. - explicit QuotaReservation(QuotaReservationBuffer* reservation_buffer); - - friend class base::RefCounted<QuotaReservation>; - virtual ~QuotaReservation(); - - static bool AdaptDidUpdateReservedQuota( - const base::WeakPtr<QuotaReservation>& reservation, - int64 previous_size, - const StatusCallback& callback, - base::File::Error error, - int64 delta); - bool DidUpdateReservedQuota(int64 previous_size, - const StatusCallback& callback, - base::File::Error error, - int64 delta); - - bool client_crashed_; - bool running_refresh_request_; - int64 remaining_quota_; - - scoped_refptr<QuotaReservationBuffer> reservation_buffer_; - - base::SequenceChecker sequence_checker_; - base::WeakPtrFactory<QuotaReservation> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(QuotaReservation); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_H_ +#include "storage/browser/fileapi/quota/quota_reservation.h" diff --git a/webkit/browser/fileapi/quota/quota_reservation_buffer.h b/webkit/browser/fileapi/quota/quota_reservation_buffer.h index 89b6e22..e7fe3f0 100644 --- a/webkit/browser/fileapi/quota/quota_reservation_buffer.h +++ b/webkit/browser/fileapi/quota/quota_reservation_buffer.h @@ -1,87 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_BUFFER_H_ -#define WEBKIT_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_BUFFER_H_ - -#include <map> - -#include "base/basictypes.h" -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "url/gurl.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/fileapi/file_system_types.h" - -namespace storage { - -class QuotaReservation; -class OpenFileHandle; -class OpenFileHandleContext; -class QuotaReservationManager; - -// QuotaReservationBuffer manages QuotaReservation instances. All consumed -// quota and leaked quota by associated QuotaReservation will be staged in -// QuotaReservationBuffer, and will be committed on a modified file is closed. -// The instance keeps alive while any associated QuotaReservation or -// OpenFileHandle alive. -// This class is usually manipulated only via OpenFileHandle and -// QuotaReservation. -class QuotaReservationBuffer : public base::RefCounted<QuotaReservationBuffer> { - public: - QuotaReservationBuffer( - base::WeakPtr<QuotaReservationManager> reservation_manager, - const GURL& origin, - FileSystemType type); - - scoped_refptr<QuotaReservation> CreateReservation(); - scoped_ptr<OpenFileHandle> GetOpenFileHandle( - QuotaReservation* reservation, - const base::FilePath& platform_path); - void CommitFileGrowth(int64 quota_consumption, int64 usage_delta); - void DetachOpenFileHandleContext(OpenFileHandleContext* context); - void PutReservationToBuffer(int64 size); - - QuotaReservationManager* reservation_manager() { - return reservation_manager_.get(); - } - - const GURL& origin() const { return origin_; } - FileSystemType type() const { return type_; } - - private: - friend class base::RefCounted<QuotaReservationBuffer>; - virtual ~QuotaReservationBuffer(); - - static bool DecrementDirtyCount( - base::WeakPtr<QuotaReservationManager> reservation_manager, - const GURL& origin, - FileSystemType type, - base::File::Error error, - int64 delta); - - typedef std::map<base::FilePath, OpenFileHandleContext*> - OpenFileHandleContextByPath; - - // Not owned. The destructor of OpenFileHandler should erase itself from - // |open_files_|. - OpenFileHandleContextByPath open_files_; - - base::WeakPtr<QuotaReservationManager> reservation_manager_; - - GURL origin_; - storage::FileSystemType type_; - - int64 reserved_quota_; - - base::SequenceChecker sequence_checker_; - - DISALLOW_COPY_AND_ASSIGN(QuotaReservationBuffer); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_BUFFER_H_ +#include "storage/browser/fileapi/quota/quota_reservation_buffer.h" diff --git a/webkit/browser/fileapi/quota/quota_reservation_manager.h b/webkit/browser/fileapi/quota/quota_reservation_manager.h index 30e1801..cf2a126 100644 --- a/webkit/browser/fileapi/quota/quota_reservation_manager.h +++ b/webkit/browser/fileapi/quota/quota_reservation_manager.h @@ -1,127 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_MANAGER_H_ -#define WEBKIT_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_MANAGER_H_ - -#include <map> -#include <utility> - -#include "base/basictypes.h" -#include "base/callback_forward.h" -#include "base/files/file.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "url/gurl.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/fileapi/file_system_types.h" - -namespace content { -class QuotaReservationManagerTest; -} - -namespace storage { - -class QuotaReservation; -class QuotaReservationBuffer; -class OpenFileHandle; -class OpenFileHandleContext; - -class STORAGE_EXPORT QuotaReservationManager { - public: - // Callback for ReserveQuota. When this callback returns false, ReserveQuota - // operation should be reverted. - typedef base::Callback<bool(base::File::Error error, int64 delta)> - ReserveQuotaCallback; - - // An abstraction of backing quota system. - class STORAGE_EXPORT QuotaBackend { - public: - QuotaBackend() {} - virtual ~QuotaBackend() {} - - // Reserves or reclaims |delta| of quota for |origin| and |type| pair. - // Reserved quota should be counted as usage, but it should be on-memory - // and be cleared by a browser restart. - // Invokes |callback| upon completion with an error code. - // |callback| should return false if it can't accept the reservation, in - // that case, the backend should roll back the reservation. - virtual void ReserveQuota(const GURL& origin, - FileSystemType type, - int64 delta, - const ReserveQuotaCallback& callback) = 0; - - // Reclaims |size| of quota for |origin| and |type|. - virtual void ReleaseReservedQuota(const GURL& origin, - FileSystemType type, - int64 size) = 0; - - // Updates disk usage of |origin| and |type|. - // Invokes |callback| upon completion with an error code. - virtual void CommitQuotaUsage(const GURL& origin, - FileSystemType type, - int64 delta) = 0; - - virtual void IncrementDirtyCount(const GURL& origin, - FileSystemType type) = 0; - virtual void DecrementDirtyCount(const GURL& origin, - FileSystemType type) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(QuotaBackend); - }; - - explicit QuotaReservationManager(scoped_ptr<QuotaBackend> backend); - ~QuotaReservationManager(); - - // The entry point of the quota reservation. Creates new reservation object - // for |origin| and |type|. - scoped_refptr<QuotaReservation> CreateReservation( - const GURL& origin, - FileSystemType type); - - private: - typedef std::map<std::pair<GURL, FileSystemType>, QuotaReservationBuffer*> - ReservationBufferByOriginAndType; - - friend class QuotaReservation; - friend class QuotaReservationBuffer; - friend class content::QuotaReservationManagerTest; - - void ReserveQuota(const GURL& origin, - FileSystemType type, - int64 delta, - const ReserveQuotaCallback& callback); - - void ReleaseReservedQuota(const GURL& origin, - FileSystemType type, - int64 size); - - void CommitQuotaUsage(const GURL& origin, - FileSystemType type, - int64 delta); - - void IncrementDirtyCount(const GURL& origin, FileSystemType type); - void DecrementDirtyCount(const GURL& origin, FileSystemType type); - - scoped_refptr<QuotaReservationBuffer> GetReservationBuffer( - const GURL& origin, - FileSystemType type); - void ReleaseReservationBuffer(QuotaReservationBuffer* reservation_pool); - - scoped_ptr<QuotaBackend> backend_; - - // Not owned. The destructor of ReservationBuffer should erase itself from - // |reservation_buffers_| by calling ReleaseReservationBuffer. - ReservationBufferByOriginAndType reservation_buffers_; - - base::SequenceChecker sequence_checker_; - base::WeakPtrFactory<QuotaReservationManager> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(QuotaReservationManager); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_QUOTA_QUOTA_RESERVATION_MANAGER_H_ +#include "storage/browser/fileapi/quota/quota_reservation_manager.h" diff --git a/webkit/browser/fileapi/recursive_operation_delegate.h b/webkit/browser/fileapi/recursive_operation_delegate.h index 6386632..b1fbd66 100644 --- a/webkit/browser/fileapi/recursive_operation_delegate.h +++ b/webkit/browser/fileapi/recursive_operation_delegate.h @@ -1,152 +1,5 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_RECURSIVE_OPERATION_DELEGATE_H_ -#define WEBKIT_BROWSER_FILEAPI_RECURSIVE_OPERATION_DELEGATE_H_ - -#include <queue> -#include <stack> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/memory/weak_ptr.h" -#include "webkit/browser/fileapi/file_system_operation.h" -#include "webkit/browser/fileapi/file_system_url.h" - -namespace storage { - -class FileSystemContext; -class FileSystemOperationRunner; - -// A base class for recursive operation delegates. -// -// In short, each subclass should override ProcessFile and ProcessDirectory -// to process a directory or a file. To start the recursive operation it -// should also call StartRecursiveOperation. -class STORAGE_EXPORT RecursiveOperationDelegate - : public base::SupportsWeakPtr<RecursiveOperationDelegate> { - public: - typedef FileSystemOperation::StatusCallback StatusCallback; - typedef FileSystemOperation::FileEntryList FileEntryList; - - virtual ~RecursiveOperationDelegate(); - - // This is called when the consumer of this instance starts a non-recursive - // operation. - virtual void Run() = 0; - - // This is called when the consumer of this instance starts a recursive - // operation. - virtual void RunRecursively() = 0; - - // This is called each time a file is found while recursively - // performing an operation. - virtual void ProcessFile(const FileSystemURL& url, - const StatusCallback& callback) = 0; - - // This is called each time a directory is found while recursively - // performing an operation. - virtual void ProcessDirectory(const FileSystemURL& url, - const StatusCallback& callback) = 0; - - - // This is called each time after files and subdirectories for a - // directory is processed while recursively performing an operation. - virtual void PostProcessDirectory(const FileSystemURL& url, - const StatusCallback& callback) = 0; - - // Cancels the currently running operation. - void Cancel(); - - protected: - explicit RecursiveOperationDelegate(FileSystemContext* file_system_context); - - // Starts to process files/directories recursively from the given |root|. - // This will call ProcessFile and ProcessDirectory on each file or directory. - // - // First, this tries to call ProcessFile with |root| regardless whether it is - // actually a file or a directory. If it is a directory, ProcessFile should - // return File::FILE_NOT_A_FILE. - // - // For each directory, the recursive operation works as follows: - // ProcessDirectory is called first for the directory. - // Then the directory contents are read (to obtain its sub directories and - // files in it). - // ProcessFile is called for found files. This may run in parallel. - // The same step is recursively applied to each subdirectory. - // After all files and subdirectories in a directory are processed, - // PostProcessDirectory is called for the directory. - // Here is an example; - // a_dir/ -+- b1_dir/ -+- c1_dir/ -+- d1_file - // | | | - // | +- c2_file +- d2_file - // | - // +- b2_dir/ --- e_dir/ - // | - // +- b3_file - // | - // +- b4_file - // Then traverse order is: - // ProcessFile(a_dir) (This should return File::FILE_NOT_A_FILE). - // ProcessDirectory(a_dir). - // ProcessFile(b3_file), ProcessFile(b4_file). (in parallel). - // ProcessDirectory(b1_dir). - // ProcessFile(c2_file) - // ProcessDirectory(c1_dir). - // ProcessFile(d1_file), ProcessFile(d2_file). (in parallel). - // PostProcessDirectory(c1_dir) - // PostProcessDirectory(b1_dir). - // ProcessDirectory(b2_dir) - // ProcessDirectory(e_dir) - // PostProcessDirectory(e_dir) - // PostProcessDirectory(b2_dir) - // PostProcessDirectory(a_dir) - // - // |callback| is fired with base::File::FILE_OK when every file/directory - // under |root| is processed, or fired earlier when any suboperation fails. - void StartRecursiveOperation(const FileSystemURL& root, - const StatusCallback& callback); - - FileSystemContext* file_system_context() { return file_system_context_; } - const FileSystemContext* file_system_context() const { - return file_system_context_; - } - - FileSystemOperationRunner* operation_runner(); - - // Called when Cancel() is called. This is a hook to do something more - // in a derived class. By default, do nothing. - virtual void OnCancel(); - - private: - void DidTryProcessFile(const FileSystemURL& root, - base::File::Error error); - void ProcessNextDirectory(); - void DidProcessDirectory(base::File::Error error); - void DidReadDirectory(const FileSystemURL& parent, - base::File::Error error, - const FileEntryList& entries, - bool has_more); - void ProcessPendingFiles(); - void DidProcessFile(base::File::Error error); - void ProcessSubDirectory(); - void DidPostProcessDirectory(base::File::Error error); - - // Called when all recursive operation is done (or an error occurs). - void Done(base::File::Error error); - - FileSystemContext* file_system_context_; - StatusCallback callback_; - std::stack<FileSystemURL> pending_directories_; - std::stack<std::queue<FileSystemURL> > pending_directory_stack_; - std::queue<FileSystemURL> pending_files_; - int inflight_operations_; - bool canceled_; - - DISALLOW_COPY_AND_ASSIGN(RecursiveOperationDelegate); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_RECURSIVE_OPERATION_DELEGATE_H_ +#include "storage/browser/fileapi/recursive_operation_delegate.h" diff --git a/webkit/browser/fileapi/remove_operation_delegate.h b/webkit/browser/fileapi/remove_operation_delegate.h index 57380a3..2a7bea3 100644 --- a/webkit/browser/fileapi/remove_operation_delegate.h +++ b/webkit/browser/fileapi/remove_operation_delegate.h @@ -1,46 +1,5 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_REMOVE_OPERATION_DELEGATE_H_ -#define WEBKIT_BROWSER_FILEAPI_REMOVE_OPERATION_DELEGATE_H_ - -#include <stack> - -#include "webkit/browser/fileapi/recursive_operation_delegate.h" - -namespace storage { - -class RemoveOperationDelegate : public RecursiveOperationDelegate { - public: - RemoveOperationDelegate(FileSystemContext* file_system_context, - const FileSystemURL& url, - const StatusCallback& callback); - virtual ~RemoveOperationDelegate(); - - // RecursiveOperationDelegate overrides: - virtual void Run() OVERRIDE; - virtual void RunRecursively() OVERRIDE; - virtual void ProcessFile(const FileSystemURL& url, - const StatusCallback& callback) OVERRIDE; - virtual void ProcessDirectory(const FileSystemURL& url, - const StatusCallback& callback) OVERRIDE; - virtual void PostProcessDirectory(const FileSystemURL& url, - const StatusCallback& callback) OVERRIDE; - - private: - void DidTryRemoveFile(base::File::Error error); - void DidTryRemoveDirectory(base::File::Error remove_file_error, - base::File::Error remove_directory_error); - void DidRemoveFile(const StatusCallback& callback, - base::File::Error error); - - FileSystemURL url_; - StatusCallback callback_; - base::WeakPtrFactory<RemoveOperationDelegate> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(RemoveOperationDelegate); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_REMOVE_OPERATION_DELEGATE_H_ +#include "storage/browser/fileapi/remove_operation_delegate.h" diff --git a/webkit/browser/fileapi/sandbox_directory_database.h b/webkit/browser/fileapi/sandbox_directory_database.h index 7dbc166..c8452b0 100644 --- a/webkit/browser/fileapi/sandbox_directory_database.h +++ b/webkit/browser/fileapi/sandbox_directory_database.h @@ -1,135 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_SANDBOX_DIRECTORY_DATABASE_H_ -#define WEBKIT_BROWSER_FILEAPI_SANDBOX_DIRECTORY_DATABASE_H_ - -#include <string> -#include <vector> - -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" -#include "base/time/time.h" -#include "webkit/browser/storage_browser_export.h" - -namespace content { -class SandboxDirectoryDatabaseTest; -} - -namespace tracked_objects { -class Location; -} - -namespace leveldb { -class DB; -class Env; -class Status; -class WriteBatch; -} - -namespace storage { - -// This class WILL NOT protect you against producing directory loops, giving an -// empty directory a backing data file, giving two files the same backing file, -// or pointing to a nonexistent backing file. It does no file IO other than -// that involved with talking to its underlying database. It does not create or -// in any way touch real files; it only creates path entries in its database. - -// TODO(ericu): Safe mode, which does more checks such as the above on debug -// builds. -// TODO(ericu): Add a method that will give a unique filename for a data file. -class STORAGE_EXPORT_PRIVATE SandboxDirectoryDatabase { - public: - typedef int64 FileId; - - struct STORAGE_EXPORT_PRIVATE FileInfo { - FileInfo(); - ~FileInfo(); - - bool is_directory() const { - return data_path.empty(); - } - - FileId parent_id; - base::FilePath data_path; - base::FilePath::StringType name; - // This modification time is valid only for directories, not files, as - // FileWriter will get the files out of sync. - // For files, look at the modification time of the underlying data_path. - base::Time modification_time; - }; - - SandboxDirectoryDatabase( - const base::FilePath& filesystem_data_directory, - leveldb::Env* env_override); - ~SandboxDirectoryDatabase(); - - bool GetChildWithName( - FileId parent_id, - const base::FilePath::StringType& name, - FileId* child_id); - bool GetFileWithPath(const base::FilePath& path, FileId* file_id); - // ListChildren will succeed, returning 0 children, if parent_id doesn't - // exist. - bool ListChildren(FileId parent_id, std::vector<FileId>* children); - bool GetFileInfo(FileId file_id, FileInfo* info); - base::File::Error AddFileInfo(const FileInfo& info, FileId* file_id); - bool RemoveFileInfo(FileId file_id); - // This does a full update of the FileInfo, and is what you'd use for moves - // and renames. If you just want to update the modification_time, use - // UpdateModificationTime. - bool UpdateFileInfo(FileId file_id, const FileInfo& info); - bool UpdateModificationTime( - FileId file_id, const base::Time& modification_time); - // This is used for an overwriting move of a file [not a directory] on top of - // another file [also not a directory]; we need to alter two files' info in a - // single transaction to avoid weird backing file references in the event of a - // partial failure. - bool OverwritingMoveFile(FileId src_file_id, FileId dest_file_id); - - // This produces the series 0, 1, 2..., starting at 0 when the underlying - // filesystem is first created, and maintaining state across - // creation/destruction of SandboxDirectoryDatabase objects. - bool GetNextInteger(int64* next); - - bool IsDirectory(FileId file_id); - - // Returns true if the database looks consistent with local filesystem. - bool IsFileSystemConsistent(); - - static bool DestroyDatabase(const base::FilePath& path, - leveldb::Env* env_override); - - private: - enum RecoveryOption { - DELETE_ON_CORRUPTION, - REPAIR_ON_CORRUPTION, - FAIL_ON_CORRUPTION, - }; - - friend class content::SandboxDirectoryDatabaseTest; - friend class ObfuscatedFileUtil; - - bool Init(RecoveryOption recovery_option); - bool RepairDatabase(const std::string& db_path); - void ReportInitStatus(const leveldb::Status& status); - bool StoreDefaultValues(); - bool GetLastFileId(FileId* file_id); - bool AddFileInfoHelper( - const FileInfo& info, FileId file_id, leveldb::WriteBatch* batch); - bool RemoveFileInfoHelper(FileId file_id, leveldb::WriteBatch* batch); - void HandleError(const tracked_objects::Location& from_here, - const leveldb::Status& status); - - const base::FilePath filesystem_data_directory_; - leveldb::Env* env_override_; - scoped_ptr<leveldb::DB> db_; - base::Time last_reported_time_; - DISALLOW_COPY_AND_ASSIGN(SandboxDirectoryDatabase); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_SANDBOX_DIRECTORY_DATABASE_H_ +#include "storage/browser/fileapi/sandbox_directory_database.h" diff --git a/webkit/browser/fileapi/sandbox_file_stream_writer.h b/webkit/browser/fileapi/sandbox_file_stream_writer.h index e900c56..6b9ed33 100644 --- a/webkit/browser/fileapi/sandbox_file_stream_writer.h +++ b/webkit/browser/fileapi/sandbox_file_stream_writer.h @@ -1,96 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_SANDBOX_FILE_STREAM_WRITER_H_ -#define WEBKIT_BROWSER_FILEAPI_SANDBOX_FILE_STREAM_WRITER_H_ - -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" -#include "url/gurl.h" -#include "webkit/browser/fileapi/file_stream_writer.h" -#include "webkit/browser/fileapi/file_system_url.h" -#include "webkit/browser/fileapi/task_runner_bound_observer_list.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/blob/shareable_file_reference.h" -#include "webkit/common/fileapi/file_system_types.h" -#include "webkit/common/quota/quota_types.h" - -namespace storage { - -class FileSystemContext; -class FileSystemQuotaUtil; -class FileStreamWriter; - -class STORAGE_EXPORT_PRIVATE SandboxFileStreamWriter - : public NON_EXPORTED_BASE(FileStreamWriter) { - public: - SandboxFileStreamWriter(FileSystemContext* file_system_context, - const FileSystemURL& url, - int64 initial_offset, - const UpdateObserverList& observers); - virtual ~SandboxFileStreamWriter(); - - // FileStreamWriter overrides. - virtual int Write(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) OVERRIDE; - virtual int Cancel(const net::CompletionCallback& callback) OVERRIDE; - virtual int Flush(const net::CompletionCallback& callback) OVERRIDE; - - // Used only by tests. - void set_default_quota(int64 quota) { - default_quota_ = quota; - } - - private: - // Performs quota calculation and calls local_file_writer_->Write(). - int WriteInternal(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback); - - // Callbacks that are chained for the first write. This eventually calls - // WriteInternal. - void DidCreateSnapshotFile( - const net::CompletionCallback& callback, - base::File::Error file_error, - const base::File::Info& file_info, - const base::FilePath& platform_path, - const scoped_refptr<storage::ShareableFileReference>& file_ref); - void DidGetUsageAndQuota(const net::CompletionCallback& callback, - storage::QuotaStatusCode status, - int64 usage, - int64 quota); - void DidInitializeForWrite(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback, - int init_status); - - void DidWrite(const net::CompletionCallback& callback, int write_response); - - // Stops the in-flight operation, calls |cancel_callback_| and returns true - // if there's a pending cancel request. - bool CancelIfRequested(); - - scoped_refptr<FileSystemContext> file_system_context_; - FileSystemURL url_; - int64 initial_offset_; - scoped_ptr<FileStreamWriter> local_file_writer_; - net::CompletionCallback cancel_callback_; - - UpdateObserverList observers_; - - base::FilePath file_path_; - int64 file_size_; - int64 total_bytes_written_; - int64 allowed_bytes_to_write_; - bool has_pending_operation_; - - int64 default_quota_; - - base::WeakPtrFactory<SandboxFileStreamWriter> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(SandboxFileStreamWriter); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_SANDBOX_FILE_STREAM_WRITER_H_ +#include "storage/browser/fileapi/sandbox_file_stream_writer.h" diff --git a/webkit/browser/fileapi/sandbox_file_system_backend.h b/webkit/browser/fileapi/sandbox_file_system_backend.h index 3ab200c..fcbe680 100644 --- a/webkit/browser/fileapi/sandbox_file_system_backend.h +++ b/webkit/browser/fileapi/sandbox_file_system_backend.h @@ -1,85 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_SANDBOX_FILE_SYSTEM_BACKEND_H_ -#define WEBKIT_BROWSER_FILEAPI_SANDBOX_FILE_SYSTEM_BACKEND_H_ - -#include <set> -#include <string> - -#include "base/compiler_specific.h" -#include "base/files/file_path.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "webkit/browser/fileapi/file_system_backend.h" -#include "webkit/browser/fileapi/file_system_quota_util.h" -#include "webkit/browser/fileapi/sandbox_file_system_backend_delegate.h" -#include "webkit/browser/fileapi/task_runner_bound_observer_list.h" -#include "webkit/browser/quota/special_storage_policy.h" -#include "webkit/browser/storage_browser_export.h" - -namespace storage { - -// TEMPORARY or PERSISTENT filesystems, which are placed under the user's -// profile directory in a sandboxed way. -// This interface also lets one enumerate and remove storage for the origins -// that use the filesystem. -class STORAGE_EXPORT SandboxFileSystemBackend - : public FileSystemBackend { - public: - explicit SandboxFileSystemBackend(SandboxFileSystemBackendDelegate* delegate); - virtual ~SandboxFileSystemBackend(); - - // FileSystemBackend overrides. - virtual bool CanHandleType(FileSystemType type) const OVERRIDE; - virtual void Initialize(FileSystemContext* context) OVERRIDE; - virtual void ResolveURL(const FileSystemURL& url, - OpenFileSystemMode mode, - const OpenFileSystemCallback& callback) OVERRIDE; - virtual AsyncFileUtil* GetAsyncFileUtil(FileSystemType type) OVERRIDE; - virtual WatcherManager* GetWatcherManager(FileSystemType type) OVERRIDE; - virtual CopyOrMoveFileValidatorFactory* GetCopyOrMoveFileValidatorFactory( - FileSystemType type, - base::File::Error* error_code) OVERRIDE; - virtual FileSystemOperation* CreateFileSystemOperation( - const FileSystemURL& url, - FileSystemContext* context, - base::File::Error* error_code) const OVERRIDE; - virtual bool SupportsStreaming(const FileSystemURL& url) const OVERRIDE; - virtual bool HasInplaceCopyImplementation( - storage::FileSystemType type) const OVERRIDE; - virtual scoped_ptr<storage::FileStreamReader> CreateFileStreamReader( - const FileSystemURL& url, - int64 offset, - const base::Time& expected_modification_time, - FileSystemContext* context) const OVERRIDE; - virtual scoped_ptr<FileStreamWriter> CreateFileStreamWriter( - const FileSystemURL& url, - int64 offset, - FileSystemContext* context) const OVERRIDE; - virtual FileSystemQuotaUtil* GetQuotaUtil() OVERRIDE; - - // Returns an origin enumerator of this backend. - // This method can only be called on the file thread. - SandboxFileSystemBackendDelegate::OriginEnumerator* CreateOriginEnumerator(); - - void set_enable_temporary_file_system_in_incognito(bool enable) { - enable_temporary_file_system_in_incognito_ = enable; - } - bool enable_temporary_file_system_in_incognito() const { - return enable_temporary_file_system_in_incognito_; - } - - - private: - SandboxFileSystemBackendDelegate* delegate_; // Not owned. - - bool enable_temporary_file_system_in_incognito_; - - DISALLOW_COPY_AND_ASSIGN(SandboxFileSystemBackend); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_SANDBOX_FILE_SYSTEM_BACKEND_H_ +#include "storage/browser/fileapi/sandbox_file_system_backend.h" diff --git a/webkit/browser/fileapi/sandbox_file_system_backend_delegate.h b/webkit/browser/fileapi/sandbox_file_system_backend_delegate.h index c0ce39e..cc883dc 100644 --- a/webkit/browser/fileapi/sandbox_file_system_backend_delegate.h +++ b/webkit/browser/fileapi/sandbox_file_system_backend_delegate.h @@ -1,260 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_SANDBOX_FILE_SYSTEM_BACKEND_DELEGATE_H_ -#define WEBKIT_BROWSER_FILEAPI_SANDBOX_FILE_SYSTEM_BACKEND_DELEGATE_H_ - -#include <map> -#include <set> -#include <string> -#include <utility> - -#include "base/files/file_path.h" -#include "base/gtest_prod_util.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/threading/thread_checker.h" -#include "base/time/time.h" -#include "webkit/browser/fileapi/file_system_backend.h" -#include "webkit/browser/fileapi/file_system_options.h" -#include "webkit/browser/fileapi/file_system_quota_util.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace content { -class SandboxFileSystemBackendDelegateTest; -class SandboxFileSystemTestHelper; -} - -namespace storage { -class QuotaManagerProxy; -class SpecialStoragePolicy; -} - -namespace storage { -class FileStreamReader; -} - -namespace storage { - -class AsyncFileUtil; -class FileStreamWriter; -class FileSystemFileUtil; -class FileSystemOperationContext; -class FileSystemURL; -class FileSystemUsageCache; -class ObfuscatedFileUtil; -class QuotaReservationManager; -class SandboxFileSystemBackend; -class SandboxQuotaObserver; - -// Delegate implementation of the some methods in Sandbox/SyncFileSystemBackend. -// An instance of this class is created and owned by FileSystemContext. -class STORAGE_EXPORT SandboxFileSystemBackendDelegate - : public FileSystemQuotaUtil { - public: - typedef FileSystemBackend::OpenFileSystemCallback OpenFileSystemCallback; - - // The FileSystem directory name. - static const base::FilePath::CharType kFileSystemDirectory[]; - - // Origin enumerator interface. - // An instance of this interface is assumed to be called on the file thread. - class OriginEnumerator { - public: - virtual ~OriginEnumerator() {} - - // Returns the next origin. Returns empty if there are no more origins. - virtual GURL Next() = 0; - - // Returns the current origin's information. - virtual bool HasFileSystemType(FileSystemType type) const = 0; - }; - - // Returns the type directory name in sandbox directory for given |type|. - static std::string GetTypeString(FileSystemType type); - - SandboxFileSystemBackendDelegate( - storage::QuotaManagerProxy* quota_manager_proxy, - base::SequencedTaskRunner* file_task_runner, - const base::FilePath& profile_path, - storage::SpecialStoragePolicy* special_storage_policy, - const FileSystemOptions& file_system_options); - - virtual ~SandboxFileSystemBackendDelegate(); - - // Returns an origin enumerator of sandbox filesystem. - // This method can only be called on the file thread. - OriginEnumerator* CreateOriginEnumerator(); - - // Gets a base directory path of the sandboxed filesystem that is - // specified by |origin_url| and |type|. - // (The path is similar to the origin's root path but doesn't contain - // the 'unique' part.) - // Returns an empty path if the given type is invalid. - // This method can only be called on the file thread. - base::FilePath GetBaseDirectoryForOriginAndType( - const GURL& origin_url, - FileSystemType type, - bool create); - - // FileSystemBackend helpers. - void OpenFileSystem( - const GURL& origin_url, - FileSystemType type, - OpenFileSystemMode mode, - const OpenFileSystemCallback& callback, - const GURL& root_url); - scoped_ptr<FileSystemOperationContext> CreateFileSystemOperationContext( - const FileSystemURL& url, - FileSystemContext* context, - base::File::Error* error_code) const; - scoped_ptr<storage::FileStreamReader> CreateFileStreamReader( - const FileSystemURL& url, - int64 offset, - const base::Time& expected_modification_time, - FileSystemContext* context) const; - scoped_ptr<FileStreamWriter> CreateFileStreamWriter( - const FileSystemURL& url, - int64 offset, - FileSystemContext* context, - FileSystemType type) const; - - // FileSystemQuotaUtil overrides. - virtual base::File::Error DeleteOriginDataOnFileTaskRunner( - FileSystemContext* context, - storage::QuotaManagerProxy* proxy, - const GURL& origin_url, - FileSystemType type) OVERRIDE; - virtual void GetOriginsForTypeOnFileTaskRunner( - FileSystemType type, - std::set<GURL>* origins) OVERRIDE; - virtual void GetOriginsForHostOnFileTaskRunner( - FileSystemType type, - const std::string& host, - std::set<GURL>* origins) OVERRIDE; - virtual int64 GetOriginUsageOnFileTaskRunner( - FileSystemContext* context, - const GURL& origin_url, - FileSystemType type) OVERRIDE; - virtual scoped_refptr<QuotaReservation> - CreateQuotaReservationOnFileTaskRunner( - const GURL& origin_url, - FileSystemType type) OVERRIDE; - virtual void AddFileUpdateObserver( - FileSystemType type, - FileUpdateObserver* observer, - base::SequencedTaskRunner* task_runner) OVERRIDE; - virtual void AddFileChangeObserver( - FileSystemType type, - FileChangeObserver* observer, - base::SequencedTaskRunner* task_runner) OVERRIDE; - virtual void AddFileAccessObserver( - FileSystemType type, - FileAccessObserver* observer, - base::SequencedTaskRunner* task_runner) OVERRIDE; - virtual const UpdateObserverList* GetUpdateObservers( - FileSystemType type) const OVERRIDE; - virtual const ChangeObserverList* GetChangeObservers( - FileSystemType type) const OVERRIDE; - virtual const AccessObserverList* GetAccessObservers( - FileSystemType type) const OVERRIDE; - - // Registers quota observer for file updates on filesystem of |type|. - void RegisterQuotaUpdateObserver(FileSystemType type); - - void InvalidateUsageCache(const GURL& origin_url, - FileSystemType type); - void StickyInvalidateUsageCache(const GURL& origin_url, - FileSystemType type); - - void CollectOpenFileSystemMetrics(base::File::Error error_code); - - base::SequencedTaskRunner* file_task_runner() { - return file_task_runner_.get(); - } - - AsyncFileUtil* file_util() { return sandbox_file_util_.get(); } - FileSystemUsageCache* usage_cache() { return file_system_usage_cache_.get(); } - SandboxQuotaObserver* quota_observer() { return quota_observer_.get(); } - - storage::SpecialStoragePolicy* special_storage_policy() { - return special_storage_policy_.get(); - } - - const FileSystemOptions& file_system_options() const { - return file_system_options_; - } - - FileSystemFileUtil* sync_file_util(); - - private: - friend class QuotaBackendImpl; - friend class SandboxQuotaObserver; - friend class content::SandboxFileSystemBackendDelegateTest; - friend class content::SandboxFileSystemTestHelper; - - // Performs API-specific validity checks on the given path |url|. - // Returns true if access to |url| is valid in this filesystem. - bool IsAccessValid(const FileSystemURL& url) const; - - // Returns true if the given |url|'s scheme is allowed to access - // filesystem. - bool IsAllowedScheme(const GURL& url) const; - - // Returns a path to the usage cache file. - base::FilePath GetUsageCachePathForOriginAndType( - const GURL& origin_url, - FileSystemType type); - - // Returns a path to the usage cache file (static version). - static base::FilePath GetUsageCachePathForOriginAndType( - ObfuscatedFileUtil* sandbox_file_util, - const GURL& origin_url, - FileSystemType type, - base::File::Error* error_out); - - int64 RecalculateUsage(FileSystemContext* context, - const GURL& origin, - FileSystemType type); - - ObfuscatedFileUtil* obfuscated_file_util(); - - scoped_refptr<base::SequencedTaskRunner> file_task_runner_; - - scoped_ptr<AsyncFileUtil> sandbox_file_util_; - scoped_ptr<FileSystemUsageCache> file_system_usage_cache_; - scoped_ptr<SandboxQuotaObserver> quota_observer_; - scoped_ptr<QuotaReservationManager> quota_reservation_manager_; - - scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy_; - - FileSystemOptions file_system_options_; - - bool is_filesystem_opened_; - base::ThreadChecker io_thread_checker_; - - // Accessed only on the file thread. - std::set<GURL> visited_origins_; - - std::set<std::pair<GURL, FileSystemType> > sticky_dirty_origins_; - - std::map<FileSystemType, UpdateObserverList> update_observers_; - std::map<FileSystemType, ChangeObserverList> change_observers_; - std::map<FileSystemType, AccessObserverList> access_observers_; - - base::Time next_release_time_for_open_filesystem_stat_; - - base::WeakPtrFactory<SandboxFileSystemBackendDelegate> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(SandboxFileSystemBackendDelegate); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_SANDBOX_FILE_SYSTEM_BACKEND_DELEGATE_H_ +#include "storage/browser/fileapi/sandbox_file_system_backend_delegate.h" diff --git a/webkit/browser/fileapi/sandbox_isolated_origin_database.h b/webkit/browser/fileapi/sandbox_isolated_origin_database.h index 2f7b766..940abb1 100644 --- a/webkit/browser/fileapi/sandbox_isolated_origin_database.h +++ b/webkit/browser/fileapi/sandbox_isolated_origin_database.h @@ -1,61 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_SANDBOX_ISOLATED_ORIGIN_DATABASE_H_ -#define WEBKIT_BROWSER_FILEAPI_SANDBOX_ISOLATED_ORIGIN_DATABASE_H_ - -#include <string> -#include <vector> - -#include "webkit/browser/fileapi/sandbox_origin_database_interface.h" - -namespace storage { - -class SandboxOriginDatabase; - -// This origin database implementation supports only one origin -// (therefore is expected to run very fast). -class STORAGE_EXPORT_PRIVATE SandboxIsolatedOriginDatabase - : public SandboxOriginDatabaseInterface { - public: - static const base::FilePath::CharType kObsoleteOriginDirectory[]; - - // Initialize this database for |origin| which makes GetPathForOrigin return - // |origin_directory| (in |file_system_directory|). - SandboxIsolatedOriginDatabase( - const std::string& origin, - const base::FilePath& file_system_directory, - const base::FilePath& origin_directory); - virtual ~SandboxIsolatedOriginDatabase(); - - // SandboxOriginDatabaseInterface overrides. - virtual bool HasOriginPath(const std::string& origin) OVERRIDE; - virtual bool GetPathForOrigin(const std::string& origin, - base::FilePath* directory) OVERRIDE; - virtual bool RemovePathForOrigin(const std::string& origin) OVERRIDE; - virtual bool ListAllOrigins(std::vector<OriginRecord>* origins) OVERRIDE; - virtual void DropDatabase() OVERRIDE; - - // TODO(kinuko): Deprecate this after a few release cycles, e.g. around M33. - static void MigrateBackFromObsoleteOriginDatabase( - const std::string& origin, - const base::FilePath& file_system_directory, - SandboxOriginDatabase* origin_database); - - const std::string& origin() const { return origin_; } - - private: - void MigrateDatabaseIfNeeded(); - - bool migration_checked_; - const std::string origin_; - const base::FilePath file_system_directory_; - const base::FilePath origin_directory_; - - DISALLOW_COPY_AND_ASSIGN(SandboxIsolatedOriginDatabase); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_SANDBOX_ISOLATED_ORIGIN_DATABASE_H_ +#include "storage/browser/fileapi/sandbox_isolated_origin_database.h" diff --git a/webkit/browser/fileapi/sandbox_origin_database.h b/webkit/browser/fileapi/sandbox_origin_database.h index f358e14..d684a81 100644 --- a/webkit/browser/fileapi/sandbox_origin_database.h +++ b/webkit/browser/fileapi/sandbox_origin_database.h @@ -1,77 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_SANDBOX_ORIGIN_DATABASE_H_ -#define WEBKIT_BROWSER_FILEAPI_SANDBOX_ORIGIN_DATABASE_H_ - -#include <string> -#include <vector> - -#include "base/memory/scoped_ptr.h" -#include "base/time/time.h" -#include "webkit/browser/fileapi/sandbox_origin_database_interface.h" - -namespace leveldb { -class DB; -class Env; -class Status; -} - -namespace tracked_objects { -class Location; -} - -namespace storage { - -// All methods of this class other than the constructor may be used only from -// the browser's FILE thread. The constructor may be used on any thread. -class STORAGE_EXPORT_PRIVATE SandboxOriginDatabase - : public SandboxOriginDatabaseInterface { - public: - // Only one instance of SandboxOriginDatabase should exist for a given path - // at a given time. - SandboxOriginDatabase(const base::FilePath& file_system_directory, - leveldb::Env* env_override); - virtual ~SandboxOriginDatabase(); - - // SandboxOriginDatabaseInterface overrides. - virtual bool HasOriginPath(const std::string& origin) OVERRIDE; - virtual bool GetPathForOrigin(const std::string& origin, - base::FilePath* directory) OVERRIDE; - virtual bool RemovePathForOrigin(const std::string& origin) OVERRIDE; - virtual bool ListAllOrigins(std::vector<OriginRecord>* origins) OVERRIDE; - virtual void DropDatabase() OVERRIDE; - - base::FilePath GetDatabasePath() const; - void RemoveDatabase(); - - private: - enum RecoveryOption { - REPAIR_ON_CORRUPTION, - DELETE_ON_CORRUPTION, - FAIL_ON_CORRUPTION, - }; - - enum InitOption { - CREATE_IF_NONEXISTENT, - FAIL_IF_NONEXISTENT, - }; - - bool Init(InitOption init_option, RecoveryOption recovery_option); - bool RepairDatabase(const std::string& db_path); - void HandleError(const tracked_objects::Location& from_here, - const leveldb::Status& status); - void ReportInitStatus(const leveldb::Status& status); - bool GetLastPathNumber(int* number); - - base::FilePath file_system_directory_; - leveldb::Env* env_override_; - scoped_ptr<leveldb::DB> db_; - base::Time last_reported_time_; - DISALLOW_COPY_AND_ASSIGN(SandboxOriginDatabase); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_SANDBOX_ORIGIN_DATABASE_H_ +#include "storage/browser/fileapi/sandbox_origin_database.h" diff --git a/webkit/browser/fileapi/sandbox_origin_database_interface.h b/webkit/browser/fileapi/sandbox_origin_database_interface.h index 37f6f3d..64b5734 100644 --- a/webkit/browser/fileapi/sandbox_origin_database_interface.h +++ b/webkit/browser/fileapi/sandbox_origin_database_interface.h @@ -1,55 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_SANDBOX_ORIGIN_DATABASE_INTERFACE_H_ -#define WEBKIT_BROWSER_FILEAPI_SANDBOX_ORIGIN_DATABASE_INTERFACE_H_ - -#include <string> -#include <vector> - -#include "base/files/file_path.h" -#include "webkit/browser/storage_browser_export.h" - -namespace storage { - -class STORAGE_EXPORT_PRIVATE SandboxOriginDatabaseInterface { - public: - struct STORAGE_EXPORT_PRIVATE OriginRecord { - std::string origin; - base::FilePath path; - - OriginRecord(); - OriginRecord(const std::string& origin, const base::FilePath& path); - ~OriginRecord(); - }; - - virtual ~SandboxOriginDatabaseInterface() {} - - // Returns true if the origin's path is included in this database. - virtual bool HasOriginPath(const std::string& origin) = 0; - - // This will produce a unique path and add it to its database, if it's not - // already present. - virtual bool GetPathForOrigin(const std::string& origin, - base::FilePath* directory) = 0; - - // Removes the origin's path from the database. - // Returns success if the origin has been successfully removed, or - // the origin is not found. - // (This doesn't remove the actual path). - virtual bool RemovePathForOrigin(const std::string& origin) = 0; - - // Lists all origins in this database. - virtual bool ListAllOrigins(std::vector<OriginRecord>* origins) = 0; - - // This will release all database resources in use; call it to save memory. - virtual void DropDatabase() = 0; - - protected: - SandboxOriginDatabaseInterface() {} -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_SANDBOX_ORIGIN_DATABASE_INTERFACE_H_ +#include "storage/browser/fileapi/sandbox_origin_database_interface.h" diff --git a/webkit/browser/fileapi/sandbox_prioritized_origin_database.h b/webkit/browser/fileapi/sandbox_prioritized_origin_database.h index 960ad27..0a745fd 100644 --- a/webkit/browser/fileapi/sandbox_prioritized_origin_database.h +++ b/webkit/browser/fileapi/sandbox_prioritized_origin_database.h @@ -1,72 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_SANDBOX_PRIORITIZED_ORIGIN_DATABASE_H_ -#define WEBKIT_BROWSER_FILEAPI_SANDBOX_PRIORITIZED_ORIGIN_DATABASE_H_ - -#include <string> -#include <vector> - -#include "base/memory/scoped_ptr.h" -#include "webkit/browser/fileapi/sandbox_origin_database_interface.h" - -namespace leveldb { -class Env; -} - -namespace storage { - -class ObfuscatedFileUtil; -class SandboxIsolatedOriginDatabase; -class SandboxOriginDatabase; - -class STORAGE_EXPORT_PRIVATE SandboxPrioritizedOriginDatabase - : public SandboxOriginDatabaseInterface { - public: - SandboxPrioritizedOriginDatabase(const base::FilePath& file_system_directory, - leveldb::Env* env_override); - virtual ~SandboxPrioritizedOriginDatabase(); - - // Sets |origin| as primary origin in this database (e.g. may - // allow faster access). - // Returns false if this database already has a primary origin - // which is different from |origin|. - bool InitializePrimaryOrigin(const std::string& origin); - std::string GetPrimaryOrigin(); - - // SandboxOriginDatabaseInterface overrides. - virtual bool HasOriginPath(const std::string& origin) OVERRIDE; - virtual bool GetPathForOrigin(const std::string& origin, - base::FilePath* directory) OVERRIDE; - virtual bool RemovePathForOrigin(const std::string& origin) OVERRIDE; - virtual bool ListAllOrigins(std::vector<OriginRecord>* origins) OVERRIDE; - virtual void DropDatabase() OVERRIDE; - - const base::FilePath& primary_origin_file() const { - return primary_origin_file_; - } - - private: - bool MaybeLoadPrimaryOrigin(); - bool ResetPrimaryOrigin(const std::string& origin); - void MaybeMigrateDatabase(const std::string& origin); - void MaybeInitializeDatabases(bool create); - void MaybeInitializeNonPrimaryDatabase(bool create); - - // For migration. - friend class ObfuscatedFileUtil; - SandboxOriginDatabase* GetSandboxOriginDatabase(); - - const base::FilePath file_system_directory_; - leveldb::Env* env_override_; - const base::FilePath primary_origin_file_; - scoped_ptr<SandboxOriginDatabase> origin_database_; - scoped_ptr<SandboxIsolatedOriginDatabase> primary_origin_database_; - - DISALLOW_COPY_AND_ASSIGN(SandboxPrioritizedOriginDatabase); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_SANDBOX_PRIORITIZED_ORIGIN_DATABASE_H_ +#include "storage/browser/fileapi/sandbox_prioritized_origin_database.h" diff --git a/webkit/browser/fileapi/sandbox_quota_observer.h b/webkit/browser/fileapi/sandbox_quota_observer.h index 7a90757..1df1a65 100644 --- a/webkit/browser/fileapi/sandbox_quota_observer.h +++ b/webkit/browser/fileapi/sandbox_quota_observer.h @@ -1,81 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_SANDBOX_QUOTA_OBSERVER_H_ -#define WEBKIT_BROWSER_FILEAPI_SANDBOX_QUOTA_OBSERVER_H_ - -#include <map> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/files/file_path.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "webkit/browser/fileapi/file_observers.h" -#include "webkit/browser/fileapi/file_system_url.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace storage { -class QuotaManagerProxy; -} - -namespace storage { - -class FileSystemUsageCache; -class FileSystemURL; -class TimedTaskHelper; -class ObfuscatedFileUtil; - -class SandboxQuotaObserver - : public FileUpdateObserver, - public FileAccessObserver { - public: - typedef std::map<base::FilePath, int64> PendingUpdateNotificationMap; - - SandboxQuotaObserver(storage::QuotaManagerProxy* quota_manager_proxy, - base::SequencedTaskRunner* update_notify_runner, - ObfuscatedFileUtil* sandbox_file_util, - FileSystemUsageCache* file_system_usage_cache_); - virtual ~SandboxQuotaObserver(); - - // FileUpdateObserver overrides. - virtual void OnStartUpdate(const FileSystemURL& url) OVERRIDE; - virtual void OnUpdate(const FileSystemURL& url, int64 delta) OVERRIDE; - virtual void OnEndUpdate(const FileSystemURL& url) OVERRIDE; - - // FileAccessObserver overrides. - virtual void OnAccess(const FileSystemURL& url) OVERRIDE; - - void SetUsageCacheEnabled(const GURL& origin, - FileSystemType type, - bool enabled); - - private: - void ApplyPendingUsageUpdate(); - void UpdateUsageCacheFile(const base::FilePath& usage_file_path, int64 delta); - - base::FilePath GetUsageCachePath(const FileSystemURL& url); - - scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy_; - scoped_refptr<base::SequencedTaskRunner> update_notify_runner_; - - // Not owned; sandbox_file_util_ should have identical lifetime with this. - ObfuscatedFileUtil* sandbox_file_util_; - - // Not owned; file_system_usage_cache_ should have longer lifetime than this. - FileSystemUsageCache* file_system_usage_cache_; - - PendingUpdateNotificationMap pending_update_notification_; - scoped_ptr<TimedTaskHelper> delayed_cache_update_helper_; - - DISALLOW_COPY_AND_ASSIGN(SandboxQuotaObserver); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_SANDBOX_QUOTA_OBSERVER_H_ +#include "storage/browser/fileapi/sandbox_quota_observer.h" diff --git a/webkit/browser/fileapi/task_runner_bound_observer_list.h b/webkit/browser/fileapi/task_runner_bound_observer_list.h index a3228ff..a5f463e 100644 --- a/webkit/browser/fileapi/task_runner_bound_observer_list.h +++ b/webkit/browser/fileapi/task_runner_bound_observer_list.h @@ -1,99 +1,5 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_TASK_RUNNER_BOUND_OBSERVER_LIST_H_ -#define WEBKIT_BROWSER_FILEAPI_TASK_RUNNER_BOUND_OBSERVER_LIST_H_ - -#include <map> - -#include "base/basictypes.h" -#include "base/bind.h" -#include "base/memory/ref_counted.h" -#include "base/sequenced_task_runner.h" -#include "base/threading/thread.h" - -namespace storage { - -// A wrapper for dispatching method. -template <class T, class Method, class Params> -void NotifyWrapper(T obj, Method m, const Params& p) { - DispatchToMethod(base::internal::UnwrapTraits<T>::Unwrap(obj), m, p); -} - -// An observer list helper to notify on a given task runner. -// Observer pointers (stored as ObserverStoreType) must be kept alive -// until this list dispatches all the notifications. -// -// Unlike regular ObserverList or ObserverListThreadSafe internal observer -// list is immutable (though not declared const) and cannot be modified after -// constructed. -// -// It is ok to specify scoped_refptr<Observer> as ObserverStoreType to -// explicitly keep references if necessary. -template <class Observer, class ObserverStoreType = Observer*> -class TaskRunnerBoundObserverList { - public: - typedef scoped_refptr<base::SequencedTaskRunner> TaskRunnerPtr; - typedef std::map<ObserverStoreType, TaskRunnerPtr> ObserversListMap; - - // Creates an empty list. - TaskRunnerBoundObserverList<Observer, ObserverStoreType>() {} - - // Creates a new list with given |observers|. - explicit TaskRunnerBoundObserverList<Observer, ObserverStoreType>( - const ObserversListMap& observers) - : observers_(observers) {} - - virtual ~TaskRunnerBoundObserverList<Observer, ObserverStoreType>() {} - - // Returns a new observer list with given observer. - // It is valid to give NULL as |runner_to_notify|, and in that case - // notifications are dispatched on the current runner. - // Note that this is a const method and does NOT change 'this' observer - // list but returns a new list. - TaskRunnerBoundObserverList<Observer, ObserverStoreType> AddObserver( - Observer* observer, - base::SequencedTaskRunner* runner_to_notify) const { - ObserversListMap observers = observers_; - observers.insert(std::make_pair(observer, runner_to_notify)); - return TaskRunnerBoundObserverList<Observer, ObserverStoreType>(observers); - } - - // Notify on the task runner that is given to AddObserver. - // If we're already on the runner this just dispatches the method. - template <class Method, class Params> - void Notify(Method method, const Params& params) const { - COMPILE_ASSERT( - (base::internal::ParamsUseScopedRefptrCorrectly<Params>::value), - badunboundmethodparams); - for (typename ObserversListMap::const_iterator it = observers_.begin(); - it != observers_.end(); ++it) { - if (!it->second.get() || it->second->RunsTasksOnCurrentThread()) { - DispatchToMethod(UnwrapTraits::Unwrap(it->first), method, params); - continue; - } - it->second->PostTask( - FROM_HERE, - base::Bind(&NotifyWrapper<ObserverStoreType, Method, Params>, - it->first, method, params)); - } - } - - private: - typedef base::internal::UnwrapTraits<ObserverStoreType> UnwrapTraits; - - ObserversListMap observers_; -}; - -class FileAccessObserver; -class FileChangeObserver; -class FileUpdateObserver; - -typedef TaskRunnerBoundObserverList<FileAccessObserver> AccessObserverList; -typedef TaskRunnerBoundObserverList<FileChangeObserver> ChangeObserverList; -typedef TaskRunnerBoundObserverList<FileUpdateObserver> UpdateObserverList; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_TASK_RUNNER_BOUND_OBSERVER_LIST_H_ +#include "storage/browser/fileapi/task_runner_bound_observer_list.h" diff --git a/webkit/browser/fileapi/timed_task_helper.h b/webkit/browser/fileapi/timed_task_helper.h index 5ea145f..956eb58 100644 --- a/webkit/browser/fileapi/timed_task_helper.h +++ b/webkit/browser/fileapi/timed_task_helper.h @@ -1,59 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_TIMED_TASK_HELPER_H_ -#define WEBKIT_BROWSER_FILEAPI_TIMED_TASK_HELPER_H_ - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/location.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/time/time.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace storage { - -// Works similarly as base::Timer, but takes SequencedTaskRunner and -// runs tasks on it (instead of implicitly bound to a thread). -// TODO(kinuko): This has nothing to do with fileapi. Move somewhere -// more common place. -class STORAGE_EXPORT TimedTaskHelper { - public: - explicit TimedTaskHelper(base::SequencedTaskRunner* task_runner); - ~TimedTaskHelper(); - - bool IsRunning() const; - void Start(const tracked_objects::Location& posted_from, - base::TimeDelta delay, - const base::Closure& user_task); - void Reset(); - - private: - struct Tracker; - static void Fired(scoped_ptr<Tracker> tracker); - - void OnFired(scoped_ptr<Tracker> tracker); - void PostDelayedTask(scoped_ptr<Tracker> tracker, base::TimeDelta delay); - - scoped_refptr<base::SequencedTaskRunner> task_runner_; - tracked_objects::Location posted_from_; - base::TimeDelta delay_; - base::Closure user_task_; - - base::TimeTicks desired_run_time_; - - // This is set to non-null and owned by a timer task while timer is running. - Tracker* tracker_; - - DISALLOW_COPY_AND_ASSIGN(TimedTaskHelper); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_TIMED_TASK_HELPER_H_ +#include "storage/browser/fileapi/timed_task_helper.h" diff --git a/webkit/browser/fileapi/transient_file_util.h b/webkit/browser/fileapi/transient_file_util.h index 4125788..cad9e89 100644 --- a/webkit/browser/fileapi/transient_file_util.h +++ b/webkit/browser/fileapi/transient_file_util.h @@ -1,36 +1,5 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_TRANSIENT_FILE_UTIL_H_ -#define WEBKIT_BROWSER_FILEAPI_TRANSIENT_FILE_UTIL_H_ - -#include "base/memory/scoped_ptr.h" -#include "webkit/browser/fileapi/local_file_util.h" -#include "webkit/browser/storage_browser_export.h" - -namespace storage { - -class FileSystemOperationContext; - -class STORAGE_EXPORT_PRIVATE TransientFileUtil - : public LocalFileUtil { - public: - TransientFileUtil() {} - virtual ~TransientFileUtil() {} - - // LocalFileUtil overrides. - virtual storage::ScopedFile CreateSnapshotFile( - FileSystemOperationContext* context, - const FileSystemURL& url, - base::File::Error* error, - base::File::Info* file_info, - base::FilePath* platform_path) OVERRIDE; - - private: - DISALLOW_COPY_AND_ASSIGN(TransientFileUtil); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_TRANSIENT_FILE_UTIL_H_ +#include "storage/browser/fileapi/transient_file_util.h" diff --git a/webkit/browser/fileapi/watcher_manager.h b/webkit/browser/fileapi/watcher_manager.h index 83a64f6..0b51e73 100644 --- a/webkit/browser/fileapi/watcher_manager.h +++ b/webkit/browser/fileapi/watcher_manager.h @@ -2,66 +2,4 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_FILEAPI_WATCHER_MANAGER_H_ -#define WEBKIT_BROWSER_FILEAPI_WATCHER_MANAGER_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "base/callback_forward.h" -#include "base/files/file.h" - -namespace base { -class Time; -} - -namespace storage { - -class FileSystemOperationContext; -class FileSystemURL; - -// An interface for providing entry observing capability for file system -// backends. -// -// It is NOT valid to give null callback to this class, and implementors -// can assume that they don't get any null callbacks. -class WatcherManager { - public: - typedef base::Callback<void(base::File::Error result)> StatusCallback; - - // Observes watched entries. - class Observer { - public: - Observer() {} - virtual ~Observer() {} - - // Notifies about an entry represented by |url| being changed. - virtual void OnEntryChanged(const FileSystemURL& url) = 0; - - // Notifies about an entry represented by |url| being removed. - virtual void OnEntryRemoved(const FileSystemURL& url) = 0; - }; - - virtual ~WatcherManager() {} - - virtual void AddObserver(Observer* observer) = 0; - virtual void RemoveObserver(Observer* observer) = 0; - virtual bool HasObserver(Observer* observer) const = 0; - - // Observes a directory entry. If the |recursive| mode is not supported then - // FILE_ERROR_INVALID_OPERATION must be returned as an error. If the |url| is - // already watched, or setting up the watcher fails, then |callback| - // must be called with a specific error code. Otherwise |callback| must be - // called with the FILE_OK error code. - virtual void WatchDirectory(const FileSystemURL& url, - bool recursive, - const StatusCallback& callback) = 0; - - // Stops observing an entry represented by |url|. - virtual void UnwatchEntry(const FileSystemURL& url, - const StatusCallback& callback) = 0; -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_FILEAPI_WATCHER_MANAGER_H_ +#include "storage/browser/fileapi/watcher_manager.h" diff --git a/webkit/browser/quota/quota_callbacks.h b/webkit/browser/quota/quota_callbacks.h index 7018aba..a68dee5 100644 --- a/webkit/browser/quota/quota_callbacks.h +++ b/webkit/browser/quota/quota_callbacks.h @@ -1,129 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_QUOTA_QUOTA_CALLBACKS_H_ -#define WEBKIT_BROWSER_QUOTA_QUOTA_CALLBACKS_H_ - -#include <map> -#include <set> -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/tuple.h" -#include "webkit/common/quota/quota_status_code.h" -#include "webkit/common/quota/quota_types.h" - -class GURL; - -namespace storage { - -struct UsageInfo; -typedef std::vector<UsageInfo> UsageInfoEntries; - -// Common callback types that are used throughout in the quota module. -typedef base::Callback<void(int64 usage, - int64 unlimited_usage)> GlobalUsageCallback; -typedef base::Callback<void(QuotaStatusCode status, int64 quota)> QuotaCallback; -typedef base::Callback<void(int64 usage)> UsageCallback; -typedef base::Callback<void(QuotaStatusCode, int64)> AvailableSpaceCallback; -typedef base::Callback<void(QuotaStatusCode)> StatusCallback; -typedef base::Callback<void(const std::set<GURL>& origins, - StorageType type)> GetOriginsCallback; -typedef base::Callback<void(const UsageInfoEntries&)> GetUsageInfoCallback; - -template<typename CallbackType, typename Args> -void DispatchToCallback(const CallbackType& callback, - const Args& args) { - DispatchToMethod(&callback, &CallbackType::Run, args); -} - -// Simple template wrapper for a callback queue. -template <typename CallbackType, typename Args> -class CallbackQueue { - public: - // Returns true if the given |callback| is the first one added to the queue. - bool Add(const CallbackType& callback) { - callbacks_.push_back(callback); - return (callbacks_.size() == 1); - } - - bool HasCallbacks() const { - return !callbacks_.empty(); - } - - // Runs the callbacks added to the queue and clears the queue. - void Run(const Args& args) { - typedef typename std::vector<CallbackType>::iterator iterator; - for (iterator iter = callbacks_.begin(); - iter != callbacks_.end(); ++iter) - DispatchToCallback(*iter, args); - callbacks_.clear(); - } - - private: - std::vector<CallbackType> callbacks_; -}; - -typedef CallbackQueue<GlobalUsageCallback, - Tuple2<int64, int64> > - GlobalUsageCallbackQueue; -typedef CallbackQueue<UsageCallback, Tuple1<int64> > - UsageCallbackQueue; -typedef CallbackQueue<AvailableSpaceCallback, - Tuple2<QuotaStatusCode, int64> > - AvailableSpaceCallbackQueue; -typedef CallbackQueue<QuotaCallback, - Tuple2<QuotaStatusCode, int64> > - GlobalQuotaCallbackQueue; -typedef CallbackQueue<base::Closure, Tuple0> ClosureQueue; - -template <typename CallbackType, typename Key, typename Args> -class CallbackQueueMap { - public: - typedef CallbackQueue<CallbackType, Args> CallbackQueueType; - typedef std::map<Key, CallbackQueueType> CallbackMap; - typedef typename CallbackMap::iterator iterator; - - bool Add(const Key& key, const CallbackType& callback) { - return callback_map_[key].Add(callback); - } - - bool HasCallbacks(const Key& key) const { - return (callback_map_.find(key) != callback_map_.end()); - } - - bool HasAnyCallbacks() const { - return !callback_map_.empty(); - } - - iterator Begin() { return callback_map_.begin(); } - iterator End() { return callback_map_.end(); } - - void Clear() { callback_map_.clear(); } - - // Runs the callbacks added for the given |key| and clears the key - // from the map. - void Run(const Key& key, const Args& args) { - if (!this->HasCallbacks(key)) - return; - CallbackQueueType& queue = callback_map_[key]; - queue.Run(args); - callback_map_.erase(key); - } - - private: - CallbackMap callback_map_; -}; - -typedef CallbackQueueMap<UsageCallback, std::string, Tuple1<int64> > - HostUsageCallbackMap; -typedef CallbackQueueMap<QuotaCallback, std::string, - Tuple2<QuotaStatusCode, int64> > - HostQuotaCallbackMap; - -} // namespace storage - -#endif // WEBKIT_QUOTA_QUOTA_TYPES_H_ +#include "storage/browser/quota/quota_callbacks.h" diff --git a/webkit/browser/quota/quota_client.h b/webkit/browser/quota/quota_client.h index 5f94dd0..435cf0f 100644 --- a/webkit/browser/quota/quota_client.h +++ b/webkit/browser/quota/quota_client.h @@ -1,81 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_QUOTA_QUOTA_CLIENT_H_ -#define WEBKIT_BROWSER_QUOTA_QUOTA_CLIENT_H_ - -#include <list> -#include <set> -#include <string> - -#include "base/callback.h" -#include "url/gurl.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/quota/quota_types.h" - -namespace storage { - -// An abstract interface for quota manager clients. -// Each storage API must provide an implementation of this interface and -// register it to the quota manager. -// All the methods are assumed to be called on the IO thread in the browser. -class STORAGE_EXPORT QuotaClient { - public: - typedef base::Callback<void(int64 usage)> GetUsageCallback; - typedef base::Callback<void(const std::set<GURL>& origins)> - GetOriginsCallback; - typedef base::Callback<void(QuotaStatusCode status)> DeletionCallback; - - virtual ~QuotaClient() {} - - enum ID { - kUnknown = 1 << 0, - kFileSystem = 1 << 1, - kDatabase = 1 << 2, - kAppcache = 1 << 3, - kIndexedDatabase = 1 << 4, - kAllClientsMask = -1, - }; - - virtual ID id() const = 0; - - // Called when the quota manager is destroyed. - virtual void OnQuotaManagerDestroyed() = 0; - - // Called by the QuotaManager. - // Gets the amount of data stored in the storage specified by - // |origin_url| and |type|. - // Note it is safe to fire the callback after the QuotaClient is destructed. - virtual void GetOriginUsage(const GURL& origin_url, - StorageType type, - const GetUsageCallback& callback) = 0; - - // Called by the QuotaManager. - // Returns a list of origins that has data in the |type| storage. - // Note it is safe to fire the callback after the QuotaClient is destructed. - virtual void GetOriginsForType(StorageType type, - const GetOriginsCallback& callback) = 0; - - // Called by the QuotaManager. - // Returns a list of origins that match the |host|. - // Note it is safe to fire the callback after the QuotaClient is destructed. - virtual void GetOriginsForHost(StorageType type, - const std::string& host, - const GetOriginsCallback& callback) = 0; - - // Called by the QuotaManager. - // Note it is safe to fire the callback after the QuotaClient is destructed. - virtual void DeleteOriginData(const GURL& origin, - StorageType type, - const DeletionCallback& callback) = 0; - - virtual bool DoesSupport(StorageType type) const = 0; -}; - -// TODO(dmikurube): Replace it to std::vector for efficiency. -typedef std::list<QuotaClient*> QuotaClientList; - -} // namespace storage - -#endif // WEBKIT_BROWSER_QUOTA_QUOTA_CLIENT_H_ +#include "storage/browser/quota/quota_client.h" diff --git a/webkit/browser/quota/quota_database.h b/webkit/browser/quota/quota_database.h index 86ec718..1415004 100644 --- a/webkit/browser/quota/quota_database.h +++ b/webkit/browser/quota/quota_database.h @@ -1,190 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_QUOTA_QUOTA_DATABASE_H_ -#define WEBKIT_BROWSER_QUOTA_QUOTA_DATABASE_H_ - -#include <set> -#include <string> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/files/file_path.h" -#include "base/gtest_prod_util.h" -#include "base/memory/scoped_ptr.h" -#include "base/time/time.h" -#include "base/timer/timer.h" -#include "url/gurl.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/quota/quota_types.h" - -namespace content { -class QuotaDatabaseTest; -} - -namespace sql { -class Connection; -class MetaTable; -} - -class GURL; - -namespace storage { - -class SpecialStoragePolicy; - -// All the methods of this class must run on the DB thread. -class STORAGE_EXPORT_PRIVATE QuotaDatabase { - public: - // Constants for {Get,Set}QuotaConfigValue keys. - static const char kDesiredAvailableSpaceKey[]; - static const char kTemporaryQuotaOverrideKey[]; - - // If 'path' is empty, an in memory database will be used. - explicit QuotaDatabase(const base::FilePath& path); - ~QuotaDatabase(); - - void CloseConnection(); - - bool GetHostQuota(const std::string& host, StorageType type, int64* quota); - bool SetHostQuota(const std::string& host, StorageType type, int64 quota); - bool DeleteHostQuota(const std::string& host, StorageType type); - - bool SetOriginLastAccessTime(const GURL& origin, - StorageType type, - base::Time last_access_time); - - bool SetOriginLastModifiedTime(const GURL& origin, - StorageType type, - base::Time last_modified_time); - - // Register initial |origins| info |type| to the database. - // This method is assumed to be called only after the installation or - // the database schema reset. - bool RegisterInitialOriginInfo( - const std::set<GURL>& origins, StorageType type); - - bool DeleteOriginInfo(const GURL& origin, StorageType type); - - bool GetQuotaConfigValue(const char* key, int64* value); - bool SetQuotaConfigValue(const char* key, int64 value); - - // Sets |origin| to the least recently used origin of origins not included - // in |exceptions| and not granted the special unlimited storage right. - // It returns false when it failed in accessing the database. - // |origin| is set to empty when there is no matching origin. - bool GetLRUOrigin(StorageType type, - const std::set<GURL>& exceptions, - SpecialStoragePolicy* special_storage_policy, - GURL* origin); - - // Populates |origins| with the ones that have been modified since - // the |modified_since|. - bool GetOriginsModifiedSince(StorageType type, - std::set<GURL>* origins, - base::Time modified_since); - - // Returns false if SetOriginDatabaseBootstrapped has never - // been called before, which means existing origins may not have been - // registered. - bool IsOriginDatabaseBootstrapped(); - bool SetOriginDatabaseBootstrapped(bool bootstrap_flag); - - private: - struct STORAGE_EXPORT_PRIVATE QuotaTableEntry { - QuotaTableEntry(); - QuotaTableEntry( - const std::string& host, - StorageType type, - int64 quota); - std::string host; - StorageType type; - int64 quota; - }; - friend STORAGE_EXPORT_PRIVATE bool operator <( - const QuotaTableEntry& lhs, const QuotaTableEntry& rhs); - - struct STORAGE_EXPORT_PRIVATE OriginInfoTableEntry { - OriginInfoTableEntry(); - OriginInfoTableEntry( - const GURL& origin, - StorageType type, - int used_count, - const base::Time& last_access_time, - const base::Time& last_modified_time); - GURL origin; - StorageType type; - int used_count; - base::Time last_access_time; - base::Time last_modified_time; - }; - friend STORAGE_EXPORT_PRIVATE bool operator <( - const OriginInfoTableEntry& lhs, const OriginInfoTableEntry& rhs); - - // Structures used for CreateSchema. - struct TableSchema { - const char* table_name; - const char* columns; - }; - struct IndexSchema { - const char* index_name; - const char* table_name; - const char* columns; - bool unique; - }; - - typedef base::Callback<bool (const QuotaTableEntry&)> QuotaTableCallback; - typedef base::Callback<bool (const OriginInfoTableEntry&)> - OriginInfoTableCallback; - - struct QuotaTableImporter; - - // For long-running transactions support. We always keep a transaction open - // so that multiple transactions can be batched. They are flushed - // with a delay after a modification has been made. We support neither - // nested transactions nor rollback (as we don't need them for now). - void Commit(); - void ScheduleCommit(); - - bool FindOriginUsedCount(const GURL& origin, - StorageType type, - int* used_count); - - bool LazyOpen(bool create_if_needed); - bool EnsureDatabaseVersion(); - bool ResetSchema(); - bool UpgradeSchema(int current_version); - - static bool CreateSchema( - sql::Connection* database, - sql::MetaTable* meta_table, - int schema_version, int compatible_version, - const TableSchema* tables, size_t tables_size, - const IndexSchema* indexes, size_t indexes_size); - - // |callback| may return false to stop reading data. - bool DumpQuotaTable(const QuotaTableCallback& callback); - bool DumpOriginInfoTable(const OriginInfoTableCallback& callback); - - base::FilePath db_file_path_; - - scoped_ptr<sql::Connection> db_; - scoped_ptr<sql::MetaTable> meta_table_; - bool is_recreating_; - bool is_disabled_; - - base::OneShotTimer<QuotaDatabase> timer_; - - friend class content::QuotaDatabaseTest; - friend class QuotaManager; - - static const TableSchema kTables[]; - static const IndexSchema kIndexes[]; - - DISALLOW_COPY_AND_ASSIGN(QuotaDatabase); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_QUOTA_QUOTA_DATABASE_H_ +#include "storage/browser/quota/quota_database.h" diff --git a/webkit/browser/quota/quota_manager.h b/webkit/browser/quota/quota_manager.h index 19c26f2..86c55a8 100644 --- a/webkit/browser/quota/quota_manager.h +++ b/webkit/browser/quota/quota_manager.h @@ -1,460 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_QUOTA_QUOTA_MANAGER_H_ -#define WEBKIT_BROWSER_QUOTA_QUOTA_MANAGER_H_ - -#include <deque> -#include <list> -#include <map> -#include <set> -#include <string> -#include <utility> -#include <vector> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/files/file_path.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/sequenced_task_runner_helpers.h" -#include "webkit/browser/quota/quota_callbacks.h" -#include "webkit/browser/quota/quota_client.h" -#include "webkit/browser/quota/quota_database.h" -#include "webkit/browser/quota/quota_task.h" -#include "webkit/browser/quota/special_storage_policy.h" -#include "webkit/browser/quota/storage_observer.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class FilePath; -class SequencedTaskRunner; -class SingleThreadTaskRunner; -} - -namespace quota_internals { -class QuotaInternalsProxy; -} - -namespace content { -class MockQuotaManager; -class MockStorageClient; -class QuotaManagerTest; -class StorageMonitorTest; - -} - -namespace storage { - -class QuotaDatabase; -class QuotaManagerProxy; -class QuotaTemporaryStorageEvictor; -class StorageMonitor; -class UsageTracker; - -struct QuotaManagerDeleter; - -struct STORAGE_EXPORT UsageAndQuota { - int64 usage; - int64 global_limited_usage; - int64 quota; - int64 available_disk_space; - - UsageAndQuota(); - UsageAndQuota(int64 usage, - int64 global_limited_usage, - int64 quota, - int64 available_disk_space); -}; - -// An interface called by QuotaTemporaryStorageEvictor. -class STORAGE_EXPORT QuotaEvictionHandler { - public: - typedef base::Callback<void(const GURL&)> GetLRUOriginCallback; - typedef StatusCallback EvictOriginDataCallback; - typedef base::Callback<void(QuotaStatusCode status, - const UsageAndQuota& usage_and_quota)> - UsageAndQuotaCallback; - - // Returns the least recently used origin. It might return empty - // GURL when there are no evictable origins. - virtual void GetLRUOrigin( - StorageType type, - const GetLRUOriginCallback& callback) = 0; - - virtual void EvictOriginData( - const GURL& origin, - StorageType type, - const EvictOriginDataCallback& callback) = 0; - - virtual void GetUsageAndQuotaForEviction( - const UsageAndQuotaCallback& callback) = 0; - - protected: - virtual ~QuotaEvictionHandler() {} -}; - -struct UsageInfo { - UsageInfo(const std::string& host, StorageType type, int64 usage) - : host(host), - type(type), - usage(usage) {} - std::string host; - StorageType type; - int64 usage; -}; - -// The quota manager class. This class is instantiated per profile and -// held by the profile. With the exception of the constructor and the -// proxy() method, all methods should only be called on the IO thread. -class STORAGE_EXPORT QuotaManager - : public QuotaTaskObserver, - public QuotaEvictionHandler, - public base::RefCountedThreadSafe<QuotaManager, QuotaManagerDeleter> { - public: - typedef base::Callback<void(QuotaStatusCode, - int64 /* usage */, - int64 /* quota */)> - GetUsageAndQuotaCallback; - - static const int64 kIncognitoDefaultQuotaLimit; - static const int64 kNoLimit; - - QuotaManager( - bool is_incognito, - const base::FilePath& profile_path, - const scoped_refptr<base::SingleThreadTaskRunner>& io_thread, - const scoped_refptr<base::SequencedTaskRunner>& db_thread, - const scoped_refptr<SpecialStoragePolicy>& special_storage_policy); - - // Returns a proxy object that can be used on any thread. - QuotaManagerProxy* proxy() { return proxy_.get(); } - - // Called by clients or webapps. Returns usage per host. - void GetUsageInfo(const GetUsageInfoCallback& callback); - - // Called by Web Apps. - // This method is declared as virtual to allow test code to override it. - virtual void GetUsageAndQuotaForWebApps( - const GURL& origin, - StorageType type, - const GetUsageAndQuotaCallback& callback); - - // Called by StorageClients. - // This method is declared as virtual to allow test code to override it. - // - // For UnlimitedStorage origins, this version skips usage and quota handling - // to avoid extra query cost. - // Do not call this method for apps/user-facing code. - virtual void GetUsageAndQuota( - const GURL& origin, - StorageType type, - const GetUsageAndQuotaCallback& callback); - - // Called by clients via proxy. - // Client storage should call this method when storage is accessed. - // Used to maintain LRU ordering. - void NotifyStorageAccessed(QuotaClient::ID client_id, - const GURL& origin, - StorageType type); - - // Called by clients via proxy. - // Client storage must call this method whenever they have made any - // modifications that change the amount of data stored in their storage. - void NotifyStorageModified(QuotaClient::ID client_id, - const GURL& origin, - StorageType type, - int64 delta); - - // Used to avoid evicting origins with open pages. - // A call to NotifyOriginInUse must be balanced by a later call - // to NotifyOriginNoLongerInUse. - void NotifyOriginInUse(const GURL& origin); - void NotifyOriginNoLongerInUse(const GURL& origin); - bool IsOriginInUse(const GURL& origin) const { - return origins_in_use_.find(origin) != origins_in_use_.end(); - } - - void SetUsageCacheEnabled(QuotaClient::ID client_id, - const GURL& origin, - StorageType type, - bool enabled); - - // DeleteOriginData and DeleteHostData (surprisingly enough) delete data of a - // particular StorageType associated with either a specific origin or set of - // origins. Each method additionally requires a |quota_client_mask| which - // specifies the types of QuotaClients to delete from the origin. This is - // specified by the caller as a bitmask built from QuotaClient::IDs. Setting - // the mask to QuotaClient::kAllClientsMask will remove all clients from the - // origin, regardless of type. - virtual void DeleteOriginData(const GURL& origin, - StorageType type, - int quota_client_mask, - const StatusCallback& callback); - void DeleteHostData(const std::string& host, - StorageType type, - int quota_client_mask, - const StatusCallback& callback); - - // Called by UI and internal modules. - void GetAvailableSpace(const AvailableSpaceCallback& callback); - void GetTemporaryGlobalQuota(const QuotaCallback& callback); - - // Ok to call with NULL callback. - void SetTemporaryGlobalOverrideQuota(int64 new_quota, - const QuotaCallback& callback); - - void GetPersistentHostQuota(const std::string& host, - const QuotaCallback& callback); - void SetPersistentHostQuota(const std::string& host, - int64 new_quota, - const QuotaCallback& callback); - void GetGlobalUsage(StorageType type, const GlobalUsageCallback& callback); - void GetHostUsage(const std::string& host, StorageType type, - const UsageCallback& callback); - void GetHostUsage(const std::string& host, StorageType type, - QuotaClient::ID client_id, - const UsageCallback& callback); - - bool IsTrackingHostUsage(StorageType type, QuotaClient::ID client_id) const; - - void GetStatistics(std::map<std::string, std::string>* statistics); - - bool IsStorageUnlimited(const GURL& origin, StorageType type) const; - - bool CanQueryDiskSize(const GURL& origin) const { - return special_storage_policy_.get() && - special_storage_policy_->CanQueryDiskSize(origin); - } - - virtual void GetOriginsModifiedSince(StorageType type, - base::Time modified_since, - const GetOriginsCallback& callback); - - bool ResetUsageTracker(StorageType type); - - // Used to register/deregister observers that wish to monitor storage events. - void AddStorageObserver(StorageObserver* observer, - const StorageObserver::MonitorParams& params); - void RemoveStorageObserver(StorageObserver* observer); - void RemoveStorageObserverForFilter(StorageObserver* observer, - const StorageObserver::Filter& filter); - - // Determines the portion of the temp pool that can be - // utilized by a single host (ie. 5 for 20%). - static const int kPerHostTemporaryPortion; - - static const int64 kPerHostPersistentQuotaLimit; - - static const char kDatabaseName[]; - - static const int kThresholdOfErrorsToBeBlacklisted; - - static const int kEvictionIntervalInMilliSeconds; - - // These are kept non-const so that test code can change the value. - // TODO(kinuko): Make this a real const value and add a proper way to set - // the quota for syncable storage. (http://crbug.com/155488) - static int64 kMinimumPreserveForSystem; - static int64 kSyncableStorageDefaultHostQuota; - - protected: - virtual ~QuotaManager(); - - private: - friend class base::DeleteHelper<QuotaManager>; - friend class base::RefCountedThreadSafe<QuotaManager, QuotaManagerDeleter>; - friend class content::QuotaManagerTest; - friend class content::StorageMonitorTest; - friend class content::MockQuotaManager; - friend class content::MockStorageClient; - friend class quota_internals::QuotaInternalsProxy; - friend class QuotaManagerProxy; - friend class QuotaTemporaryStorageEvictor; - friend struct QuotaManagerDeleter; - - class GetUsageInfoTask; - - class OriginDataDeleter; - class HostDataDeleter; - - class GetModifiedSinceHelper; - class DumpQuotaTableHelper; - class DumpOriginInfoTableHelper; - - typedef QuotaDatabase::QuotaTableEntry QuotaTableEntry; - typedef QuotaDatabase::OriginInfoTableEntry OriginInfoTableEntry; - typedef std::vector<QuotaTableEntry> QuotaTableEntries; - typedef std::vector<OriginInfoTableEntry> OriginInfoTableEntries; - - // Function pointer type used to store the function which returns the - // available disk space for the disk containing the given FilePath. - typedef int64 (*GetAvailableDiskSpaceFn)(const base::FilePath&); - - typedef base::Callback<void(const QuotaTableEntries&)> - DumpQuotaTableCallback; - typedef base::Callback<void(const OriginInfoTableEntries&)> - DumpOriginInfoTableCallback; - - struct EvictionContext { - EvictionContext(); - virtual ~EvictionContext(); - GURL evicted_origin; - StorageType evicted_type; - - EvictOriginDataCallback evict_origin_data_callback; - }; - - typedef QuotaEvictionHandler::UsageAndQuotaCallback - UsageAndQuotaDispatcherCallback; - - // This initialization method is lazily called on the IO thread - // when the first quota manager API is called. - // Initialize must be called after all quota clients are added to the - // manager by RegisterStorage. - void LazyInitialize(); - - // Called by clients via proxy. - // Registers a quota client to the manager. - // The client must remain valid until OnQuotaManagerDestored is called. - void RegisterClient(QuotaClient* client); - - UsageTracker* GetUsageTracker(StorageType type) const; - - // Extract cached origins list from the usage tracker. - // (Might return empty list if no origin is tracked by the tracker.) - void GetCachedOrigins(StorageType type, std::set<GURL>* origins); - - // These internal methods are separately defined mainly for testing. - void NotifyStorageAccessedInternal( - QuotaClient::ID client_id, - const GURL& origin, - StorageType type, - base::Time accessed_time); - void NotifyStorageModifiedInternal( - QuotaClient::ID client_id, - const GURL& origin, - StorageType type, - int64 delta, - base::Time modified_time); - - void DumpQuotaTable(const DumpQuotaTableCallback& callback); - void DumpOriginInfoTable(const DumpOriginInfoTableCallback& callback); - - // Methods for eviction logic. - void StartEviction(); - void DeleteOriginFromDatabase(const GURL& origin, StorageType type); - - void DidOriginDataEvicted(QuotaStatusCode status); - - void ReportHistogram(); - void DidGetTemporaryGlobalUsageForHistogram(int64 usage, - int64 unlimited_usage); - void DidGetPersistentGlobalUsageForHistogram(int64 usage, - int64 unlimited_usage); - - // QuotaEvictionHandler. - virtual void GetLRUOrigin( - StorageType type, - const GetLRUOriginCallback& callback) OVERRIDE; - virtual void EvictOriginData( - const GURL& origin, - StorageType type, - const EvictOriginDataCallback& callback) OVERRIDE; - virtual void GetUsageAndQuotaForEviction( - const UsageAndQuotaCallback& callback) OVERRIDE; - - void DidSetTemporaryGlobalOverrideQuota(const QuotaCallback& callback, - const int64* new_quota, - bool success); - void DidGetPersistentHostQuota(const std::string& host, - const int64* quota, - bool success); - void DidSetPersistentHostQuota(const std::string& host, - const QuotaCallback& callback, - const int64* new_quota, - bool success); - void DidInitialize(int64* temporary_quota_override, - int64* desired_available_space, - bool success); - void DidGetLRUOrigin(const GURL* origin, - bool success); - void DidGetInitialTemporaryGlobalQuota(QuotaStatusCode status, - int64 quota_unused); - void DidInitializeTemporaryOriginsInfo(bool success); - void DidGetAvailableSpace(int64 space); - void DidDatabaseWork(bool success); - - void DeleteOnCorrectThread() const; - - void PostTaskAndReplyWithResultForDBThread( - const tracked_objects::Location& from_here, - const base::Callback<bool(QuotaDatabase*)>& task, - const base::Callback<void(bool)>& reply); - - const bool is_incognito_; - const base::FilePath profile_path_; - - scoped_refptr<QuotaManagerProxy> proxy_; - bool db_disabled_; - bool eviction_disabled_; - scoped_refptr<base::SingleThreadTaskRunner> io_thread_; - scoped_refptr<base::SequencedTaskRunner> db_thread_; - mutable scoped_ptr<QuotaDatabase> database_; - - GetLRUOriginCallback lru_origin_callback_; - std::set<GURL> access_notified_origins_; - - QuotaClientList clients_; - - scoped_ptr<UsageTracker> temporary_usage_tracker_; - scoped_ptr<UsageTracker> persistent_usage_tracker_; - scoped_ptr<UsageTracker> syncable_usage_tracker_; - // TODO(michaeln): Need a way to clear the cache, drop and - // reinstantiate the trackers when they're not handling requests. - - scoped_ptr<QuotaTemporaryStorageEvictor> temporary_storage_evictor_; - EvictionContext eviction_context_; - - ClosureQueue db_initialization_callbacks_; - AvailableSpaceCallbackQueue available_space_callbacks_; - GlobalQuotaCallbackQueue temporary_global_quota_callbacks_; - HostQuotaCallbackMap persistent_host_quota_callbacks_; - - bool temporary_quota_initialized_; - int64 temporary_quota_override_; - - int64 desired_available_space_; - - // Map from origin to count. - std::map<GURL, int> origins_in_use_; - // Map from origin to error count. - std::map<GURL, int> origins_in_error_; - - scoped_refptr<SpecialStoragePolicy> special_storage_policy_; - - base::RepeatingTimer<QuotaManager> histogram_timer_; - - // Pointer to the function used to get the available disk space. This is - // overwritten by QuotaManagerTest in order to attain a deterministic reported - // value. The default value points to base::SysInfo::AmountOfFreeDiskSpace. - GetAvailableDiskSpaceFn get_disk_space_fn_; - - scoped_ptr<StorageMonitor> storage_monitor_; - - base::WeakPtrFactory<QuotaManager> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(QuotaManager); -}; - -struct QuotaManagerDeleter { - static void Destruct(const QuotaManager* manager) { - manager->DeleteOnCorrectThread(); - } -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_QUOTA_QUOTA_MANAGER_H_ +#include "storage/browser/quota/quota_manager.h" diff --git a/webkit/browser/quota/quota_manager_proxy.h b/webkit/browser/quota/quota_manager_proxy.h index 447664c..49e7b21 100644 --- a/webkit/browser/quota/quota_manager_proxy.h +++ b/webkit/browser/quota/quota_manager_proxy.h @@ -2,78 +2,4 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_QUOTA_QUOTA_MANAGER_PROXY_H_ -#define WEBKIT_BROWSER_QUOTA_QUOTA_MANAGER_PROXY_H_ - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/files/file_path.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/sequenced_task_runner_helpers.h" -#include "webkit/browser/quota/quota_callbacks.h" -#include "webkit/browser/quota/quota_client.h" -#include "webkit/browser/quota/quota_database.h" -#include "webkit/browser/quota/quota_manager.h" -#include "webkit/browser/quota/quota_task.h" -#include "webkit/browser/quota/special_storage_policy.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class SequencedTaskRunner; -class SingleThreadTaskRunner; -} - -namespace storage { - -// The proxy may be called and finally released on any thread. -class STORAGE_EXPORT QuotaManagerProxy - : public base::RefCountedThreadSafe<QuotaManagerProxy> { - public: - typedef QuotaManager::GetUsageAndQuotaCallback - GetUsageAndQuotaCallback; - - virtual void RegisterClient(QuotaClient* client); - virtual void NotifyStorageAccessed(QuotaClient::ID client_id, - const GURL& origin, - StorageType type); - virtual void NotifyStorageModified(QuotaClient::ID client_id, - const GURL& origin, - StorageType type, - int64 delta); - virtual void NotifyOriginInUse(const GURL& origin); - virtual void NotifyOriginNoLongerInUse(const GURL& origin); - - virtual void SetUsageCacheEnabled(QuotaClient::ID client_id, - const GURL& origin, - StorageType type, - bool enabled); - virtual void GetUsageAndQuota( - base::SequencedTaskRunner* original_task_runner, - const GURL& origin, - StorageType type, - const GetUsageAndQuotaCallback& callback); - - // This method may only be called on the IO thread. - // It may return NULL if the manager has already been deleted. - QuotaManager* quota_manager() const; - - protected: - friend class QuotaManager; - friend class base::RefCountedThreadSafe<QuotaManagerProxy>; - - QuotaManagerProxy( - QuotaManager* manager, - const scoped_refptr<base::SingleThreadTaskRunner>& io_thread); - virtual ~QuotaManagerProxy(); - - QuotaManager* manager_; // only accessed on the io thread - scoped_refptr<base::SingleThreadTaskRunner> io_thread_; - - DISALLOW_COPY_AND_ASSIGN(QuotaManagerProxy); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_QUOTA_QUOTA_MANAGER_PROXY_H_ +#include "storage/browser/quota/quota_manager_proxy.h" diff --git a/webkit/browser/quota/quota_task.h b/webkit/browser/quota/quota_task.h index 5201a61..66f2256 100644 --- a/webkit/browser/quota/quota_task.h +++ b/webkit/browser/quota/quota_task.h @@ -1,79 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_QUOTA_QUOTA_TASK_H_ -#define WEBKIT_BROWSER_QUOTA_QUOTA_TASK_H_ - -#include <set> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "base/sequenced_task_runner_helpers.h" -#include "webkit/browser/storage_browser_export.h" - -namespace base { -class SingleThreadTaskRunner; -class TaskRunner; -} - -namespace storage { - -class QuotaTaskObserver; - -// A base class for quota tasks. -// TODO(kinuko): Revise this using base::Callback. -class QuotaTask { - public: - void Start(); - - protected: - explicit QuotaTask(QuotaTaskObserver* observer); - virtual ~QuotaTask(); - - // The task body. - virtual void Run() = 0; - - // Called upon completion, on the original message loop. - virtual void Completed() = 0; - - // Called when the task is aborted. - virtual void Aborted() {} - - void CallCompleted(); - - // Call this to delete itself. - void DeleteSoon(); - - QuotaTaskObserver* observer() const { return observer_; } - base::SingleThreadTaskRunner* original_task_runner() const { - return original_task_runner_.get(); - } - - private: - friend class base::DeleteHelper<QuotaTask>; - friend class QuotaTaskObserver; - - void Abort(); - QuotaTaskObserver* observer_; - scoped_refptr<base::SingleThreadTaskRunner> original_task_runner_; - bool delete_scheduled_; -}; - -class STORAGE_EXPORT QuotaTaskObserver { - protected: - friend class QuotaTask; - - QuotaTaskObserver(); - virtual ~QuotaTaskObserver(); - - void RegisterTask(QuotaTask* task); - void UnregisterTask(QuotaTask* task); - - typedef std::set<QuotaTask*> TaskSet; - TaskSet running_quota_tasks_; -}; -} - -#endif // WEBKIT_BROWSER_QUOTA_QUOTA_TASK_H_ +#include "storage/browser/quota/quota_task.h" diff --git a/webkit/browser/quota/quota_temporary_storage_evictor.h b/webkit/browser/quota/quota_temporary_storage_evictor.h index 6a4fbd7..e7b63c7 100644 --- a/webkit/browser/quota/quota_temporary_storage_evictor.h +++ b/webkit/browser/quota/quota_temporary_storage_evictor.h @@ -1,134 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_QUOTA_QUOTA_TEMPORARY_STORAGE_EVICTOR_H_ -#define WEBKIT_BROWSER_QUOTA_QUOTA_TEMPORARY_STORAGE_EVICTOR_H_ - -#include <map> -#include <string> - -#include "base/memory/weak_ptr.h" -#include "base/threading/non_thread_safe.h" -#include "base/timer/timer.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/quota/quota_types.h" - -class GURL; - -namespace content { -class QuotaTemporaryStorageEvictorTest; -} - -namespace storage { - -class QuotaEvictionHandler; -struct UsageAndQuota; - -class STORAGE_EXPORT_PRIVATE QuotaTemporaryStorageEvictor - : public base::NonThreadSafe { - public: - struct Statistics { - Statistics() - : num_errors_on_evicting_origin(0), - num_errors_on_getting_usage_and_quota(0), - num_evicted_origins(0), - num_eviction_rounds(0), - num_skipped_eviction_rounds(0) {} - int64 num_errors_on_evicting_origin; - int64 num_errors_on_getting_usage_and_quota; - int64 num_evicted_origins; - int64 num_eviction_rounds; - int64 num_skipped_eviction_rounds; - - void subtract_assign(const Statistics& rhs) { - num_errors_on_evicting_origin -= rhs.num_errors_on_evicting_origin; - num_errors_on_getting_usage_and_quota -= - rhs.num_errors_on_getting_usage_and_quota; - num_evicted_origins -= rhs.num_evicted_origins; - num_eviction_rounds -= rhs.num_eviction_rounds; - num_skipped_eviction_rounds -= rhs.num_skipped_eviction_rounds; - } - }; - - struct EvictionRoundStatistics { - EvictionRoundStatistics(); - - bool in_round; - bool is_initialized; - - base::Time start_time; - int64 usage_overage_at_round; - int64 diskspace_shortage_at_round; - - int64 usage_on_beginning_of_round; - int64 usage_on_end_of_round; - int64 num_evicted_origins_in_round; - }; - - QuotaTemporaryStorageEvictor( - QuotaEvictionHandler* quota_eviction_handler, - int64 interval_ms); - virtual ~QuotaTemporaryStorageEvictor(); - - void GetStatistics(std::map<std::string, int64>* statistics); - void ReportPerRoundHistogram(); - void ReportPerHourHistogram(); - void Start(); - - int64 min_available_disk_space_to_start_eviction() { - return min_available_disk_space_to_start_eviction_; - } - void reset_min_available_disk_space_to_start_eviction() { - min_available_disk_space_to_start_eviction_ = - kMinAvailableDiskSpaceToStartEvictionNotSpecified; - } - void set_min_available_disk_space_to_start_eviction(int64 value) { - min_available_disk_space_to_start_eviction_ = value; - } - - private: - friend class content::QuotaTemporaryStorageEvictorTest; - - void StartEvictionTimerWithDelay(int delay_ms); - void ConsiderEviction(); - void OnGotUsageAndQuotaForEviction( - QuotaStatusCode status, - const UsageAndQuota& quota_and_usage); - void OnGotLRUOrigin(const GURL& origin); - void OnEvictionComplete(QuotaStatusCode status); - - void OnEvictionRoundStarted(); - void OnEvictionRoundFinished(); - - // This is only used for tests. - void set_repeated_eviction(bool repeated_eviction) { - repeated_eviction_ = repeated_eviction; - } - - static const int kMinAvailableDiskSpaceToStartEvictionNotSpecified; - - int64 min_available_disk_space_to_start_eviction_; - - // Not owned; quota_eviction_handler owns us. - QuotaEvictionHandler* quota_eviction_handler_; - - Statistics statistics_; - Statistics previous_statistics_; - EvictionRoundStatistics round_statistics_; - base::Time time_of_end_of_last_nonskipped_round_; - base::Time time_of_end_of_last_round_; - - int64 interval_ms_; - bool repeated_eviction_; - - base::OneShotTimer<QuotaTemporaryStorageEvictor> eviction_timer_; - base::RepeatingTimer<QuotaTemporaryStorageEvictor> histogram_timer_; - base::WeakPtrFactory<QuotaTemporaryStorageEvictor> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(QuotaTemporaryStorageEvictor); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_QUOTA_QUOTA_TEMPORARY_STORAGE_EVICTOR_H_ +#include "storage/browser/quota/quota_temporary_storage_evictor.h" diff --git a/webkit/browser/quota/special_storage_policy.h b/webkit/browser/quota/special_storage_policy.h index 5ddc821..b0430fd 100644 --- a/webkit/browser/quota/special_storage_policy.h +++ b/webkit/browser/quota/special_storage_policy.h @@ -1,86 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_QUOTA_SPECIAL_STORAGE_POLICY_H_ -#define WEBKIT_BROWSER_QUOTA_SPECIAL_STORAGE_POLICY_H_ - -#include <string> - -#include "base/memory/ref_counted.h" -#include "base/observer_list.h" -#include "webkit/browser/storage_browser_export.h" - -class GURL; - -namespace storage { - -// Special rights are granted to 'extensions' and 'applications'. The -// storage subsystems query this interface to determine which origins -// have these rights. Chrome provides an impl that is cognizant of what -// is currently installed in the extensions system. -// The IsSomething() methods must be thread-safe, however Observers should -// only be notified, added, and removed on the IO thead. -class STORAGE_EXPORT SpecialStoragePolicy - : public base::RefCountedThreadSafe<SpecialStoragePolicy> { - public: - typedef int StoragePolicy; - enum ChangeFlags { - STORAGE_PROTECTED = 1 << 0, - STORAGE_UNLIMITED = 1 << 1, - }; - - class STORAGE_EXPORT Observer { - public: - virtual void OnGranted(const GURL& origin, int change_flags) = 0; - virtual void OnRevoked(const GURL& origin, int change_flags) = 0; - virtual void OnCleared() = 0; - - protected: - virtual ~Observer(); - }; - - SpecialStoragePolicy(); - - // Protected storage is not subject to removal by the browsing data remover. - virtual bool IsStorageProtected(const GURL& origin) = 0; - - // Unlimited storage is not subject to 'quotas'. - virtual bool IsStorageUnlimited(const GURL& origin) = 0; - - // Some origins (e.g. installed apps) have access to the size of the remaining - // disk capacity. - virtual bool CanQueryDiskSize(const GURL& origin) = 0; - - // Checks if extension identified with |extension_id| is registered as - // file handler. - virtual bool IsFileHandler(const std::string& extension_id) = 0; - - // Checks if the origin contains per-site isolated storage. - virtual bool HasIsolatedStorage(const GURL& origin) = 0; - - // Some origins are only allowed to store session-only data which is deleted - // when the session ends. - virtual bool IsStorageSessionOnly(const GURL& origin) = 0; - - // Returns true if some origins are only allowed session-only storage. - virtual bool HasSessionOnlyOrigins() = 0; - - // Adds/removes an observer, the policy does not take - // ownership of the observer. Should only be called on the IO thread. - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - - protected: - friend class base::RefCountedThreadSafe<SpecialStoragePolicy>; - virtual ~SpecialStoragePolicy(); - void NotifyGranted(const GURL& origin, int change_flags); - void NotifyRevoked(const GURL& origin, int change_flags); - void NotifyCleared(); - - ObserverList<Observer> observers_; -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_QUOTA_SPECIAL_STORAGE_POLICY_H_ +#include "storage/browser/quota/special_storage_policy.h" diff --git a/webkit/browser/quota/storage_monitor.h b/webkit/browser/quota/storage_monitor.h index 66a7e8a..48992e4 100644 --- a/webkit/browser/quota/storage_monitor.h +++ b/webkit/browser/quota/storage_monitor.h @@ -2,179 +2,4 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_QUOTA_STORAGE_MONITOR_H_ -#define WEBKIT_BROWSER_QUOTA_STORAGE_MONITOR_H_ - -#include <map> - -#include "base/memory/weak_ptr.h" -#include "base/time/time.h" -#include "base/timer/timer.h" -#include "webkit/browser/quota/storage_observer.h" - -namespace content { -class StorageMonitorTestBase; -} - -namespace storage { - -class QuotaManager; - -// This class dispatches storage events to observers of a common -// StorageObserver::Filter. -class STORAGE_EXPORT_PRIVATE StorageObserverList { - public: - StorageObserverList(); - virtual ~StorageObserverList(); - - // Adds/removes an observer. - void AddObserver(StorageObserver* observer, - const StorageObserver::MonitorParams& params); - void RemoveObserver(StorageObserver* observer); - - // Returns the number of observers. - int ObserverCount() const; - - // Forwards a storage change to observers. The event may be dispatched - // immediately to an observer or after a delay, depending on the desired event - // rate of the observer. - void OnStorageChange(const StorageObserver::Event& event); - - // Dispatch an event to observers that require it. - void MaybeDispatchEvent(const StorageObserver::Event& event); - - // Ensure the specified observer receives the next dispatched event. - void ScheduleUpdateForObserver(StorageObserver* observer); - - private: - struct STORAGE_EXPORT_PRIVATE ObserverState { - GURL origin; - base::TimeTicks last_notification_time; - base::TimeDelta rate; - bool requires_update; - - ObserverState(); - }; - typedef std::map<StorageObserver*, ObserverState> StorageObserverStateMap; - - void DispatchPendingEvent(); - - StorageObserverStateMap observers_; - base::OneShotTimer<StorageObserverList> notification_timer_; - StorageObserver::Event pending_event_; - - friend class content::StorageMonitorTestBase; - - DISALLOW_COPY_AND_ASSIGN(StorageObserverList); -}; - - -// Manages the storage observers of a common host. Caches the usage and quota of -// the host to avoid accumulating for every change. -class STORAGE_EXPORT_PRIVATE HostStorageObservers { - public: - explicit HostStorageObservers(QuotaManager* quota_manager); - virtual ~HostStorageObservers(); - - bool is_initialized() const { return initialized_; } - - // Adds/removes an observer. - void AddObserver( - StorageObserver* observer, - const StorageObserver::MonitorParams& params); - void RemoveObserver(StorageObserver* observer); - bool ContainsObservers() const; - - // Handles a usage change. - void NotifyUsageChange(const StorageObserver::Filter& filter, int64 delta); - - private: - void StartInitialization(const StorageObserver::Filter& filter); - void GotHostUsageAndQuota(const StorageObserver::Filter& filter, - QuotaStatusCode status, - int64 usage, - int64 quota); - void DispatchEvent(const StorageObserver::Filter& filter, bool is_update); - - QuotaManager* quota_manager_; - StorageObserverList observers_; - - // Flags used during initialization of the cached properties. - bool initialized_; - bool initializing_; - bool event_occurred_before_init_; - int64 usage_deltas_during_init_; - - // Cached accumulated usage and quota for the host. - int64 cached_usage_; - int64 cached_quota_; - - base::WeakPtrFactory<HostStorageObservers> weak_factory_; - - friend class content::StorageMonitorTestBase; - - DISALLOW_COPY_AND_ASSIGN(HostStorageObservers); -}; - - -// Manages the observers of a common storage type. -class STORAGE_EXPORT_PRIVATE StorageTypeObservers { - public: - explicit StorageTypeObservers(QuotaManager* quota_manager); - virtual ~StorageTypeObservers(); - - // Adds and removes an observer. - void AddObserver(StorageObserver* observer, - const StorageObserver::MonitorParams& params); - void RemoveObserver(StorageObserver* observer); - void RemoveObserverForFilter(StorageObserver* observer, - const StorageObserver::Filter& filter); - - // Returns the observers of a specific host. - const HostStorageObservers* GetHostObservers(const std::string& host) const; - - // Handles a usage change. - void NotifyUsageChange(const StorageObserver::Filter& filter, int64 delta); - - private: - typedef std::map<std::string, HostStorageObservers*> HostObserversMap; - - QuotaManager* quota_manager_; - HostObserversMap host_observers_map_; - - DISALLOW_COPY_AND_ASSIGN(StorageTypeObservers); -}; - - -// Storage monitor manages observers and dispatches storage events to them. -class STORAGE_EXPORT_PRIVATE StorageMonitor { - public: - explicit StorageMonitor(QuotaManager* quota_manager); - virtual ~StorageMonitor(); - - // Adds and removes an observer. - void AddObserver(StorageObserver* observer, - const StorageObserver::MonitorParams& params); - void RemoveObserver(StorageObserver* observer); - void RemoveObserverForFilter(StorageObserver* observer, - const StorageObserver::Filter& filter); - - // Returns the observers of a specific storage type. - const StorageTypeObservers* GetStorageTypeObservers( - StorageType storage_type) const; - - // Handles a usage change. - void NotifyUsageChange(const StorageObserver::Filter& filter, int64 delta); - - private: - typedef std::map<StorageType, StorageTypeObservers*> StorageTypeObserversMap; - - QuotaManager* quota_manager_; - StorageTypeObserversMap storage_type_observers_map_; - - DISALLOW_COPY_AND_ASSIGN(StorageMonitor); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_QUOTA_STORAGE_MONITOR_H_ +#include "storage/browser/quota/storage_monitor.h" diff --git a/webkit/browser/quota/storage_observer.h b/webkit/browser/quota/storage_observer.h index 1272f941..e732df1 100644 --- a/webkit/browser/quota/storage_observer.h +++ b/webkit/browser/quota/storage_observer.h @@ -2,78 +2,4 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_QUOTA_STORAGE_OBSERVER_H_ -#define WEBKIT_BROWSER_QUOTA_STORAGE_OBSERVER_H_ - -#include "base/basictypes.h" -#include "base/time/time.h" -#include "url/gurl.h" -#include "webkit/browser/quota/quota_client.h" -#include "webkit/common/quota/quota_types.h" - -namespace storage { - -// This interface is implemented by observers that wish to monitor storage -// events, such as changes in quota or usage. -class STORAGE_EXPORT StorageObserver { - public: - struct STORAGE_EXPORT Filter { - // The storage type to monitor. This must not be kStorageTypeUnknown or - // kStorageTypeQuotaNotManaged. - StorageType storage_type; - - // The origin to monitor usage for. Must be specified. - GURL origin; - - Filter(); - Filter(StorageType storage_type, const GURL& origin); - bool operator==(const Filter& other) const; - }; - - struct STORAGE_EXPORT MonitorParams { - // Storage type and origin to monitor. - Filter filter; - - // The rate at which storage events will be fired. Events will be fired at - // approximately this rate, or when a storage status change has been - // detected, whichever is the least frequent. - base::TimeDelta rate; - - // If set to true, the observer will be dispatched an event when added. - bool dispatch_initial_state; - - MonitorParams(); - MonitorParams(StorageType storage_type, - const GURL& origin, - const base::TimeDelta& rate, - bool get_initial_state); - MonitorParams(const Filter& filter, - const base::TimeDelta& rate, - bool get_initial_state); - }; - - struct STORAGE_EXPORT Event { - // The storage type and origin monitored. - Filter filter; - - // The current usage corresponding to the filter. - int64 usage; - - // The quota corresponding to the filter. - int64 quota; - - Event(); - Event(const Filter& filter, int64 usage, int64 quota); - bool operator==(const Event& other) const; - }; - - // Will be called on the IO thread when a storage event occurs. - virtual void OnStorageEvent(const Event& event) = 0; - - protected: - virtual ~StorageObserver() {} -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_QUOTA_STORAGE_OBSERVER_H_ +#include "storage/browser/quota/storage_observer.h" diff --git a/webkit/browser/quota/usage_tracker.h b/webkit/browser/quota/usage_tracker.h index 85792ac..e576d00 100644 --- a/webkit/browser/quota/usage_tracker.h +++ b/webkit/browser/quota/usage_tracker.h @@ -1,202 +1,5 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_QUOTA_USAGE_TRACKER_H_ -#define WEBKIT_BROWSER_QUOTA_USAGE_TRACKER_H_ - -#include <list> -#include <map> -#include <set> -#include <string> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/memory/scoped_ptr.h" -#include "base/threading/non_thread_safe.h" -#include "url/gurl.h" -#include "webkit/browser/quota/quota_callbacks.h" -#include "webkit/browser/quota/quota_client.h" -#include "webkit/browser/quota/quota_task.h" -#include "webkit/browser/quota/special_storage_policy.h" -#include "webkit/browser/storage_browser_export.h" -#include "webkit/common/quota/quota_types.h" - -namespace storage { - -class ClientUsageTracker; -class StorageMonitor; - -// A helper class that gathers and tracks the amount of data stored in -// all quota clients. -// An instance of this class is created per storage type. -class STORAGE_EXPORT UsageTracker : public QuotaTaskObserver { - public: - UsageTracker(const QuotaClientList& clients, StorageType type, - SpecialStoragePolicy* special_storage_policy, - StorageMonitor* storage_monitor); - virtual ~UsageTracker(); - - StorageType type() const { return type_; } - ClientUsageTracker* GetClientTracker(QuotaClient::ID client_id); - - void GetGlobalLimitedUsage(const UsageCallback& callback); - void GetGlobalUsage(const GlobalUsageCallback& callback); - void GetHostUsage(const std::string& host, const UsageCallback& callback); - void UpdateUsageCache(QuotaClient::ID client_id, - const GURL& origin, - int64 delta); - void GetCachedHostsUsage(std::map<std::string, int64>* host_usage) const; - void GetCachedOrigins(std::set<GURL>* origins) const; - bool IsWorking() const { - return global_usage_callbacks_.HasCallbacks() || - host_usage_callbacks_.HasAnyCallbacks(); - } - - void SetUsageCacheEnabled(QuotaClient::ID client_id, - const GURL& origin, - bool enabled); - - private: - struct AccumulateInfo { - AccumulateInfo() : pending_clients(0), usage(0), unlimited_usage(0) {} - int pending_clients; - int64 usage; - int64 unlimited_usage; - }; - - typedef std::map<QuotaClient::ID, ClientUsageTracker*> ClientTrackerMap; - - friend class ClientUsageTracker; - void AccumulateClientGlobalLimitedUsage(AccumulateInfo* info, - int64 limited_usage); - void AccumulateClientGlobalUsage(AccumulateInfo* info, - int64 usage, - int64 unlimited_usage); - void AccumulateClientHostUsage(AccumulateInfo* info, - const std::string& host, - int64 usage); - - const StorageType type_; - ClientTrackerMap client_tracker_map_; - - UsageCallbackQueue global_limited_usage_callbacks_; - GlobalUsageCallbackQueue global_usage_callbacks_; - HostUsageCallbackMap host_usage_callbacks_; - - StorageMonitor* storage_monitor_; - - base::WeakPtrFactory<UsageTracker> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(UsageTracker); -}; - -// This class holds per-client usage tracking information and caches per-host -// usage data. An instance of this class is created per client. -class ClientUsageTracker : public SpecialStoragePolicy::Observer, - public base::NonThreadSafe, - public base::SupportsWeakPtr<ClientUsageTracker> { - public: - typedef base::Callback<void(int64 limited_usage, - int64 unlimited_usage)> HostUsageAccumulator; - typedef base::Callback<void(const GURL& origin, - int64 usage)> OriginUsageAccumulator; - typedef std::map<std::string, std::set<GURL> > OriginSetByHost; - - ClientUsageTracker(UsageTracker* tracker, - QuotaClient* client, - StorageType type, - SpecialStoragePolicy* special_storage_policy, - StorageMonitor* storage_monitor); - virtual ~ClientUsageTracker(); - - void GetGlobalLimitedUsage(const UsageCallback& callback); - void GetGlobalUsage(const GlobalUsageCallback& callback); - void GetHostUsage(const std::string& host, const UsageCallback& callback); - void UpdateUsageCache(const GURL& origin, int64 delta); - void GetCachedHostsUsage(std::map<std::string, int64>* host_usage) const; - void GetCachedOrigins(std::set<GURL>* origins) const; - int64 GetCachedOriginsUsage(const std::set<GURL>& origins, - std::vector<GURL>* origins_not_in_cache); - bool IsUsageCacheEnabledForOrigin(const GURL& origin) const; - void SetUsageCacheEnabled(const GURL& origin, bool enabled); - - private: - typedef CallbackQueueMap<HostUsageAccumulator, std::string, - Tuple2<int64, int64> > HostUsageAccumulatorMap; - - typedef std::set<std::string> HostSet; - typedef std::map<GURL, int64> UsageMap; - typedef std::map<std::string, UsageMap> HostUsageMap; - - struct AccumulateInfo { - int pending_jobs; - int64 limited_usage; - int64 unlimited_usage; - - AccumulateInfo() - : pending_jobs(0), limited_usage(0), unlimited_usage(0) {} - }; - - void AccumulateLimitedOriginUsage(AccumulateInfo* info, - const UsageCallback& callback, - int64 usage); - void DidGetOriginsForGlobalUsage(const GlobalUsageCallback& callback, - const std::set<GURL>& origins); - void AccumulateHostUsage(AccumulateInfo* info, - const GlobalUsageCallback& callback, - int64 limited_usage, - int64 unlimited_usage); - - void DidGetOriginsForHostUsage(const std::string& host, - const std::set<GURL>& origins); - - void GetUsageForOrigins(const std::string& host, - const std::set<GURL>& origins); - void AccumulateOriginUsage(AccumulateInfo* info, - const std::string& host, - const GURL& origin, - int64 usage); - - void DidGetHostUsageAfterUpdate(const GURL& origin, int64 usage); - - // Methods used by our GatherUsage tasks, as a task makes progress - // origins and hosts are added incrementally to the cache. - void AddCachedOrigin(const GURL& origin, int64 usage); - void AddCachedHost(const std::string& host); - - int64 GetCachedHostUsage(const std::string& host) const; - int64 GetCachedGlobalUnlimitedUsage(); - bool GetCachedOriginUsage(const GURL& origin, int64* usage) const; - - // SpecialStoragePolicy::Observer overrides - virtual void OnGranted(const GURL& origin, int change_flags) OVERRIDE; - virtual void OnRevoked(const GURL& origin, int change_flags) OVERRIDE; - virtual void OnCleared() OVERRIDE; - - bool IsStorageUnlimited(const GURL& origin) const; - - UsageTracker* tracker_; - QuotaClient* client_; - const StorageType type_; - StorageMonitor* storage_monitor_; - - int64 global_limited_usage_; - int64 global_unlimited_usage_; - bool global_usage_retrieved_; - HostSet cached_hosts_; - HostUsageMap cached_usage_by_host_; - - OriginSetByHost non_cached_limited_origins_by_host_; - OriginSetByHost non_cached_unlimited_origins_by_host_; - - GlobalUsageCallbackQueue global_usage_callback_; - HostUsageAccumulatorMap host_usage_accumulators_; - - scoped_refptr<SpecialStoragePolicy> special_storage_policy_; - - DISALLOW_COPY_AND_ASSIGN(ClientUsageTracker); -}; - -} // namespace storage - -#endif // WEBKIT_BROWSER_QUOTA_USAGE_TRACKER_H_ +#include "storage/browser/quota/usage_tracker.h" diff --git a/webkit/browser/storage_browser_export.h b/webkit/browser/storage_browser_export.h index 293ce40..421ae558 100644 --- a/webkit/browser/storage_browser_export.h +++ b/webkit/browser/storage_browser_export.h @@ -1,34 +1,5 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef WEBKIT_BROWSER_STORAGE_BROWSER_EXPORT_H__ -#define WEBKIT_BROWSER_STORAGE_BROWSER_EXPORT_H__ - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(STORAGE_BROWSER_IMPLEMENTATION) -#define STORAGE_EXPORT __declspec(dllexport) -#define STORAGE_EXPORT_PRIVATE __declspec(dllexport) -#else -#define STORAGE_EXPORT __declspec(dllimport) -#define STORAGE_EXPORT_PRIVATE __declspec(dllimport) -#endif // defined(STORAGE_BROWSER_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(STORAGE_BROWSER_IMPLEMENTATION) -#define STORAGE_EXPORT __attribute__((visibility("default"))) -#define STORAGE_EXPORT_PRIVATE __attribute__((visibility("default"))) -#else -#define STORAGE_EXPORT -#define STORAGE_EXPORT_PRIVATE -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define STORAGE_EXPORT -#define STORAGE_EXPORT_PRIVATE -#endif - -#endif // WEBKIT_BROWSER_STORAGE_BROWSER_EXPORT_H__ +#include "storage/browser/storage_browser_export.h" |