- remove mojo_view_manager_lib_unittests from chrome_tests.py
[chromium-blink-merge.git] / content / browser / storage_partition_impl_map.cc
blob3a67d724837c371d697e2a819d807649c09daeae
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/storage_partition_impl_map.h"
7 #include "base/bind.h"
8 #include "base/callback.h"
9 #include "base/file_util.h"
10 #include "base/files/file_enumerator.h"
11 #include "base/files/file_path.h"
12 #include "base/stl_util.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/threading/sequenced_worker_pool.h"
17 #include "content/browser/appcache/chrome_appcache_service.h"
18 #include "content/browser/fileapi/browser_file_system_helper.h"
19 #include "content/browser/fileapi/chrome_blob_storage_context.h"
20 #include "content/browser/loader/resource_request_info_impl.h"
21 #include "content/browser/resource_context_impl.h"
22 #include "content/browser/service_worker/service_worker_request_handler.h"
23 #include "content/browser/storage_partition_impl.h"
24 #include "content/browser/streams/stream.h"
25 #include "content/browser/streams/stream_context.h"
26 #include "content/browser/streams/stream_registry.h"
27 #include "content/browser/streams/stream_url_request_job.h"
28 #include "content/browser/webui/url_data_manager_backend.h"
29 #include "content/public/browser/browser_context.h"
30 #include "content/public/browser/browser_thread.h"
31 #include "content/public/browser/content_browser_client.h"
32 #include "content/public/browser/storage_partition.h"
33 #include "content/public/common/content_constants.h"
34 #include "content/public/common/url_constants.h"
35 #include "crypto/sha2.h"
36 #include "net/url_request/url_request_context.h"
37 #include "net/url_request/url_request_context_getter.h"
38 #include "webkit/browser/blob/blob_storage_context.h"
39 #include "webkit/browser/blob/blob_url_request_job_factory.h"
40 #include "webkit/browser/fileapi/file_system_url_request_job_factory.h"
41 #include "webkit/common/blob/blob_data.h"
43 using fileapi::FileSystemContext;
44 using webkit_blob::BlobStorageContext;
46 namespace content {
48 namespace {
50 // A derivative that knows about Streams too.
51 class BlobProtocolHandler : public net::URLRequestJobFactory::ProtocolHandler {
52 public:
53 BlobProtocolHandler(ChromeBlobStorageContext* blob_storage_context,
54 StreamContext* stream_context,
55 fileapi::FileSystemContext* file_system_context)
56 : blob_storage_context_(blob_storage_context),
57 stream_context_(stream_context),
58 file_system_context_(file_system_context) {
61 virtual ~BlobProtocolHandler() {
64 virtual net::URLRequestJob* MaybeCreateJob(
65 net::URLRequest* request,
66 net::NetworkDelegate* network_delegate) const OVERRIDE {
67 scoped_refptr<Stream> stream =
68 stream_context_->registry()->GetStream(request->url());
69 if (stream.get())
70 return new StreamURLRequestJob(request, network_delegate, stream);
72 if (!blob_protocol_handler_) {
73 // Construction is deferred because 'this' is constructed on
74 // the main thread but we want blob_protocol_handler_ constructed
75 // on the IO thread.
76 blob_protocol_handler_.reset(
77 new webkit_blob::BlobProtocolHandler(
78 blob_storage_context_->context(),
79 file_system_context_,
80 BrowserThread::GetMessageLoopProxyForThread(
81 BrowserThread::FILE).get()));
83 return blob_protocol_handler_->MaybeCreateJob(request, network_delegate);
86 private:
87 const scoped_refptr<ChromeBlobStorageContext> blob_storage_context_;
88 const scoped_refptr<StreamContext> stream_context_;
89 const scoped_refptr<fileapi::FileSystemContext> file_system_context_;
90 mutable scoped_ptr<webkit_blob::BlobProtocolHandler> blob_protocol_handler_;
91 DISALLOW_COPY_AND_ASSIGN(BlobProtocolHandler);
94 // These constants are used to create the directory structure under the profile
95 // where renderers with a non-default storage partition keep their persistent
96 // state. This will contain a set of directories that partially mirror the
97 // directory structure of BrowserContext::GetPath().
99 // The kStoragePartitionDirname contains an extensions directory which is
100 // further partitioned by extension id, followed by another level of directories
101 // for the "default" extension storage partition and one directory for each
102 // persistent partition used by a webview tag. Example:
104 // Storage/ext/ABCDEF/def
105 // Storage/ext/ABCDEF/hash(partition name)
107 // The code in GetStoragePartitionPath() constructs these path names.
109 // TODO(nasko): Move extension related path code out of content.
110 const base::FilePath::CharType kStoragePartitionDirname[] =
111 FILE_PATH_LITERAL("Storage");
112 const base::FilePath::CharType kExtensionsDirname[] =
113 FILE_PATH_LITERAL("ext");
114 const base::FilePath::CharType kDefaultPartitionDirname[] =
115 FILE_PATH_LITERAL("def");
116 const base::FilePath::CharType kTrashDirname[] =
117 FILE_PATH_LITERAL("trash");
119 // Because partition names are user specified, they can be arbitrarily long
120 // which makes them unsuitable for paths names. We use a truncation of a
121 // SHA256 hash to perform a deterministic shortening of the string. The
122 // kPartitionNameHashBytes constant controls the length of the truncation.
123 // We use 6 bytes, which gives us 99.999% reliability against collisions over
124 // 1 million partition domains.
126 // Analysis:
127 // We assume that all partition names within one partition domain are
128 // controlled by the the same entity. Thus there is no chance for adverserial
129 // attack and all we care about is accidental collision. To get 5 9s over
130 // 1 million domains, we need the probability of a collision in any one domain
131 // to be
133 // p < nroot(1000000, .99999) ~= 10^-11
135 // We use the following birthday attack approximation to calculate the max
136 // number of unique names for this probability:
138 // n(p,H) = sqrt(2*H * ln(1/(1-p)))
140 // For a 6-byte hash, H = 2^(6*8). n(10^-11, H) ~= 75
142 // An average partition domain is likely to have less than 10 unique
143 // partition names which is far lower than 75.
145 // Note, that for 4 9s of reliability, the limit is 237 partition names per
146 // partition domain.
147 const int kPartitionNameHashBytes = 6;
149 // Needed for selecting all files in ObliterateOneDirectory() below.
150 #if defined(OS_POSIX)
151 const int kAllFileTypes = base::FileEnumerator::FILES |
152 base::FileEnumerator::DIRECTORIES |
153 base::FileEnumerator::SHOW_SYM_LINKS;
154 #else
155 const int kAllFileTypes = base::FileEnumerator::FILES |
156 base::FileEnumerator::DIRECTORIES;
157 #endif
159 base::FilePath GetStoragePartitionDomainPath(
160 const std::string& partition_domain) {
161 CHECK(base::IsStringUTF8(partition_domain));
163 return base::FilePath(kStoragePartitionDirname).Append(kExtensionsDirname)
164 .Append(base::FilePath::FromUTF8Unsafe(partition_domain));
167 // Helper function for doing a depth-first deletion of the data on disk.
168 // Examines paths directly in |current_dir| (no recursion) and tries to
169 // delete from disk anything that is in, or isn't a parent of something in
170 // |paths_to_keep|. Paths that need further expansion are added to
171 // |paths_to_consider|.
172 void ObliterateOneDirectory(const base::FilePath& current_dir,
173 const std::vector<base::FilePath>& paths_to_keep,
174 std::vector<base::FilePath>* paths_to_consider) {
175 CHECK(current_dir.IsAbsolute());
177 base::FileEnumerator enumerator(current_dir, false, kAllFileTypes);
178 for (base::FilePath to_delete = enumerator.Next(); !to_delete.empty();
179 to_delete = enumerator.Next()) {
180 // Enum tracking which of the 3 possible actions to take for |to_delete|.
181 enum { kSkip, kEnqueue, kDelete } action = kDelete;
183 for (std::vector<base::FilePath>::const_iterator to_keep =
184 paths_to_keep.begin();
185 to_keep != paths_to_keep.end();
186 ++to_keep) {
187 if (to_delete == *to_keep) {
188 action = kSkip;
189 break;
190 } else if (to_delete.IsParent(*to_keep)) {
191 // |to_delete| contains a path to keep. Add to stack for further
192 // processing.
193 action = kEnqueue;
194 break;
198 switch (action) {
199 case kDelete:
200 base::DeleteFile(to_delete, true);
201 break;
203 case kEnqueue:
204 paths_to_consider->push_back(to_delete);
205 break;
207 case kSkip:
208 break;
213 // Synchronously attempts to delete |unnormalized_root|, preserving only
214 // entries in |paths_to_keep|. If there are no entries in |paths_to_keep| on
215 // disk, then it completely removes |unnormalized_root|. All paths must be
216 // absolute paths.
217 void BlockingObliteratePath(
218 const base::FilePath& unnormalized_browser_context_root,
219 const base::FilePath& unnormalized_root,
220 const std::vector<base::FilePath>& paths_to_keep,
221 const scoped_refptr<base::TaskRunner>& closure_runner,
222 const base::Closure& on_gc_required) {
223 // Early exit required because MakeAbsoluteFilePath() will fail on POSIX
224 // if |unnormalized_root| does not exist. This is safe because there is
225 // nothing to do in this situation anwyays.
226 if (!base::PathExists(unnormalized_root)) {
227 return;
230 // Never try to obliterate things outside of the browser context root or the
231 // browser context root itself. Die hard.
232 base::FilePath root = base::MakeAbsoluteFilePath(unnormalized_root);
233 base::FilePath browser_context_root =
234 base::MakeAbsoluteFilePath(unnormalized_browser_context_root);
235 CHECK(!root.empty());
236 CHECK(!browser_context_root.empty());
237 CHECK(browser_context_root.IsParent(root) && browser_context_root != root);
239 // Reduce |paths_to_keep| set to those under the root and actually on disk.
240 std::vector<base::FilePath> valid_paths_to_keep;
241 for (std::vector<base::FilePath>::const_iterator it = paths_to_keep.begin();
242 it != paths_to_keep.end();
243 ++it) {
244 if (root.IsParent(*it) && base::PathExists(*it))
245 valid_paths_to_keep.push_back(*it);
248 // If none of the |paths_to_keep| are valid anymore then we just whack the
249 // root and be done with it. Otherwise, signal garbage collection and do
250 // a best-effort delete of the on-disk structures.
251 if (valid_paths_to_keep.empty()) {
252 base::DeleteFile(root, true);
253 return;
255 closure_runner->PostTask(FROM_HERE, on_gc_required);
257 // Otherwise, start at the root and delete everything that is not in
258 // |valid_paths_to_keep|.
259 std::vector<base::FilePath> paths_to_consider;
260 paths_to_consider.push_back(root);
261 while(!paths_to_consider.empty()) {
262 base::FilePath path = paths_to_consider.back();
263 paths_to_consider.pop_back();
264 ObliterateOneDirectory(path, valid_paths_to_keep, &paths_to_consider);
268 // Ensures each path in |active_paths| is a direct child of storage_root.
269 void NormalizeActivePaths(const base::FilePath& storage_root,
270 base::hash_set<base::FilePath>* active_paths) {
271 base::hash_set<base::FilePath> normalized_active_paths;
273 for (base::hash_set<base::FilePath>::iterator iter = active_paths->begin();
274 iter != active_paths->end(); ++iter) {
275 base::FilePath relative_path;
276 if (!storage_root.AppendRelativePath(*iter, &relative_path))
277 continue;
279 std::vector<base::FilePath::StringType> components;
280 relative_path.GetComponents(&components);
282 DCHECK(!relative_path.empty());
283 normalized_active_paths.insert(storage_root.Append(components.front()));
286 active_paths->swap(normalized_active_paths);
289 // Deletes all entries inside the |storage_root| that are not in the
290 // |active_paths|. Deletion is done in 2 steps:
292 // (1) Moving all garbage collected paths into a trash directory.
293 // (2) Asynchronously deleting the trash directory.
295 // The deletion is asynchronous because after (1) completes, calling code can
296 // safely continue to use the paths that had just been garbage collected
297 // without fear of race conditions.
299 // This code also ignores failed moves rather than attempting a smarter retry.
300 // Moves shouldn't fail here unless there is some out-of-band error (eg.,
301 // FS corruption). Retry logic is dangerous in the general case because
302 // there is not necessarily a guaranteed case where the logic may succeed.
304 // This function is still named BlockingGarbageCollect() because it does
305 // execute a few filesystem operations synchronously.
306 void BlockingGarbageCollect(
307 const base::FilePath& storage_root,
308 const scoped_refptr<base::TaskRunner>& file_access_runner,
309 scoped_ptr<base::hash_set<base::FilePath> > active_paths) {
310 CHECK(storage_root.IsAbsolute());
312 NormalizeActivePaths(storage_root, active_paths.get());
314 base::FileEnumerator enumerator(storage_root, false, kAllFileTypes);
315 base::FilePath trash_directory;
316 if (!base::CreateTemporaryDirInDir(storage_root, kTrashDirname,
317 &trash_directory)) {
318 // Unable to continue without creating the trash directory so give up.
319 return;
321 for (base::FilePath path = enumerator.Next(); !path.empty();
322 path = enumerator.Next()) {
323 if (active_paths->find(path) == active_paths->end() &&
324 path != trash_directory) {
325 // Since |trash_directory| is unique for each run of this function there
326 // can be no colllisions on the move.
327 base::Move(path, trash_directory.Append(path.BaseName()));
331 file_access_runner->PostTask(
332 FROM_HERE,
333 base::Bind(base::IgnoreResult(&base::DeleteFile), trash_directory, true));
336 } // namespace
338 // static
339 base::FilePath StoragePartitionImplMap::GetStoragePartitionPath(
340 const std::string& partition_domain,
341 const std::string& partition_name) {
342 if (partition_domain.empty())
343 return base::FilePath();
345 base::FilePath path = GetStoragePartitionDomainPath(partition_domain);
347 // TODO(ajwong): Mangle in-memory into this somehow, either by putting
348 // it into the partition_name, or by manually adding another path component
349 // here. Otherwise, it's possible to have an in-memory StoragePartition and
350 // a persistent one that return the same FilePath for GetPath().
351 if (!partition_name.empty()) {
352 // For analysis of why we can ignore collisions, see the comment above
353 // kPartitionNameHashBytes.
354 char buffer[kPartitionNameHashBytes];
355 crypto::SHA256HashString(partition_name, &buffer[0],
356 sizeof(buffer));
357 return path.AppendASCII(base::HexEncode(buffer, sizeof(buffer)));
360 return path.Append(kDefaultPartitionDirname);
363 StoragePartitionImplMap::StoragePartitionImplMap(
364 BrowserContext* browser_context)
365 : browser_context_(browser_context),
366 resource_context_initialized_(false) {
367 // Doing here instead of initializer list cause it's just too ugly to read.
368 base::SequencedWorkerPool* blocking_pool = BrowserThread::GetBlockingPool();
369 file_access_runner_ =
370 blocking_pool->GetSequencedTaskRunner(blocking_pool->GetSequenceToken());
373 StoragePartitionImplMap::~StoragePartitionImplMap() {
374 STLDeleteContainerPairSecondPointers(partitions_.begin(),
375 partitions_.end());
378 StoragePartitionImpl* StoragePartitionImplMap::Get(
379 const std::string& partition_domain,
380 const std::string& partition_name,
381 bool in_memory) {
382 // Find the previously created partition if it's available.
383 StoragePartitionConfig partition_config(
384 partition_domain, partition_name, in_memory);
386 PartitionMap::const_iterator it = partitions_.find(partition_config);
387 if (it != partitions_.end())
388 return it->second;
390 base::FilePath partition_path =
391 browser_context_->GetPath().Append(
392 GetStoragePartitionPath(partition_domain, partition_name));
393 StoragePartitionImpl* partition =
394 StoragePartitionImpl::Create(browser_context_, in_memory,
395 partition_path);
396 partitions_[partition_config] = partition;
398 ChromeBlobStorageContext* blob_storage_context =
399 ChromeBlobStorageContext::GetFor(browser_context_);
400 StreamContext* stream_context = StreamContext::GetFor(browser_context_);
401 ProtocolHandlerMap protocol_handlers;
402 protocol_handlers[url::kBlobScheme] =
403 linked_ptr<net::URLRequestJobFactory::ProtocolHandler>(
404 new BlobProtocolHandler(blob_storage_context,
405 stream_context,
406 partition->GetFileSystemContext()));
407 protocol_handlers[url::kFileSystemScheme] =
408 linked_ptr<net::URLRequestJobFactory::ProtocolHandler>(
409 CreateFileSystemProtocolHandler(partition_domain,
410 partition->GetFileSystemContext()));
411 protocol_handlers[kChromeUIScheme] =
412 linked_ptr<net::URLRequestJobFactory::ProtocolHandler>(
413 URLDataManagerBackend::CreateProtocolHandler(
414 browser_context_->GetResourceContext(),
415 browser_context_->IsOffTheRecord(),
416 partition->GetAppCacheService(),
417 blob_storage_context));
418 std::vector<std::string> additional_webui_schemes;
419 GetContentClient()->browser()->GetAdditionalWebUISchemes(
420 &additional_webui_schemes);
421 for (std::vector<std::string>::const_iterator it =
422 additional_webui_schemes.begin();
423 it != additional_webui_schemes.end();
424 ++it) {
425 protocol_handlers[*it] =
426 linked_ptr<net::URLRequestJobFactory::ProtocolHandler>(
427 URLDataManagerBackend::CreateProtocolHandler(
428 browser_context_->GetResourceContext(),
429 browser_context_->IsOffTheRecord(),
430 partition->GetAppCacheService(),
431 blob_storage_context));
433 protocol_handlers[kChromeDevToolsScheme] =
434 linked_ptr<net::URLRequestJobFactory::ProtocolHandler>(
435 CreateDevToolsProtocolHandler(browser_context_->GetResourceContext(),
436 browser_context_->IsOffTheRecord()));
438 URLRequestInterceptorScopedVector request_interceptors;
439 request_interceptors.push_back(
440 ServiceWorkerRequestHandler::CreateInterceptor().release());
442 // These calls must happen after StoragePartitionImpl::Create().
443 if (partition_domain.empty()) {
444 partition->SetURLRequestContext(
445 GetContentClient()->browser()->CreateRequestContext(
446 browser_context_,
447 &protocol_handlers,
448 request_interceptors.Pass()));
449 } else {
450 partition->SetURLRequestContext(
451 GetContentClient()->browser()->CreateRequestContextForStoragePartition(
452 browser_context_,
453 partition->GetPath(),
454 in_memory,
455 &protocol_handlers,
456 request_interceptors.Pass()));
458 partition->SetMediaURLRequestContext(
459 partition_domain.empty() ?
460 browser_context_->GetMediaRequestContext() :
461 browser_context_->GetMediaRequestContextForStoragePartition(
462 partition->GetPath(), in_memory));
464 PostCreateInitialization(partition, in_memory);
466 return partition;
469 void StoragePartitionImplMap::AsyncObliterate(
470 const GURL& site,
471 const base::Closure& on_gc_required) {
472 // This method should avoid creating any StoragePartition (which would
473 // create more open file handles) so that it can delete as much of the
474 // data off disk as possible.
475 std::string partition_domain;
476 std::string partition_name;
477 bool in_memory = false;
478 GetContentClient()->browser()->GetStoragePartitionConfigForSite(
479 browser_context_, site, false, &partition_domain,
480 &partition_name, &in_memory);
482 // Find the active partitions for the domain. Because these partitions are
483 // active, it is not possible to just delete the directories that contain
484 // the backing data structures without causing the browser to crash. Instead,
485 // of deleteing the directory, we tell each storage context later to
486 // remove any data they have saved. This will leave the directory structure
487 // intact but it will only contain empty databases.
488 std::vector<StoragePartitionImpl*> active_partitions;
489 std::vector<base::FilePath> paths_to_keep;
490 for (PartitionMap::const_iterator it = partitions_.begin();
491 it != partitions_.end();
492 ++it) {
493 const StoragePartitionConfig& config = it->first;
494 if (config.partition_domain == partition_domain) {
495 it->second->ClearData(
496 // All except shader cache.
497 ~StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE,
498 StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL,
499 GURL(),
500 StoragePartition::OriginMatcherFunction(),
501 base::Time(), base::Time::Max(),
502 base::Bind(&base::DoNothing));
503 if (!config.in_memory) {
504 paths_to_keep.push_back(it->second->GetPath());
509 // Start a best-effort delete of the on-disk storage excluding paths that are
510 // known to still be in use. This is to delete any previously created
511 // StoragePartition state that just happens to not have been used during this
512 // run of the browser.
513 base::FilePath domain_root = browser_context_->GetPath().Append(
514 GetStoragePartitionDomainPath(partition_domain));
516 BrowserThread::PostBlockingPoolTask(
517 FROM_HERE,
518 base::Bind(&BlockingObliteratePath, browser_context_->GetPath(),
519 domain_root, paths_to_keep,
520 base::MessageLoopProxy::current(), on_gc_required));
523 void StoragePartitionImplMap::GarbageCollect(
524 scoped_ptr<base::hash_set<base::FilePath> > active_paths,
525 const base::Closure& done) {
526 // Include all paths for current StoragePartitions in the active_paths since
527 // they cannot be deleted safely.
528 for (PartitionMap::const_iterator it = partitions_.begin();
529 it != partitions_.end();
530 ++it) {
531 const StoragePartitionConfig& config = it->first;
532 if (!config.in_memory)
533 active_paths->insert(it->second->GetPath());
536 // Find the directory holding the StoragePartitions and delete everything in
537 // there that isn't considered active.
538 base::FilePath storage_root = browser_context_->GetPath().Append(
539 GetStoragePartitionDomainPath(std::string()));
540 file_access_runner_->PostTaskAndReply(
541 FROM_HERE,
542 base::Bind(&BlockingGarbageCollect, storage_root,
543 file_access_runner_,
544 base::Passed(&active_paths)),
545 done);
548 void StoragePartitionImplMap::ForEach(
549 const BrowserContext::StoragePartitionCallback& callback) {
550 for (PartitionMap::const_iterator it = partitions_.begin();
551 it != partitions_.end();
552 ++it) {
553 callback.Run(it->second);
557 void StoragePartitionImplMap::PostCreateInitialization(
558 StoragePartitionImpl* partition,
559 bool in_memory) {
560 // TODO(ajwong): ResourceContexts no longer have any storage related state.
561 // We should move this into a place where it is called once per
562 // BrowserContext creation rather than piggybacking off the default context
563 // creation.
564 // Note: moving this into Get() before partitions_[] is set causes reentrency.
565 if (!resource_context_initialized_) {
566 resource_context_initialized_ = true;
567 InitializeResourceContext(browser_context_);
570 // Check first to avoid memory leak in unittests.
571 if (BrowserThread::IsMessageLoopValid(BrowserThread::IO)) {
572 BrowserThread::PostTask(
573 BrowserThread::IO, FROM_HERE,
574 base::Bind(&ChromeAppCacheService::InitializeOnIOThread,
575 partition->GetAppCacheService(),
576 in_memory ? base::FilePath() :
577 partition->GetPath().Append(kAppCacheDirname),
578 browser_context_->GetResourceContext(),
579 make_scoped_refptr(partition->GetURLRequestContext()),
580 make_scoped_refptr(
581 browser_context_->GetSpecialStoragePolicy())));
583 BrowserThread::PostTask(
584 BrowserThread::IO,
585 FROM_HERE,
586 base::Bind(&ServiceWorkerContextWrapper::SetBlobParametersForCache,
587 partition->GetServiceWorkerContext(),
588 make_scoped_refptr(partition->GetURLRequestContext()),
589 make_scoped_refptr(
590 ChromeBlobStorageContext::GetFor(browser_context_))));
592 // We do not call InitializeURLRequestContext() for media contexts because,
593 // other than the HTTP cache, the media contexts share the same backing
594 // objects as their associated "normal" request context. Thus, the previous
595 // call serves to initialize the media request context for this storage
596 // partition as well.
600 } // namespace content