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