summaryrefslogtreecommitdiff
path: root/chromium/components/services/unzip/unzipper_impl.cc
blob: ff49fcff06767b2f479f62ac912972a972feb512 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/services/unzip/unzipper_impl.h"

#include <string>
#include <utility>

#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/files/file.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "components/services/filesystem/public/mojom/directory.mojom.h"
#include "third_party/ced/src/compact_enc_det/compact_enc_det.h"
#include "third_party/zlib/google/redact.h"
#include "third_party/zlib/google/zip.h"
#include "third_party/zlib/google/zip_reader.h"

namespace unzip {
namespace {

// Modifies output_dir to point to the final directory.
bool CreateDirectory(filesystem::mojom::Directory* output_dir,
                     const base::FilePath& path) {
  base::File::Error err = base::File::Error::FILE_OK;
  return output_dir->OpenDirectory(path.AsUTF8Unsafe(), mojo::NullReceiver(),
                                   filesystem::mojom::kFlagOpenAlways, &err) &&
         err == base::File::Error::FILE_OK;
}

// A file writer that uses a mojom::Directory.
class Writer : public zip::FileWriterDelegate {
 public:
  Writer(mojo::Remote<filesystem::mojom::Directory> output_dir,
         base::FilePath path)
      : FileWriterDelegate(base::File()),
        owned_output_dir_(std::move(output_dir)),
        output_dir_(owned_output_dir_.get()),
        path_(std::move(path)) {
    DCHECK(output_dir_);
  }

  Writer(filesystem::mojom::Directory* output_dir, base::FilePath path)
      : FileWriterDelegate(base::File()),
        output_dir_(output_dir),
        path_(std::move(path)) {
    DCHECK(output_dir_);
  }

  // Creates the output file.
  bool PrepareOutput() override {
    if (base::File::Error err;
        !output_dir_->OpenFileHandle(
            path_.AsUTF8Unsafe(),
            filesystem::mojom::kFlagCreate | filesystem::mojom::kFlagWrite |
                filesystem::mojom::kFlagWriteAttributes,
            &err, &owned_file_) ||
        err != base::File::Error::FILE_OK) {
      LOG(ERROR) << "Cannot create extracted file " << zip::Redact(path_);
      return false;
    }

    return FileWriterDelegate::PrepareOutput();
  }

  // Deletes the output file.
  void OnError() override {
    FileWriterDelegate::OnError();
    owned_file_.Close();

    if (base::File::Error err;
        !output_dir_->Delete(path_.AsUTF8Unsafe(), 0, &err) ||
        err != base::File::Error::FILE_OK) {
      LOG(ERROR) << "Cannot delete extracted file " << zip::Redact(path_);
    }
  }

