summaryrefslogtreecommitdiff
path: root/chromium/third_party/zlib/google/zip.cc
blob: 14e33cf39e9f2f278df886c488be2f292969277a (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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/zlib/google/zip.h"

#include <string>
#include <vector>

#include "base/bind.h"
#include "base/files/file.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "third_party/zlib/google/redact.h"
#include "third_party/zlib/google/zip_internal.h"
#include "third_party/zlib/google/zip_reader.h"
#include "third_party/zlib/google/zip_writer.h"

namespace zip {
namespace {

bool IsHiddenFile(const base::FilePath& file_path) {
  return file_path.BaseName().value()[0] == '.';
}

// Creates a directory at |extract_dir|/|entry_path|, including any parents.
bool CreateDirectory(const base::FilePath& extract_dir,
                     const base::FilePath& entry_path) {
  const base::FilePath dir = extract_dir.Append(entry_path);
  const bool ok = base::CreateDirectory(dir);
  PLOG_IF(ERROR, !ok) << "Cannot create directory " << Redact(dir);
  return ok;
}

// Creates a WriterDelegate that can write a file at |extract_dir|/|entry_path|.
std::unique_ptr<WriterDelegate> CreateFilePathWriterDelegate(
    const base::FilePath& extract_dir,
    const base::FilePath& entry_path) {
  return std::make_unique<FilePathWriterDelegate>(
      extract_dir.Append(entry_path));
}

class DirectFileAccessor : public FileAccessor {
 public:
  explicit DirectFileAccessor(base::FilePath src_dir)
      : src_dir_(std::move(src_dir)) {}

  ~DirectFileAccessor() override = default;

  bool Open(const Paths paths, std::vector<base::File>* const files) override {
    DCHECK(files);
    files->reserve(files->size() + paths.size());

    for (const base::FilePath& path : paths) {
      DCHECK(!path.IsAbsolute());
      const base::FilePath absolute_path = src_dir_.Append(path);
      if (base::DirectoryExists(absolute_path)) {
        files->emplace_back();
        LOG(ERROR) << "Cannot open " << Redact(path) << ": It is a directory";
      } else {
        files->emplace_back(
            absolute_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
        LOG_IF(ERROR, !files->back().IsValid())
            << "Cannot open " << Redact(path) << ": "
            << base::File::ErrorToString(files->back().error_details());
      }
    }

    return true;
  }

  bool List(const base::FilePath& path,
            std::vector<base::FilePath>* const files,
            std::vector<base::FilePath>* const subdirs) override {
    DCHECK(!path.IsAbsolute());
    DCHECK(files);
    DCHECK(subdirs);

    base::FileEnumerator file_enumerator(
        src_dir_.Append(path), false /* recursive */,
        base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES);

    while (!file_enumerator.Next().empty()) {
      const base::FileEnumerator::FileInfo info = file_enumerator.GetInfo();
      (info.IsDirectory() ? subdirs : files)
          ->push_back(path.Append(info.GetName()));
    }

    return true;
  }

  bool GetInfo(const base::FilePath& path, Info* const info) override {
    DCHECK(!path.IsAbsolute());
    DCHECK(info);

    base::File::Info file_info;
    if (!base::GetFileInfo(src_dir_.Append(path), &file_info)) {
      PLOG(ERROR) << "Cannot get info of " << Redact(path);
      return false;
    }

    info->is_directory = file_info.is_directory;
    info->last_modified = file_info.last_modified;

    return true;
  }

 private:
  const base::FilePath src_dir_;
};

}  // namespace

std::ostream& operator<<(std::ostream& out, const Progress& progress) {
  return out << progress.bytes << " bytes, " << progress.files << " files, "
             << progress.directories << " dirs, " << progress.errors
             << " errors";
}

bool Zip(const ZipParams& params) {
  DirectFileAccessor default_accessor(params.src_dir);
  FileAccessor* const file_accessor = params.file_accessor ? params.file_accessor : &default_accessor;

  std::unique_ptr<internal::ZipWriter> zip_writer;

#if defined(OS_POSIX) || defined(OS_FUCHSIA)
  if (params.dest_fd != base::kInvalidPlatformFile) {
    DCHECK(params.dest_file.empty());
    zip_writer =
        internal::ZipWriter::CreateWithFd(params.dest_fd, file_accessor);
    if (!zip_writer)
      return false;
  }
#endif

  if (!zip_writer) {
    zip_writer = internal::ZipWriter::Create(params.dest_file, file_accessor);
    if (!zip_writer)
      return false;
  }

  zip_writer->SetProgressCallback(params.progress_callback,
                                  params.progress_period);
  zip_writer->SetRecursive(params.recursive);
  zip_writer->ContinueOnError(params.continue_on_error);

  if (!params.include_hidden_files || params.filter_callback)
    zip_writer->SetFilterCallback(base::BindRepeating(
        [](const ZipParams* const params, const base::FilePath& path) -> bool {
          return (params->include_hidden_files || !IsHiddenFile(path)) &&
                 (!params->filter_callback ||
                  params->filter_callback.Run(params->src_dir.Append(path)));
        },
        &params));

  if (params.src_files.empty()) {
    // No source items are specified. Zip the entire source directory.
    zip_writer->SetRecursive(true);
    if (!zip_writer->AddDirectoryContents(base::FilePath()))
      return false;
  } else {
    // Only zip the specified source items.
    if (!zip_writer->AddMixedEntries(params.src_files))
      return false;
  }

  return zip_writer->Close();
}

bool Unzip(const base::FilePath& src_file,
           const base::FilePath& dest_dir,
           UnzipOptions options) {
  base::File file(src_file, base::File::FLAG_OPEN | base::File::FLAG_READ);
  if (!file.IsValid()) {
    PLOG(ERROR) << "Cannot open " << Redact(src_file) << ": "
                << base::File::ErrorToString(file.error_details());
    return false;
  }

  DLOG_IF(WARNING, !base::IsDirectoryEmpty(dest_dir))
      << "ZIP extraction directory is not empty: " << dest_dir;

  return Unzip(file.GetPlatformFile(),
               base::BindRepeating(&CreateFilePathWriterDelegate, dest_dir),
               base::BindRepeating(&CreateDirectory, dest_dir),
               std::move(options));
}

bool Unzip(const base::PlatformFile& src_file,
           WriterFactory writer_factory,
           DirectoryCreator directory_creator,
           UnzipOptions options) {
  ZipReader reader;
  reader.SetEncoding(std::move(options.encoding));
  reader.SetPassword(std::move(options.password));

  if (!reader.OpenFromPlatformFile(src_file)) {
    LOG(ERROR) << "Cannot open ZIP from file handle " << src_file;
    return false;
  }

  while (const ZipReader::Entry* const entry = reader.Next()) {
    if (entry->is_unsafe) {
      LOG(ERROR) << "Found unsafe entry " << Redact(entry->path) << " in ZIP";
      if (!options.continue_on_error)
        return false;
      continue;
    }

    if (options.filter && !options.filter.Run(entry->path)) {
      VLOG(1) << "Skipped ZIP entry " << Redact(entry->path);
      continue;
    }

    if (entry->is_directory) {
      // It's a directory.
      if (!directory_creator.Run(entry->path)) {
        LOG(ERROR) << "Cannot create directory " << Redact(entry->path);
        if (!options.continue_on_error)
          return false;
      }

      continue;
    }

    // It's a file.
    std::unique_ptr<WriterDelegate> writer = writer_factory.Run(entry->path);
    if (!writer ||
        (options.progress ? !reader.ExtractCurrentEntryWithListener(
                                writer.get(), options.progress)
                          : !reader.ExtractCurrentEntry(writer.get()))) {
      LOG(ERROR) << "Cannot extract file " << Redact(entry->path)
                 << " from ZIP";
      if (!options.continue_on_error)
        return false;
    }
  }

  return reader.ok();
}

bool ZipWithFilterCallback(const base::FilePath& src_dir,
                           const base::FilePath& dest_file,
                           FilterCallback filter) {
  DCHECK(base::DirectoryExists(src_dir));
  ZipParams params = {};
  params.src_dir = src_dir;
  params.dest_file = dest_file;
  params.filter_callback = std::move(filter);

  return Zip(params);
}

bool Zip(const base::FilePath& src_dir,
         const base::FilePath& dest_file,
         bool include_hidden_files) {
  ZipParams params = {};
  params.src_dir = src_dir;
  params.dest_file = dest_file;
  params.include_hidden_files = include_hidden_files;

  return Zip(params);
}

#if defined(OS_POSIX) || defined(OS_FUCHSIA)
bool ZipFiles(const base::FilePath& src_dir,
              Paths src_relative_paths,
              int dest_fd) {
  DCHECK(base::DirectoryExists(src_dir));
  return Zip({.src_dir = src_dir,
              .dest_fd = dest_fd,
              .src_files = src_relative_paths});
}
#endif  // defined(OS_POSIX) || defined(OS_FUCHSIA)

}  // namespace zip