1 // Copyright 2013 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 "chrome/browser/extensions/api/image_writer_private/operation.h"
7 #include "base/file_util.h"
8 #include "base/files/file_enumerator.h"
9 #include "base/threading/worker_pool.h"
10 #include "chrome/browser/extensions/api/image_writer_private/error_messages.h"
11 #include "chrome/browser/extensions/api/image_writer_private/operation_manager.h"
12 #include "content/public/browser/browser_thread.h"
14 namespace extensions {
15 namespace image_writer {
17 using content::BrowserThread;
19 const int kMD5BufferSize = 1024;
20 #if defined(OS_CHROMEOS)
21 // Chrome OS only has a 1 GB temporary partition. This is too small to hold our
22 // unzipped image. Fortunately we mount part of the temporary partition under
24 const char kChromeOSTempRoot[] = "/var/tmp";
27 Operation::Operation(base::WeakPtr<OperationManager> manager,
28 const ExtensionId& extension_id,
29 const std::string& device_path)
31 extension_id_(extension_id),
33 device_path_(base::FilePath::FromUTF8Unsafe(device_path)),
35 device_path_(device_path),
37 stage_(image_writer_api::STAGE_UNKNOWN),
41 Operation::~Operation() {}
43 void Operation::Cancel() {
44 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
46 stage_ = image_writer_api::STAGE_NONE;
51 void Operation::Abort() {
52 Error(error::kAborted);
55 int Operation::GetProgress() {
59 image_writer_api::Stage Operation::GetStage() {
63 #if !defined(OS_CHROMEOS)
64 void Operation::SetUtilityClientForTesting(
65 scoped_refptr<ImageWriterUtilityClient> client) {
66 image_writer_client_ = client;
68 base::Bind(&ImageWriterUtilityClient::Shutdown, image_writer_client_));
72 void Operation::Start() {
73 #if defined(OS_CHROMEOS)
74 if (!temp_dir_.CreateUniqueTempDirUnderPath(
75 base::FilePath(kChromeOSTempRoot))) {
77 if (!temp_dir_.CreateUniqueTempDir()) {
79 Error(error::kTempDirError);
84 base::Bind(base::IgnoreResult(&base::ScopedTempDir::Delete),
85 base::Unretained(&temp_dir_)));
90 void Operation::Unzip(const base::Closure& continuation) {
91 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
96 if (image_path_.Extension() != FILE_PATH_LITERAL(".zip")) {
97 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, continuation);
101 SetStage(image_writer_api::STAGE_UNZIP);
103 if (!(zip_reader_.Open(image_path_) && zip_reader_.AdvanceToNextEntry() &&
104 zip_reader_.OpenCurrentEntryInZip())) {
105 Error(error::kUnzipGenericError);
109 if (zip_reader_.HasMore()) {
110 Error(error::kUnzipInvalidArchive);
114 // Create a new target to unzip to. The original file is opened by the
116 zip::ZipReader::EntryInfo* entry_info = zip_reader_.current_entry_info();
118 image_path_ = temp_dir_.path().Append(entry_info->file_path().BaseName());
120 Error(error::kTempDirError);
124 zip_reader_.ExtractCurrentEntryToFilePathAsync(
126 base::Bind(&Operation::CompleteAndContinue, this, continuation),
127 base::Bind(&Operation::OnUnzipFailure, this),
128 base::Bind(&Operation::OnUnzipProgress,
130 zip_reader_.current_entry_info()->original_size()));
133 void Operation::Finish() {
134 if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
135 BrowserThread::PostTask(
136 BrowserThread::FILE, FROM_HERE, base::Bind(&Operation::Finish, this));
142 BrowserThread::PostTask(
145 base::Bind(&OperationManager::OnComplete, manager_, extension_id_));
148 void Operation::Error(const std::string& error_message) {
149 if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
150 BrowserThread::PostTask(BrowserThread::FILE,
152 base::Bind(&Operation::Error, this, error_message));
156 BrowserThread::PostTask(
159 base::Bind(&OperationManager::OnError,
169 void Operation::SetProgress(int progress) {
170 if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
171 BrowserThread::PostTask(
174 base::Bind(&Operation::SetProgress,
180 if (progress <= progress_) {
188 progress_ = progress;
190 BrowserThread::PostTask(BrowserThread::UI,
192 base::Bind(&OperationManager::OnProgress,
199 void Operation::SetStage(image_writer_api::Stage stage) {
200 if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
201 BrowserThread::PostTask(
204 base::Bind(&Operation::SetStage,
217 BrowserThread::PostTask(
220 base::Bind(&OperationManager::OnProgress,
227 bool Operation::IsCancelled() {
228 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
230 return stage_ == image_writer_api::STAGE_NONE;
233 void Operation::AddCleanUpFunction(const base::Closure& callback) {
234 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
235 cleanup_functions_.push_back(callback);
238 void Operation::CompleteAndContinue(const base::Closure& continuation) {
239 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
240 SetProgress(kProgressComplete);
241 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, continuation);
244 #if !defined(OS_CHROMEOS)
245 void Operation::StartUtilityClient() {
246 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
247 if (!image_writer_client_) {
248 image_writer_client_ = new ImageWriterUtilityClient();
249 AddCleanUpFunction(base::Bind(&Operation::StopUtilityClient, this));
253 void Operation::StopUtilityClient() {
254 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
255 BrowserThread::PostTask(
258 base::Bind(&ImageWriterUtilityClient::Shutdown, image_writer_client_));
261 void Operation::WriteImageProgress(int64 total_bytes, int64 curr_bytes) {
262 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
267 int progress = kProgressComplete * curr_bytes / total_bytes;
269 if (progress > GetProgress()) {
270 SetProgress(progress);
275 void Operation::GetMD5SumOfFile(
276 const base::FilePath& file_path,
280 const base::Callback<void(const std::string&)>& callback) {
285 base::MD5Init(&md5_context_);
287 base::File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
288 if (!file.IsValid()) {
289 Error(error::kImageOpenError);
293 if (file_size <= 0) {
294 file_size = file.GetLength();
296 Error(error::kImageOpenError);
301 BrowserThread::PostTask(BrowserThread::FILE,
303 base::Bind(&Operation::MD5Chunk,
313 void Operation::MD5Chunk(
315 int64 bytes_processed,
319 const base::Callback<void(const std::string&)>& callback) {
323 CHECK_LE(bytes_processed, bytes_total);
325 scoped_ptr<char[]> buffer(new char[kMD5BufferSize]);
326 int read_size = std::min(bytes_total - bytes_processed,
327 static_cast<int64>(kMD5BufferSize));
329 if (read_size == 0) {
330 // Nothing to read, we are done.
331 base::MD5Digest digest;
332 base::MD5Final(&digest, &md5_context_);
333 callback.Run(base::MD5DigestToBase16(digest));
335 int len = file.Read(bytes_processed, buffer.get(), read_size);
337 if (len == read_size) {
339 base::MD5Update(&md5_context_, base::StringPiece(buffer.get(), len));
341 ((bytes_processed + len) * progress_scale) / bytes_total +
343 SetProgress(percent_curr);
345 BrowserThread::PostTask(BrowserThread::FILE,
347 base::Bind(&Operation::MD5Chunk,
350 bytes_processed + len,
355 // Skip closing the file.
358 // We didn't read the bytes we expected.
359 Error(error::kHashReadError);
364 void Operation::OnUnzipFailure() {
365 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
366 Error(error::kUnzipGenericError);
369 void Operation::OnUnzipProgress(int64 total_bytes, int64 progress_bytes) {
370 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
372 int progress_percent = kProgressComplete * progress_bytes / total_bytes;
373 SetProgress(progress_percent);
376 void Operation::CleanUp() {
377 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
378 for (std::vector<base::Closure>::iterator it = cleanup_functions_.begin();
379 it != cleanup_functions_.end();
383 cleanup_functions_.clear();
386 } // namespace image_writer
387 } // namespace extensions