 private:
  const mojo::Remote<filesystem::mojom::Directory> owned_output_dir_;
  const raw_ptr<filesystem::mojom::Directory> output_dir_;
  const base::FilePath path_;
};

std::unique_ptr<zip::WriterDelegate> MakeFileWriterDelegate(
    filesystem::mojom::Directory* output_dir,
    const base::FilePath& path) {
  if (path == path.BaseName())
    return std::make_unique<Writer>(output_dir, path);

  mojo::Remote<filesystem::mojom::Directory> parent;

  if (base::File::Error err;
      !output_dir->OpenDirectory(path.DirName().AsUTF8Unsafe(),
                                 parent.BindNewPipeAndPassReceiver(),
                                 filesystem::mojom::kFlagOpenAlways, &err) ||
      err != base::File::Error::FILE_OK) {
    return nullptr;
  }

  return std::make_unique<Writer>(std::move(parent), path.BaseName());
}

bool Filter(const mojo::Remote<mojom::UnzipFilter>& filter,
            const base::FilePath& path) {
  bool result = false;
  filter->ShouldUnzipFile(path, &result);
  return result;
}

// Reads the given ZIP archive, and returns all the filenames concatenated
// together in one long string capped at ~100KB, without any separator, and in
// the encoding used by the ZIP archive itself. Returns an empty string if the
// ZIP cannot be read.
std::string GetRawFileNamesFromZip(const base::File& zip_file) {
  std::string result;

  // Open ZIP archive for reading.
  zip::ZipReader reader;
  if (!reader.OpenFromPlatformFile(zip_file.GetPlatformFile())) {
    LOG(ERROR) << "Cannot decode ZIP archive from file handle "
               << zip_file.GetPlatformFile();
    return result;
  }

  // Reserve a ~100KB buffer.
  result.reserve(100000);

  // Iterate over file entries of the ZIP archive.
  while (const zip::ZipReader::Entry* const entry = reader.Next()) {
    const std::string& path = entry->path_in_original_encoding;

    // Stop if we have enough data in |result|.
    if (path.size() > (result.capacity() - result.size()))
      break;

    // Accumulate data in |result|.
    result += path;
  }

  LOG_IF(ERROR, result.empty()) << "Cannot extract filenames from ZIP archive";
  return result;
}

}  // namespace

UnzipperImpl::UnzipperImpl() = default;

UnzipperImpl::UnzipperImpl(mojo::PendingReceiver<mojom::Unzipper> receiver)
    : receiver_(this, std::move(receiver)) {
  receiver_.set_disconnect_handler(base::BindOnce(
      &UnzipperImpl::OnReceiverDisconnect, weak_ptr_factory_.GetWeakPtr()));
}

UnzipperImpl::~UnzipperImpl() = default;

Encoding GetEncoding(const base::File& zip_file) {
  // Accumulate raw filenames.
  const std::string all_names = GetRawFileNamesFromZip(zip_file);
  if (all_names.empty()) {
    return UNKNOWN_ENCODING;
  }

  // Detect encoding.
  int consumed_bytes = 0;
  bool is_reliable = false;
  const Encoding encoding = CompactEncDet::DetectEncoding(
      all_names.data(), all_names.size(), nullptr, nullptr, nullptr,
      UNKNOWN_ENCODING, UNKNOWN_LANGUAGE,
      CompactEncDet::QUERY_CORPUS,  // Plain text
      true,                         // Exclude 7-bit encodings
      &consumed_bytes, &is_reliable);

  VLOG(1) << "Detected encoding: " << MimeEncodingName(encoding) << " ("
          << encoding << "), reliable: " << is_reliable
          << ", consumed bytes: " << consumed_bytes;

  LOG_IF(ERROR, encoding == UNKNOWN_ENCODING)
      << "Cannot detect encoding of filenames in ZIP archive";

  return encoding;
}

void UnzipperImpl::Listener(const mojo::Remote<mojom::UnzipListener>& listener,
                            uint64_t bytes) {
  listener->OnProgress(bytes);
}

bool DoUnzip(base::File zip_file,
             mojo::Remote<filesystem::mojom::Directory> output_dir,
             std::string encoding_name,
             std::string password,
             zip::FilterCallback filter_cb,
             zip::UnzipProgressCallback progress_cb) {
  return zip::Unzip(
      zip_file.GetPlatformFile(),
      base::BindRepeating(&MakeFileWriterDelegate, output_dir.get()),
      base::BindRepeating(&CreateDirectory, output_dir.get()),
      {.encoding = std::move(encoding_name),
       .filter = std::move(filter_cb),
       .progress = std::move(progress_cb),
       .password = std::move(password)});
}

bool RunUnzip(
    base::File zip_file,
    mojo::PendingRemote<filesystem::mojom::Directory> output_dir_remote,
    std::string encoding_name,
    std::string password,
    mojo::PendingRemote<mojom::UnzipFilter> filter_remote,
    mojo::PendingRemote<mojom::UnzipListener> listener_remote) {
  mojo::Remote<filesystem::mojom::Directory> output_dir(
      std::move(output_dir_remote));

  zip::FilterCallback filter_cb;
  if (filter_remote) {
    filter_cb = base::BindRepeating(
        &Filter, mojo::Remote<mojom::UnzipFilter>(std::move(filter_remote)));
  }

  zip::UnzipProgressCallback progress_cb;
  if (listener_remote) {
    mojo::Remote<mojom::UnzipListener> listener(std::move(listener_remote));
    progress_cb =
        base::BindRepeating(&UnzipperImpl::Listener, std::move(listener));
  }
  return zip::Unzip(
      zip_file.GetPlatformFile(),
      base::BindRepeating(&MakeFileWriterDelegate, output_dir.get()),
      base::BindRepeating(&CreateDirectory, output_dir.get()),
      {.encoding = std::move(encoding_name),
       .filter = std::move(filter_cb),
       .progress = std::move(progress_cb),
       .password = std::move(password)});
}

void UnzipperImpl::Unzip(
    base::File zip_file,
    mojo::PendingRemote<filesystem::mojom::Directory> output_dir_remote,
    mojom::UnzipOptionsPtr set_options,
    mojo::PendingRemote<mojom::UnzipFilter> filter_remote,
    mojo::PendingRemote<mojom::UnzipListener> listener_remote,
    UnzipCallback callback) {
  DCHECK(zip_file.IsValid());

  std::string encoding_name;
  if (set_options->encoding == "auto") {
    Encoding encoding = GetEncoding(zip_file);
    if (IsShiftJisOrVariant(encoding) || encoding == RUSSIAN_CP866) {
      encoding_name = MimeEncodingName(encoding);
    }
  } else {
    encoding_name = set_options->encoding;
  }

  runner_->PostTaskAndReplyWithResult(
      FROM_HERE,
      base::BindOnce(&RunUnzip, std::move(zip_file),
                     std::move(output_dir_remote), std::move(encoding_name),
                     std::move(set_options->password), std::move(filter_remote),
                     std::move(listener_remote)),
      base::BindOnce(std::move(callback)));
}

void UnzipperImpl::DetectEncoding(base::File zip_file,
                                  DetectEncodingCallback callback) {
  DCHECK(zip_file.IsValid());

  const Encoding encoding = GetEncoding(zip_file);
  std::move(callback).Run(encoding);
}

void UnzipperImpl::GetExtractedInfo(base::File zip_file,
                                    GetExtractedInfoCallback callback) {
  DCHECK(zip_file.IsValid());

  // Open ZIP archive for reading.
  zip::ZipReader reader;
  if (!reader.OpenFromPlatformFile(zip_file.GetPlatformFile())) {
    LOG(ERROR) << "Cannot decode ZIP archive from file handle "
               << zip_file.GetPlatformFile();
    unzip::mojom::InfoPtr info =
        unzip::mojom::Info::New(false, 0, false, false);
    std::move(callback).Run(std::move(info));
    return;
  }

  int64_t size = 0;
  bool valid = true;
  bool has_encrypted_content = false;
  bool uses_aes_encryption = false;

  // Iterate over file entries of the ZIP archive.
  while (const zip::ZipReader::Entry* const entry = reader.Next()) {
    // Check for (invalid) size stored.
    if (entry->original_size < 0 ||
        entry->original_size > std::numeric_limits<int64_t>::max() - size) {
      LOG(ERROR) << "ZIP bad size info from file handle "
                 << zip_file.GetPlatformFile();
      valid = false;
      break;
    }
    // Accumulate size (since original_size is signed, ignore invalid sizes).
    if (entry->original_size > 0) {
      size += entry->original_size;
    }
    if (entry->is_encrypted) {
      has_encrypted_content = true;
      if (entry->uses_aes_encryption) {
        uses_aes_encryption = true;
      }
    }
  }
  unzip::mojom::InfoPtr info = unzip::mojom::Info::New(
      valid, size, has_encrypted_content, uses_aes_encryption);
  std::move(callback).Run(std::move(info));
}

void UnzipperImpl::OnReceiverDisconnect() {
  DCHECK(receiver_.is_bound());
  receiver_.reset();
}

}  // namespace unzip