OLD | NEW |
1 // Copyright 2016 The Chromium Authors. All rights reserved. | 1 // Copyright 2016 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "chromeos/printing/ppd_cache.h" | 5 #include "chromeos/printing/ppd_cache.h" |
6 | 6 |
7 #include <utility> | 7 #include <utility> |
8 #include <vector> | 8 #include <vector> |
9 | 9 |
10 #include "base/bind.h" | 10 #include "base/bind.h" |
11 #include "base/files/file_util.h" | 11 #include "base/files/file_util.h" |
12 #include "base/json/json_parser.h" | 12 #include "base/json/json_parser.h" |
13 #include "base/json/json_writer.h" | 13 #include "base/json/json_writer.h" |
14 #include "base/memory/ptr_util.h" | 14 #include "base/memory/ptr_util.h" |
15 #include "base/strings/string_number_conversions.h" | 15 #include "base/strings/string_number_conversions.h" |
16 #include "base/strings/string_util.h" | 16 #include "base/strings/string_util.h" |
17 #include "base/synchronization/lock.h" | 17 #include "base/synchronization/lock.h" |
| 18 #include "base/task_runner_util.h" |
| 19 #include "base/task_scheduler/post_task.h" |
18 #include "base/threading/sequenced_task_runner_handle.h" | 20 #include "base/threading/sequenced_task_runner_handle.h" |
19 #include "base/threading/thread_restrictions.h" | 21 #include "base/threading/thread_restrictions.h" |
20 #include "base/time/time.h" | 22 #include "base/time/time.h" |
21 #include "base/values.h" | 23 #include "base/values.h" |
22 #include "chromeos/printing/printing_constants.h" | 24 #include "chromeos/printing/printing_constants.h" |
23 #include "crypto/sha2.h" | 25 #include "crypto/sha2.h" |
24 #include "net/base/io_buffer.h" | 26 #include "net/base/io_buffer.h" |
25 #include "net/filter/gzip_header.h" | 27 #include "net/filter/gzip_header.h" |
26 | 28 |
27 namespace chromeos { | 29 namespace chromeos { |
28 namespace printing { | 30 namespace printing { |
29 namespace { | 31 namespace { |
30 | 32 |
| 33 // Return the (full) path to the file we expect to find the given key at. |
| 34 base::FilePath FilePathForKey(const base::FilePath& base_dir, |
| 35 const std::string& key) { |
| 36 std::string hashed_key = crypto::SHA256HashString(key); |
| 37 return base_dir.Append(base::HexEncode(hashed_key.data(), hashed_key.size())); |
| 38 } |
| 39 |
| 40 // If the cache doesn't already exist, create it. |
| 41 void MaybeCreateCache(const base::FilePath& base_dir) { |
| 42 if (!base::PathExists(base_dir)) { |
| 43 base::CreateDirectory(base_dir); |
| 44 } |
| 45 } |
| 46 |
| 47 // Find implementation, blocks on file access. Must be run on a thread that |
| 48 // allows I/O. |
| 49 PpdCache::FindResult FindImpl(const base::FilePath& cache_dir, |
| 50 const std::string& key) { |
| 51 base::ThreadRestrictions::AssertIOAllowed(); |
| 52 |
| 53 PpdCache::FindResult result; |
| 54 result.success = false; |
| 55 if (!base::PathExists(cache_dir)) { |
| 56 // If the cache dir was missing, we'll miss anyway. |
| 57 return result; |
| 58 } |
| 59 |
| 60 base::File file(FilePathForKey(cache_dir, key), |
| 61 base::File::FLAG_OPEN | base::File::FLAG_READ); |
| 62 |
| 63 if (file.IsValid()) { |
| 64 int64_t len = file.GetLength(); |
| 65 if (len >= static_cast<int64_t>(crypto::kSHA256Length) && |
| 66 len <= static_cast<int64_t>(kMaxPpdSizeBytes) + |
| 67 static_cast<int64_t>(crypto::kSHA256Length)) { |
| 68 std::unique_ptr<char[]> buf(new char[len]); |
| 69 if (file.ReadAtCurrentPos(buf.get(), len) == len) { |
| 70 base::StringPiece contents(buf.get(), len - crypto::kSHA256Length); |
| 71 base::StringPiece checksum(buf.get() + len - crypto::kSHA256Length, |
| 72 crypto::kSHA256Length); |
| 73 if (crypto::SHA256HashString(contents) == checksum) { |
| 74 base::File::Info info; |
| 75 if (file.GetInfo(&info)) { |
| 76 result.success = true; |
| 77 result.age = base::Time::Now() - info.last_modified; |
| 78 contents.CopyToString(&result.contents); |
| 79 } |
| 80 } else { |
| 81 LOG(ERROR) << "Bad checksum for cache key " << key; |
| 82 } |
| 83 } |
| 84 } |
| 85 } |
| 86 |
| 87 return result; |
| 88 } |
| 89 |
| 90 // Store implementation, blocks on file access. Must be run on a thread that |
| 91 // allows I/O. |
| 92 void StoreImpl(const base::FilePath& cache_dir, |
| 93 const std::string& key, |
| 94 const std::string& contents) { |
| 95 base::ThreadRestrictions::AssertIOAllowed(); |
| 96 |
| 97 MaybeCreateCache(cache_dir); |
| 98 if (contents.size() > kMaxPpdSizeBytes) { |
| 99 LOG(ERROR) << "Ignoring attempt to cache large object"; |
| 100 } else { |
| 101 auto path = FilePathForKey(cache_dir, key); |
| 102 base::File file(path, |
| 103 base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); |
| 104 std::string checksum = crypto::SHA256HashString(contents); |
| 105 if (!file.IsValid() || |
| 106 file.WriteAtCurrentPos(contents.data(), contents.size()) != |
| 107 static_cast<int>(contents.size()) || |
| 108 file.WriteAtCurrentPos(checksum.data(), checksum.size()) != |
| 109 static_cast<int>(checksum.size())) { |
| 110 LOG(ERROR) << "Failed to create ppd cache file"; |
| 111 file.Close(); |
| 112 if (!base::DeleteFile(path, false)) { |
| 113 LOG(ERROR) << "Failed to cleanup failed creation."; |
| 114 } |
| 115 } |
| 116 } |
| 117 } |
| 118 |
31 class PpdCacheImpl : public PpdCache { | 119 class PpdCacheImpl : public PpdCache { |
32 public: | 120 public: |
33 PpdCacheImpl(const base::FilePath& cache_base_dir, | 121 explicit PpdCacheImpl(const base::FilePath& cache_base_dir) |
34 const scoped_refptr<base::SequencedTaskRunner>& disk_task_runner) | 122 : cache_base_dir_(cache_base_dir), |
35 : cache_base_dir_(cache_base_dir), disk_task_runner_(disk_task_runner) {} | 123 fetch_task_runner_(base::CreateSequencedTaskRunnerWithTraits( |
| 124 {base::TaskPriority::USER_VISIBLE, base::MayBlock(), |
| 125 base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), |
| 126 store_task_runner_(base::CreateSequencedTaskRunnerWithTraits( |
| 127 {base::TaskPriority::BACKGROUND, base::MayBlock(), |
| 128 base::TaskShutdownBehavior::BLOCK_SHUTDOWN})) {} |
36 | 129 |
37 // Public API functions. | 130 // Public API functions. |
38 void Find(const std::string& key, const FindCallback& cb) override { | 131 void Find(const std::string& key, const FindCallback& cb) override { |
39 // Ensure the cache lives until the op is over. | 132 base::PostTaskAndReplyWithResult( |
40 AddRef(); | 133 fetch_task_runner_.get(), FROM_HERE, |
41 ++inflight_ops_; | 134 base::Bind(&FindImpl, cache_base_dir_, key), cb); |
42 disk_task_runner_->PostTask( | |
43 FROM_HERE, base::Bind(&PpdCacheImpl::FindImpl, this, key, | |
44 base::SequencedTaskRunnerHandle::Get(), cb)); | |
45 } | 135 } |
46 | 136 |
47 // Store the given contents at the given key. If cb is non-null, it will | 137 // Store the given contents at the given key. If cb is non-null, it will |
48 // be invoked on completion. | 138 // be invoked on completion. |
49 void Store(const std::string& key, | 139 void Store(const std::string& key, |
50 const std::string& contents, | 140 const std::string& contents, |
51 const base::Callback<void()>& cb) override { | 141 const base::Closure& cb) override { |
52 AddRef(); | 142 store_task_runner_->PostTaskAndReply( |
53 ++inflight_ops_; | 143 FROM_HERE, base::Bind(&StoreImpl, cache_base_dir_, key, contents), cb); |
54 disk_task_runner_->PostTask( | |
55 FROM_HERE, base::Bind(&PpdCacheImpl::StoreImpl, this, key, contents, | |
56 base::SequencedTaskRunnerHandle::Get(), cb)); | |
57 } | 144 } |
58 | 145 |
59 bool Idle() const override { return inflight_ops_ == 0; } | |
60 | |
61 private: | 146 private: |
62 ~PpdCacheImpl() override {} | 147 ~PpdCacheImpl() override {} |
63 | 148 |
64 // If the cache doesn't already exist, create it. | |
65 void MaybeCreateCache() { | |
66 if (!base::PathExists(cache_base_dir_)) { | |
67 base::CreateDirectory(cache_base_dir_); | |
68 } | |
69 } | |
70 | |
71 // Find implementation, runs on the i/o thread. | |
72 void FindImpl(const std::string& key, | |
73 const scoped_refptr<base::SequencedTaskRunner>& callback_runner, | |
74 const FindCallback& cb) { | |
75 base::ThreadRestrictions::AssertIOAllowed(); | |
76 FindResult result; | |
77 result.success = false; | |
78 MaybeCreateCache(); | |
79 base::File file(FilePathForKey(key), | |
80 base::File::FLAG_OPEN | base::File::FLAG_READ); | |
81 | |
82 if (file.IsValid()) { | |
83 int64_t len = file.GetLength(); | |
84 if (len >= static_cast<int64_t>(crypto::kSHA256Length) && | |
85 len <= static_cast<int64_t>(kMaxPpdSizeBytes) + | |
86 static_cast<int64_t>(crypto::kSHA256Length)) { | |
87 std::unique_ptr<char[]> buf(new char[len]); | |
88 if (file.ReadAtCurrentPos(buf.get(), len) == len) { | |
89 base::StringPiece contents(buf.get(), len - crypto::kSHA256Length); | |
90 base::StringPiece checksum(buf.get() + len - crypto::kSHA256Length, | |
91 crypto::kSHA256Length); | |
92 if (crypto::SHA256HashString(contents) == checksum) { | |
93 base::File::Info info; | |
94 if (file.GetInfo(&info)) { | |
95 result.success = true; | |
96 result.age = base::Time::Now() - info.last_modified; | |
97 contents.CopyToString(&result.contents); | |
98 } | |
99 } else { | |
100 LOG(ERROR) << "Bad checksum for cache key " << key; | |
101 } | |
102 } | |
103 } | |
104 } | |
105 callback_runner->PostTask(FROM_HERE, | |
106 base::Bind(&PpdCacheImpl::ReplyAndRelease, this, | |
107 base::Bind(cb, result))); | |
108 } | |
109 | |
110 // If |cb| is non-null, invoke it on this thread, then decrement the refcount. | |
111 void ReplyAndRelease(const base::Callback<void()>& cb) { | |
112 if (!cb.is_null()) { | |
113 cb.Run(); | |
114 } | |
115 --inflight_ops_; | |
116 Release(); | |
117 // Object may be destroyed here, so no further access to object data | |
118 // allowed. | |
119 } | |
120 | |
121 // Store implementation, runs on the i/o thread. | |
122 void StoreImpl( | |
123 const std::string& key, | |
124 const std::string& contents, | |
125 const scoped_refptr<base::SequencedTaskRunner>& callback_runner, | |
126 const base::Callback<void()> cb) { | |
127 base::ThreadRestrictions::AssertIOAllowed(); | |
128 MaybeCreateCache(); | |
129 if (contents.size() > kMaxPpdSizeBytes) { | |
130 LOG(ERROR) << "Ignoring attempt to cache large object"; | |
131 } else { | |
132 auto path = FilePathForKey(key); | |
133 base::File file(path, | |
134 base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); | |
135 std::string checksum = crypto::SHA256HashString(contents); | |
136 if (!file.IsValid() || | |
137 file.WriteAtCurrentPos(contents.data(), contents.size()) != | |
138 static_cast<int>(contents.size()) || | |
139 file.WriteAtCurrentPos(checksum.data(), checksum.size()) != | |
140 static_cast<int>(checksum.size())) { | |
141 LOG(ERROR) << "Failed to create ppd cache file"; | |
142 file.Close(); | |
143 if (!base::DeleteFile(path, false)) { | |
144 LOG(ERROR) << "Failed to cleanup failed creation."; | |
145 } | |
146 } | |
147 } | |
148 callback_runner->PostTask( | |
149 FROM_HERE, base::Bind(&PpdCacheImpl::ReplyAndRelease, this, cb)); | |
150 } | |
151 | |
152 // Return the (full) path to the file we expect to find the given key at. | |
153 base::FilePath FilePathForKey(const std::string& key) { | |
154 std::string hashed_key = crypto::SHA256HashString(key); | |
155 return cache_base_dir_.Append( | |
156 base::HexEncode(hashed_key.data(), hashed_key.size())); | |
157 } | |
158 | |
159 int inflight_ops_ = 0; | |
160 | |
161 base::FilePath cache_base_dir_; | 149 base::FilePath cache_base_dir_; |
162 scoped_refptr<base::SequencedTaskRunner> disk_task_runner_; | 150 scoped_refptr<base::SequencedTaskRunner> fetch_task_runner_; |
| 151 scoped_refptr<base::SequencedTaskRunner> store_task_runner_; |
163 | 152 |
164 DISALLOW_COPY_AND_ASSIGN(PpdCacheImpl); | 153 DISALLOW_COPY_AND_ASSIGN(PpdCacheImpl); |
165 }; | 154 }; |
166 | 155 |
167 } // namespace | 156 } // namespace |
168 | 157 |
169 // static | 158 // static |
170 scoped_refptr<PpdCache> PpdCache::Create( | 159 scoped_refptr<PpdCache> PpdCache::Create(const base::FilePath& cache_base_dir) { |
171 const base::FilePath& cache_base_dir, | 160 return scoped_refptr<PpdCache>(new PpdCacheImpl(cache_base_dir)); |
172 scoped_refptr<base::SequencedTaskRunner> disk_task_runner) { | |
173 return scoped_refptr<PpdCache>( | |
174 new PpdCacheImpl(cache_base_dir, disk_task_runner)); | |
175 } | 161 } |
176 | 162 |
177 } // namespace printing | 163 } // namespace printing |
178 } // namespace chromeos | 164 } // namespace chromeos |
OLD | NEW |