• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2011 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 "third_party/zlib/google/zip_reader.h"
6 
7 #include <stddef.h>
8 #include <stdint.h>
9 #include <string.h>
10 
11 #include <iterator>
12 #include <string>
13 #include <vector>
14 
15 #include "base/bind.h"
16 #include "base/check.h"
17 #include "base/files/file.h"
18 #include "base/files/file_path.h"
19 #include "base/files/file_util.h"
20 #include "base/files/scoped_temp_dir.h"
21 #include "base/hash/md5.h"
22 #include "base/path_service.h"
23 #include "base/run_loop.h"
24 #include "base/strings/string_piece.h"
25 #include "base/strings/stringprintf.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/test/bind.h"
28 #include "base/test/task_environment.h"
29 #include "base/time/time.h"
30 #include "build/build_config.h"
31 #include "testing/gmock/include/gmock/gmock.h"
32 #include "testing/gtest/include/gtest/gtest.h"
33 #include "testing/platform_test.h"
34 #include "third_party/zlib/google/zip_internal.h"
35 
36 using ::testing::_;
37 using ::testing::ElementsAre;
38 using ::testing::ElementsAreArray;
39 using ::testing::Return;
40 using ::testing::SizeIs;
41 
42 namespace {
43 
44 const static std::string kQuuxExpectedMD5 = "d1ae4ac8a17a0e09317113ab284b57a6";
45 
46 class FileWrapper {
47  public:
48   typedef enum { READ_ONLY, READ_WRITE } AccessMode;
49 
FileWrapper(const base::FilePath & path,AccessMode mode)50   FileWrapper(const base::FilePath& path, AccessMode mode) {
51     int flags = base::File::FLAG_READ;
52     if (mode == READ_ONLY)
53       flags |= base::File::FLAG_OPEN;
54     else
55       flags |= base::File::FLAG_WRITE | base::File::FLAG_CREATE_ALWAYS;
56 
57     file_.Initialize(path, flags);
58   }
59 
~FileWrapper()60   ~FileWrapper() {}
61 
platform_file()62   base::PlatformFile platform_file() { return file_.GetPlatformFile(); }
63 
file()64   base::File* file() { return &file_; }
65 
66  private:
67   base::File file_;
68 };
69 
70 // A mock that provides methods that can be used as callbacks in asynchronous
71 // unzip functions.  Tracks the number of calls and number of bytes reported.
72 // Assumes that progress callbacks will be executed in-order.
73 class MockUnzipListener : public base::SupportsWeakPtr<MockUnzipListener> {
74  public:
MockUnzipListener()75   MockUnzipListener()
76       : success_calls_(0),
77         failure_calls_(0),
78         progress_calls_(0),
79         current_progress_(0) {}
80 
81   // Success callback for async functions.
OnUnzipSuccess()82   void OnUnzipSuccess() { success_calls_++; }
83 
84   // Failure callback for async functions.
OnUnzipFailure()85   void OnUnzipFailure() { failure_calls_++; }
86 
87   // Progress callback for async functions.
OnUnzipProgress(int64_t progress)88   void OnUnzipProgress(int64_t progress) {
89     DCHECK(progress > current_progress_);
90     progress_calls_++;
91     current_progress_ = progress;
92   }
93 
success_calls()94   int success_calls() { return success_calls_; }
failure_calls()95   int failure_calls() { return failure_calls_; }
progress_calls()96   int progress_calls() { return progress_calls_; }
current_progress()97   int current_progress() { return current_progress_; }
98 
99  private:
100   int success_calls_;
101   int failure_calls_;
102   int progress_calls_;
103 
104   int64_t current_progress_;
105 };
106 
107 class MockWriterDelegate : public zip::WriterDelegate {
108  public:
109   MOCK_METHOD0(PrepareOutput, bool());
110   MOCK_METHOD2(WriteBytes, bool(const char*, int));
111   MOCK_METHOD1(SetTimeModified, void(const base::Time&));
112   MOCK_METHOD1(SetPosixFilePermissions, void(int));
113   MOCK_METHOD0(OnError, void());
114 };
115 
ExtractCurrentEntryToFilePath(zip::ZipReader * reader,base::FilePath path)116 bool ExtractCurrentEntryToFilePath(zip::ZipReader* reader,
117                                    base::FilePath path) {
118   zip::FilePathWriterDelegate writer(path);
119   return reader->ExtractCurrentEntry(&writer);
120 }
121 
LocateAndOpenEntry(zip::ZipReader * const reader,const base::FilePath & path_in_zip)122 const zip::ZipReader::Entry* LocateAndOpenEntry(
123     zip::ZipReader* const reader,
124     const base::FilePath& path_in_zip) {
125   DCHECK(reader);
126   EXPECT_TRUE(reader->ok());
127 
128   // The underlying library can do O(1) access, but ZipReader does not expose
129   // that. O(N) access is acceptable for these tests.
130   while (const zip::ZipReader::Entry* const entry = reader->Next()) {
131     EXPECT_TRUE(reader->ok());
132     if (entry->path == path_in_zip)
133       return entry;
134   }
135 
136   EXPECT_TRUE(reader->ok());
137   return nullptr;
138 }
139 
140 using Paths = std::vector<base::FilePath>;
141 
142 }  // namespace
143 
144 namespace zip {
145 
146 // Make the test a PlatformTest to setup autorelease pools properly on Mac.
147 class ZipReaderTest : public PlatformTest {
148  protected:
SetUp()149   void SetUp() override {
150     PlatformTest::SetUp();
151 
152     ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
153     test_dir_ = temp_dir_.GetPath();
154   }
155 
GetTestDataDirectory()156   static base::FilePath GetTestDataDirectory() {
157     base::FilePath path;
158     CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &path));
159     return path.AppendASCII("third_party")
160         .AppendASCII("zlib")
161         .AppendASCII("google")
162         .AppendASCII("test")
163         .AppendASCII("data");
164   }
165 
GetPaths(const base::FilePath & zip_path,base::StringPiece encoding={})166   static Paths GetPaths(const base::FilePath& zip_path,
167                         base::StringPiece encoding = {}) {
168     Paths paths;
169 
170     if (ZipReader reader; reader.Open(zip_path)) {
171       if (!encoding.empty())
172         reader.SetEncoding(std::string(encoding));
173 
174       while (const ZipReader::Entry* const entry = reader.Next()) {
175         EXPECT_TRUE(reader.ok());
176         paths.push_back(entry->path);
177       }
178 
179       EXPECT_TRUE(reader.ok());
180     }
181 
182     return paths;
183   }
184 
185   // The path to temporary directory used to contain the test operations.
186   base::FilePath test_dir_;
187   // The path to the test data directory where test.zip etc. are located.
188   const base::FilePath data_dir_ = GetTestDataDirectory();
189   // The path to test.zip in the test data directory.
190   const base::FilePath test_zip_file_ = data_dir_.AppendASCII("test.zip");
191   const Paths test_zip_contents_ = {
192       base::FilePath(FILE_PATH_LITERAL("foo/")),
193       base::FilePath(FILE_PATH_LITERAL("foo/bar/")),
194       base::FilePath(FILE_PATH_LITERAL("foo/bar/baz.txt")),
195       base::FilePath(FILE_PATH_LITERAL("foo/bar/quux.txt")),
196       base::FilePath(FILE_PATH_LITERAL("foo/bar.txt")),
197       base::FilePath(FILE_PATH_LITERAL("foo.txt")),
198       base::FilePath(FILE_PATH_LITERAL("foo/bar/.hidden")),
199   };
200   base::ScopedTempDir temp_dir_;
201   base::test::TaskEnvironment task_environment_;
202 };
203 
TEST_F(ZipReaderTest,Open_ValidZipFile)204 TEST_F(ZipReaderTest, Open_ValidZipFile) {
205   ZipReader reader;
206   EXPECT_TRUE(reader.Open(test_zip_file_));
207   EXPECT_TRUE(reader.ok());
208 }
209 
TEST_F(ZipReaderTest,Open_ValidZipPlatformFile)210 TEST_F(ZipReaderTest, Open_ValidZipPlatformFile) {
211   ZipReader reader;
212   EXPECT_FALSE(reader.ok());
213   FileWrapper zip_fd_wrapper(test_zip_file_, FileWrapper::READ_ONLY);
214   EXPECT_TRUE(reader.OpenFromPlatformFile(zip_fd_wrapper.platform_file()));
215   EXPECT_TRUE(reader.ok());
216 }
217 
TEST_F(ZipReaderTest,Open_NonExistentFile)218 TEST_F(ZipReaderTest, Open_NonExistentFile) {
219   ZipReader reader;
220   EXPECT_FALSE(reader.ok());
221   EXPECT_FALSE(reader.Open(data_dir_.AppendASCII("nonexistent.zip")));
222   EXPECT_FALSE(reader.ok());
223 }
224 
TEST_F(ZipReaderTest,Open_ExistentButNonZipFile)225 TEST_F(ZipReaderTest, Open_ExistentButNonZipFile) {
226   ZipReader reader;
227   EXPECT_FALSE(reader.ok());
228   EXPECT_FALSE(reader.Open(data_dir_.AppendASCII("create_test_zip.sh")));
229   EXPECT_FALSE(reader.ok());
230 }
231 
TEST_F(ZipReaderTest,Open_EmptyFile)232 TEST_F(ZipReaderTest, Open_EmptyFile) {
233   ZipReader reader;
234   EXPECT_FALSE(reader.ok());
235   EXPECT_FALSE(reader.Open(data_dir_.AppendASCII("empty.zip")));
236   EXPECT_FALSE(reader.ok());
237 }
238 
239 // Iterate through the contents in the test ZIP archive, and compare that the
240 // contents collected from the ZipReader matches the expected contents.
TEST_F(ZipReaderTest,Iteration)241 TEST_F(ZipReaderTest, Iteration) {
242   Paths actual_contents;
243   ZipReader reader;
244   EXPECT_FALSE(reader.ok());
245   EXPECT_TRUE(reader.Open(test_zip_file_));
246   EXPECT_TRUE(reader.ok());
247   while (const ZipReader::Entry* const entry = reader.Next()) {
248     EXPECT_TRUE(reader.ok());
249     actual_contents.push_back(entry->path);
250   }
251 
252   EXPECT_TRUE(reader.ok());
253   EXPECT_FALSE(reader.Next());  // Shouldn't go further.
254   EXPECT_TRUE(reader.ok());
255 
256   EXPECT_THAT(actual_contents, SizeIs(reader.num_entries()));
257   EXPECT_THAT(actual_contents, ElementsAreArray(test_zip_contents_));
258 }
259 
260 // Open the test ZIP archive from a file descriptor, iterate through its
261 // contents, and compare that they match the expected contents.
TEST_F(ZipReaderTest,PlatformFileIteration)262 TEST_F(ZipReaderTest, PlatformFileIteration) {
263   Paths actual_contents;
264   ZipReader reader;
265   FileWrapper zip_fd_wrapper(test_zip_file_, FileWrapper::READ_ONLY);
266   EXPECT_TRUE(reader.OpenFromPlatformFile(zip_fd_wrapper.platform_file()));
267   EXPECT_TRUE(reader.ok());
268   while (const ZipReader::Entry* const entry = reader.Next()) {
269     EXPECT_TRUE(reader.ok());
270     actual_contents.push_back(entry->path);
271   }
272 
273   EXPECT_TRUE(reader.ok());
274   EXPECT_FALSE(reader.Next());  // Shouldn't go further.
275   EXPECT_TRUE(reader.ok());
276 
277   EXPECT_THAT(actual_contents, SizeIs(reader.num_entries()));
278   EXPECT_THAT(actual_contents, ElementsAreArray(test_zip_contents_));
279 }
280 
TEST_F(ZipReaderTest,RegularFile)281 TEST_F(ZipReaderTest, RegularFile) {
282   ZipReader reader;
283   ASSERT_TRUE(reader.Open(test_zip_file_));
284   base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt"));
285 
286   const ZipReader::Entry* entry = LocateAndOpenEntry(&reader, target_path);
287   ASSERT_TRUE(entry);
288 
289   EXPECT_EQ(target_path, entry->path);
290   EXPECT_EQ(13527, entry->original_size);
291 
292   // The expected time stamp: 2009-05-29 06:22:20
293   base::Time::Exploded exploded = {};  // Zero-clear.
294   entry->last_modified.UTCExplode(&exploded);
295   EXPECT_EQ(2009, exploded.year);
296   EXPECT_EQ(5, exploded.month);
297   EXPECT_EQ(29, exploded.day_of_month);
298   EXPECT_EQ(6, exploded.hour);
299   EXPECT_EQ(22, exploded.minute);
300   EXPECT_EQ(20, exploded.second);
301   EXPECT_EQ(0, exploded.millisecond);
302 
303   EXPECT_FALSE(entry->is_unsafe);
304   EXPECT_FALSE(entry->is_directory);
305 }
306 
TEST_F(ZipReaderTest,DotDotFile)307 TEST_F(ZipReaderTest, DotDotFile) {
308   ZipReader reader;
309   ASSERT_TRUE(reader.Open(data_dir_.AppendASCII("evil.zip")));
310   base::FilePath target_path(FILE_PATH_LITERAL(
311       "../levilevilevilevilevilevilevilevilevilevilevilevil"));
312   const ZipReader::Entry* entry = LocateAndOpenEntry(&reader, target_path);
313   ASSERT_TRUE(entry);
314   EXPECT_EQ(target_path, entry->path);
315   // This file is unsafe because of ".." in the file name.
316   EXPECT_TRUE(entry->is_unsafe);
317   EXPECT_FALSE(entry->is_directory);
318 }
319 
TEST_F(ZipReaderTest,InvalidUTF8File)320 TEST_F(ZipReaderTest, InvalidUTF8File) {
321   ZipReader reader;
322   ASSERT_TRUE(reader.Open(data_dir_.AppendASCII("evil_via_invalid_utf8.zip")));
323   base::FilePath target_path = base::FilePath::FromUTF8Unsafe(".�.\\evil.txt");
324   const ZipReader::Entry* entry = LocateAndOpenEntry(&reader, target_path);
325   ASSERT_TRUE(entry);
326   EXPECT_EQ(target_path, entry->path);
327   EXPECT_FALSE(entry->is_unsafe);
328   EXPECT_FALSE(entry->is_directory);
329 }
330 
331 // By default, file paths in ZIPs are interpreted as UTF-8. But in this test,
332 // the ZIP archive contains file paths that are actually encoded in Shift JIS.
333 // The SJIS-encoded paths are thus wrongly interpreted as UTF-8, resulting in
334 // garbled paths. Invalid UTF-8 sequences are safely converted to the
335 // replacement character �.
TEST_F(ZipReaderTest,EncodingSjisAsUtf8)336 TEST_F(ZipReaderTest, EncodingSjisAsUtf8) {
337   EXPECT_THAT(
338       GetPaths(data_dir_.AppendASCII("SJIS Bug 846195.zip")),
339       ElementsAre(
340           base::FilePath::FromUTF8Unsafe("�V�����t�H���_/SJIS_835C_�\\.txt"),
341           base::FilePath::FromUTF8Unsafe(
342               "�V�����t�H���_/�V�����e�L�X�g �h�L�������g.txt")));
343 }
344 
345 // In this test, SJIS-encoded paths are interpreted as Code Page 1252. This
346 // results in garbled paths. Note the presence of C1 control codes U+0090 and
347 // U+0081 in the garbled paths.
TEST_F(ZipReaderTest,EncodingSjisAs1252)348 TEST_F(ZipReaderTest, EncodingSjisAs1252) {
349   EXPECT_THAT(
350       GetPaths(data_dir_.AppendASCII("SJIS Bug 846195.zip"), "windows-1252"),
351       ElementsAre(base::FilePath::FromUTF8Unsafe(
352                       "\u0090V‚µ‚¢ƒtƒHƒ‹ƒ_/SJIS_835C_ƒ\\.txt"),
353                   base::FilePath::FromUTF8Unsafe(
354                       "\u0090V‚µ‚¢ƒtƒHƒ‹ƒ_/\u0090V‚µ‚¢ƒeƒLƒXƒg "
355                       "ƒhƒLƒ…ƒ\u0081ƒ“ƒg.txt")));
356 }
357 
358 // In this test, SJIS-encoded paths are interpreted as Code Page 866. This
359 // results in garbled paths.
TEST_F(ZipReaderTest,EncodingSjisAsIbm866)360 TEST_F(ZipReaderTest, EncodingSjisAsIbm866) {
361   EXPECT_THAT(
362       GetPaths(data_dir_.AppendASCII("SJIS Bug 846195.zip"), "IBM866"),
363       ElementsAre(
364           base::FilePath::FromUTF8Unsafe("РVВ╡ВвГtГHГЛГ_/SJIS_835C_Г\\.txt"),
365           base::FilePath::FromUTF8Unsafe(
366               "РVВ╡ВвГtГHГЛГ_/РVВ╡ВвГeГLГXГg ГhГLГЕГБГУГg.txt")));
367 }
368 
369 // Tests that SJIS-encoded paths are correctly converted to Unicode.
TEST_F(ZipReaderTest,EncodingSjis)370 TEST_F(ZipReaderTest, EncodingSjis) {
371   EXPECT_THAT(
372       GetPaths(data_dir_.AppendASCII("SJIS Bug 846195.zip"), "Shift_JIS"),
373       ElementsAre(
374           base::FilePath::FromUTF8Unsafe("新しいフォルダ/SJIS_835C_ソ.txt"),
375           base::FilePath::FromUTF8Unsafe(
376               "新しいフォルダ/新しいテキスト ドキュメント.txt")));
377 }
378 
TEST_F(ZipReaderTest,AbsoluteFile)379 TEST_F(ZipReaderTest, AbsoluteFile) {
380   ZipReader reader;
381   ASSERT_TRUE(
382       reader.Open(data_dir_.AppendASCII("evil_via_absolute_file_name.zip")));
383   base::FilePath target_path(FILE_PATH_LITERAL("/evil.txt"));
384   const ZipReader::Entry* entry = LocateAndOpenEntry(&reader, target_path);
385   ASSERT_TRUE(entry);
386   EXPECT_EQ(target_path, entry->path);
387   // This file is unsafe because of the absolute file name.
388   EXPECT_TRUE(entry->is_unsafe);
389   EXPECT_FALSE(entry->is_directory);
390 }
391 
TEST_F(ZipReaderTest,Directory)392 TEST_F(ZipReaderTest, Directory) {
393   ZipReader reader;
394   ASSERT_TRUE(reader.Open(test_zip_file_));
395   base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/"));
396   const ZipReader::Entry* entry = LocateAndOpenEntry(&reader, target_path);
397   ASSERT_TRUE(entry);
398   EXPECT_EQ(target_path, entry->path);
399   // The directory size should be zero.
400   EXPECT_EQ(0, entry->original_size);
401 
402   // The expected time stamp: 2009-05-31 15:49:52
403   base::Time::Exploded exploded = {};  // Zero-clear.
404   entry->last_modified.UTCExplode(&exploded);
405   EXPECT_EQ(2009, exploded.year);
406   EXPECT_EQ(5, exploded.month);
407   EXPECT_EQ(31, exploded.day_of_month);
408   EXPECT_EQ(15, exploded.hour);
409   EXPECT_EQ(49, exploded.minute);
410   EXPECT_EQ(52, exploded.second);
411   EXPECT_EQ(0, exploded.millisecond);
412 
413   EXPECT_FALSE(entry->is_unsafe);
414   EXPECT_TRUE(entry->is_directory);
415 }
416 
TEST_F(ZipReaderTest,EncryptedFile_WrongPassword)417 TEST_F(ZipReaderTest, EncryptedFile_WrongPassword) {
418   ZipReader reader;
419   ASSERT_TRUE(reader.Open(data_dir_.AppendASCII("Different Encryptions.zip")));
420   reader.SetPassword("wrong password");
421 
422   {
423     const ZipReader::Entry* entry = reader.Next();
424     ASSERT_TRUE(entry);
425     EXPECT_EQ(base::FilePath::FromASCII("ClearText.txt"), entry->path);
426     EXPECT_FALSE(entry->is_directory);
427     EXPECT_FALSE(entry->is_encrypted);
428     std::string contents = "dummy";
429     EXPECT_TRUE(reader.ExtractCurrentEntryToString(&contents));
430     EXPECT_EQ("This is not encrypted.\n", contents);
431   }
432 
433   for (const base::StringPiece path : {
434            "Encrypted AES-128.txt",
435            "Encrypted AES-192.txt",
436            "Encrypted AES-256.txt",
437            "Encrypted ZipCrypto.txt",
438        }) {
439     const ZipReader::Entry* entry = reader.Next();
440     ASSERT_TRUE(entry);
441     EXPECT_EQ(base::FilePath::FromASCII(path), entry->path);
442     EXPECT_FALSE(entry->is_directory);
443     EXPECT_TRUE(entry->is_encrypted);
444     std::string contents = "dummy";
445     EXPECT_FALSE(reader.ExtractCurrentEntryToString(&contents));
446   }
447 
448   EXPECT_FALSE(reader.Next());
449   EXPECT_TRUE(reader.ok());
450 }
451 
TEST_F(ZipReaderTest,EncryptedFile_RightPassword)452 TEST_F(ZipReaderTest, EncryptedFile_RightPassword) {
453   ZipReader reader;
454   ASSERT_TRUE(reader.Open(data_dir_.AppendASCII("Different Encryptions.zip")));
455   reader.SetPassword("password");
456 
457   {
458     const ZipReader::Entry* entry = reader.Next();
459     ASSERT_TRUE(entry);
460     EXPECT_EQ(base::FilePath::FromASCII("ClearText.txt"), entry->path);
461     EXPECT_FALSE(entry->is_directory);
462     EXPECT_FALSE(entry->is_encrypted);
463     std::string contents = "dummy";
464     EXPECT_TRUE(reader.ExtractCurrentEntryToString(&contents));
465     EXPECT_EQ("This is not encrypted.\n", contents);
466   }
467 
468   // TODO(crbug.com/1296838) Support AES encryption.
469   for (const base::StringPiece path : {
470            "Encrypted AES-128.txt",
471            "Encrypted AES-192.txt",
472            "Encrypted AES-256.txt",
473        }) {
474     const ZipReader::Entry* entry = reader.Next();
475     ASSERT_TRUE(entry);
476     EXPECT_EQ(base::FilePath::FromASCII(path), entry->path);
477     EXPECT_FALSE(entry->is_directory);
478     EXPECT_TRUE(entry->is_encrypted);
479     std::string contents = "dummy";
480     EXPECT_FALSE(reader.ExtractCurrentEntryToString(&contents));
481     EXPECT_EQ("", contents);
482   }
483 
484   {
485     const ZipReader::Entry* entry = reader.Next();
486     ASSERT_TRUE(entry);
487     EXPECT_EQ(base::FilePath::FromASCII("Encrypted ZipCrypto.txt"),
488               entry->path);
489     EXPECT_FALSE(entry->is_directory);
490     EXPECT_TRUE(entry->is_encrypted);
491     std::string contents = "dummy";
492     EXPECT_TRUE(reader.ExtractCurrentEntryToString(&contents));
493     EXPECT_EQ("This is encrypted with ZipCrypto.\n", contents);
494   }
495 
496   EXPECT_FALSE(reader.Next());
497   EXPECT_TRUE(reader.ok());
498 }
499 
500 // Verifies that the ZipReader class can extract a file from a zip archive
501 // stored in memory. This test opens a zip archive in a std::string object,
502 // extracts its content, and verifies the content is the same as the expected
503 // text.
TEST_F(ZipReaderTest,OpenFromString)504 TEST_F(ZipReaderTest, OpenFromString) {
505   // A zip archive consisting of one file "test.txt", which is a 16-byte text
506   // file that contains "This is a test.\n".
507   const char kTestData[] =
508       "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00\xa4\x66\x24\x41\x13\xe8"
509       "\xcb\x27\x10\x00\x00\x00\x10\x00\x00\x00\x08\x00\x1c\x00\x74\x65"
510       "\x73\x74\x2e\x74\x78\x74\x55\x54\x09\x00\x03\x34\x89\x45\x50\x34"
511       "\x89\x45\x50\x75\x78\x0b\x00\x01\x04\x8e\xf0\x00\x00\x04\x88\x13"
512       "\x00\x00\x54\x68\x69\x73\x20\x69\x73\x20\x61\x20\x74\x65\x73\x74"
513       "\x2e\x0a\x50\x4b\x01\x02\x1e\x03\x0a\x00\x00\x00\x00\x00\xa4\x66"
514       "\x24\x41\x13\xe8\xcb\x27\x10\x00\x00\x00\x10\x00\x00\x00\x08\x00"
515       "\x18\x00\x00\x00\x00\x00\x01\x00\x00\x00\xa4\x81\x00\x00\x00\x00"
516       "\x74\x65\x73\x74\x2e\x74\x78\x74\x55\x54\x05\x00\x03\x34\x89\x45"
517       "\x50\x75\x78\x0b\x00\x01\x04\x8e\xf0\x00\x00\x04\x88\x13\x00\x00"
518       "\x50\x4b\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00\x4e\x00\x00\x00"
519       "\x52\x00\x00\x00\x00\x00";
520   std::string data(kTestData, std::size(kTestData));
521   ZipReader reader;
522   ASSERT_TRUE(reader.OpenFromString(data));
523   base::FilePath target_path(FILE_PATH_LITERAL("test.txt"));
524   ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path));
525   ASSERT_TRUE(ExtractCurrentEntryToFilePath(&reader,
526                                             test_dir_.AppendASCII("test.txt")));
527 
528   std::string actual;
529   ASSERT_TRUE(
530       base::ReadFileToString(test_dir_.AppendASCII("test.txt"), &actual));
531   EXPECT_EQ(std::string("This is a test.\n"), actual);
532 }
533 
534 // Verifies that the asynchronous extraction to a file works.
TEST_F(ZipReaderTest,ExtractToFileAsync_RegularFile)535 TEST_F(ZipReaderTest, ExtractToFileAsync_RegularFile) {
536   MockUnzipListener listener;
537 
538   ZipReader reader;
539   base::FilePath target_file = test_dir_.AppendASCII("quux.txt");
540   base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt"));
541   ASSERT_TRUE(reader.Open(test_zip_file_));
542   ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path));
543   reader.ExtractCurrentEntryToFilePathAsync(
544       target_file,
545       base::BindOnce(&MockUnzipListener::OnUnzipSuccess, listener.AsWeakPtr()),
546       base::BindOnce(&MockUnzipListener::OnUnzipFailure, listener.AsWeakPtr()),
547       base::BindRepeating(&MockUnzipListener::OnUnzipProgress,
548                           listener.AsWeakPtr()));
549 
550   EXPECT_EQ(0, listener.success_calls());
551   EXPECT_EQ(0, listener.failure_calls());
552   EXPECT_EQ(0, listener.progress_calls());
553 
554   base::RunLoop().RunUntilIdle();
555 
556   EXPECT_EQ(1, listener.success_calls());
557   EXPECT_EQ(0, listener.failure_calls());
558   EXPECT_LE(1, listener.progress_calls());
559 
560   std::string output;
561   ASSERT_TRUE(
562       base::ReadFileToString(test_dir_.AppendASCII("quux.txt"), &output));
563   const std::string md5 = base::MD5String(output);
564   EXPECT_EQ(kQuuxExpectedMD5, md5);
565 
566   int64_t file_size = 0;
567   ASSERT_TRUE(base::GetFileSize(target_file, &file_size));
568 
569   EXPECT_EQ(file_size, listener.current_progress());
570 }
571 
TEST_F(ZipReaderTest,ExtractToFileAsync_Encrypted_NoPassword)572 TEST_F(ZipReaderTest, ExtractToFileAsync_Encrypted_NoPassword) {
573   MockUnzipListener listener;
574 
575   ZipReader reader;
576   ASSERT_TRUE(reader.Open(data_dir_.AppendASCII("Different Encryptions.zip")));
577   ASSERT_TRUE(LocateAndOpenEntry(
578       &reader, base::FilePath::FromASCII("Encrypted ZipCrypto.txt")));
579   const base::FilePath target_path = test_dir_.AppendASCII("extracted");
580   reader.ExtractCurrentEntryToFilePathAsync(
581       target_path,
582       base::BindOnce(&MockUnzipListener::OnUnzipSuccess, listener.AsWeakPtr()),
583       base::BindOnce(&MockUnzipListener::OnUnzipFailure, listener.AsWeakPtr()),
584       base::BindRepeating(&MockUnzipListener::OnUnzipProgress,
585                           listener.AsWeakPtr()));
586 
587   EXPECT_EQ(0, listener.success_calls());
588   EXPECT_EQ(0, listener.failure_calls());
589   EXPECT_EQ(0, listener.progress_calls());
590 
591   base::RunLoop().RunUntilIdle();
592 
593   EXPECT_EQ(0, listener.success_calls());
594   EXPECT_EQ(1, listener.failure_calls());
595   EXPECT_LE(1, listener.progress_calls());
596 
597   // The extracted file contains rubbish data.
598   // We probably shouldn't even look at it.
599   std::string contents;
600   ASSERT_TRUE(base::ReadFileToString(target_path, &contents));
601   EXPECT_NE("", contents);
602   EXPECT_EQ(contents.size(), listener.current_progress());
603 }
604 
TEST_F(ZipReaderTest,ExtractToFileAsync_Encrypted_RightPassword)605 TEST_F(ZipReaderTest, ExtractToFileAsync_Encrypted_RightPassword) {
606   MockUnzipListener listener;
607 
608   ZipReader reader;
609   reader.SetPassword("password");
610   ASSERT_TRUE(reader.Open(data_dir_.AppendASCII("Different Encryptions.zip")));
611   ASSERT_TRUE(LocateAndOpenEntry(
612       &reader, base::FilePath::FromASCII("Encrypted ZipCrypto.txt")));
613   const base::FilePath target_path = test_dir_.AppendASCII("extracted");
614   reader.ExtractCurrentEntryToFilePathAsync(
615       target_path,
616       base::BindOnce(&MockUnzipListener::OnUnzipSuccess, listener.AsWeakPtr()),
617       base::BindOnce(&MockUnzipListener::OnUnzipFailure, listener.AsWeakPtr()),
618       base::BindRepeating(&MockUnzipListener::OnUnzipProgress,
619                           listener.AsWeakPtr()));
620 
621   EXPECT_EQ(0, listener.success_calls());
622   EXPECT_EQ(0, listener.failure_calls());
623   EXPECT_EQ(0, listener.progress_calls());
624 
625   base::RunLoop().RunUntilIdle();
626 
627   EXPECT_EQ(1, listener.success_calls());
628   EXPECT_EQ(0, listener.failure_calls());
629   EXPECT_LE(1, listener.progress_calls());
630 
631   std::string contents;
632   ASSERT_TRUE(base::ReadFileToString(target_path, &contents));
633   EXPECT_EQ("This is encrypted with ZipCrypto.\n", contents);
634   EXPECT_EQ(contents.size(), listener.current_progress());
635 }
636 
TEST_F(ZipReaderTest,ExtractToFileAsync_WrongCrc)637 TEST_F(ZipReaderTest, ExtractToFileAsync_WrongCrc) {
638   MockUnzipListener listener;
639 
640   ZipReader reader;
641   ASSERT_TRUE(reader.Open(data_dir_.AppendASCII("Wrong CRC.zip")));
642   ASSERT_TRUE(
643       LocateAndOpenEntry(&reader, base::FilePath::FromASCII("Corrupted.txt")));
644   const base::FilePath target_path = test_dir_.AppendASCII("extracted");
645   reader.ExtractCurrentEntryToFilePathAsync(
646       target_path,
647       base::BindOnce(&MockUnzipListener::OnUnzipSuccess, listener.AsWeakPtr()),
648       base::BindOnce(&MockUnzipListener::OnUnzipFailure, listener.AsWeakPtr()),
649       base::BindRepeating(&MockUnzipListener::OnUnzipProgress,
650                           listener.AsWeakPtr()));
651 
652   EXPECT_EQ(0, listener.success_calls());
653   EXPECT_EQ(0, listener.failure_calls());
654   EXPECT_EQ(0, listener.progress_calls());
655 
656   base::RunLoop().RunUntilIdle();
657 
658   EXPECT_EQ(0, listener.success_calls());
659   EXPECT_EQ(1, listener.failure_calls());
660   EXPECT_LE(1, listener.progress_calls());
661 
662   std::string contents;
663   ASSERT_TRUE(base::ReadFileToString(target_path, &contents));
664   EXPECT_EQ("This file has been changed after its CRC was computed.\n",
665             contents);
666   EXPECT_EQ(contents.size(), listener.current_progress());
667 }
668 
669 // Verifies that the asynchronous extraction to a file works.
TEST_F(ZipReaderTest,ExtractToFileAsync_Directory)670 TEST_F(ZipReaderTest, ExtractToFileAsync_Directory) {
671   MockUnzipListener listener;
672 
673   ZipReader reader;
674   base::FilePath target_file = test_dir_.AppendASCII("foo");
675   base::FilePath target_path(FILE_PATH_LITERAL("foo/"));
676   ASSERT_TRUE(reader.Open(test_zip_file_));
677   ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path));
678   reader.ExtractCurrentEntryToFilePathAsync(
679       target_file,
680       base::BindOnce(&MockUnzipListener::OnUnzipSuccess, listener.AsWeakPtr()),
681       base::BindOnce(&MockUnzipListener::OnUnzipFailure, listener.AsWeakPtr()),
682       base::BindRepeating(&MockUnzipListener::OnUnzipProgress,
683                           listener.AsWeakPtr()));
684 
685   EXPECT_EQ(0, listener.success_calls());
686   EXPECT_EQ(0, listener.failure_calls());
687   EXPECT_EQ(0, listener.progress_calls());
688 
689   base::RunLoop().RunUntilIdle();
690 
691   EXPECT_EQ(1, listener.success_calls());
692   EXPECT_EQ(0, listener.failure_calls());
693   EXPECT_GE(0, listener.progress_calls());
694 
695   ASSERT_TRUE(base::DirectoryExists(target_file));
696 }
697 
TEST_F(ZipReaderTest,ExtractCurrentEntryToString)698 TEST_F(ZipReaderTest, ExtractCurrentEntryToString) {
699   // test_mismatch_size.zip contains files with names from 0.txt to 7.txt with
700   // sizes from 0 to 7 bytes respectively, being the contents of each file a
701   // substring of "0123456" starting at '0'.
702   base::FilePath test_zip_file =
703       data_dir_.AppendASCII("test_mismatch_size.zip");
704 
705   ZipReader reader;
706   std::string contents;
707   ASSERT_TRUE(reader.Open(test_zip_file));
708 
709   for (size_t i = 0; i < 8; i++) {
710     SCOPED_TRACE(base::StringPrintf("Processing %d.txt", static_cast<int>(i)));
711 
712     base::FilePath file_name = base::FilePath::FromUTF8Unsafe(
713         base::StringPrintf("%d.txt", static_cast<int>(i)));
714     ASSERT_TRUE(LocateAndOpenEntry(&reader, file_name));
715 
716     if (i > 1) {
717       // Off by one byte read limit: must fail.
718       EXPECT_FALSE(reader.ExtractCurrentEntryToString(i - 1, &contents));
719     }
720 
721     if (i > 0) {
722       // Exact byte read limit: must pass.
723       EXPECT_TRUE(reader.ExtractCurrentEntryToString(i, &contents));
724       EXPECT_EQ(std::string(base::StringPiece("0123456", i)), contents);
725     }
726 
727     // More than necessary byte read limit: must pass.
728     EXPECT_TRUE(reader.ExtractCurrentEntryToString(&contents));
729     EXPECT_EQ(std::string(base::StringPiece("0123456", i)), contents);
730   }
731   reader.Close();
732 }
733 
TEST_F(ZipReaderTest,ExtractPartOfCurrentEntry)734 TEST_F(ZipReaderTest, ExtractPartOfCurrentEntry) {
735   // test_mismatch_size.zip contains files with names from 0.txt to 7.txt with
736   // sizes from 0 to 7 bytes respectively, being the contents of each file a
737   // substring of "0123456" starting at '0'.
738   base::FilePath test_zip_file =
739       data_dir_.AppendASCII("test_mismatch_size.zip");
740 
741   ZipReader reader;
742   std::string contents;
743   ASSERT_TRUE(reader.Open(test_zip_file));
744 
745   base::FilePath file_name0 = base::FilePath::FromUTF8Unsafe("0.txt");
746   ASSERT_TRUE(LocateAndOpenEntry(&reader, file_name0));
747   EXPECT_TRUE(reader.ExtractCurrentEntryToString(0, &contents));
748   EXPECT_EQ("", contents);
749   EXPECT_TRUE(reader.ExtractCurrentEntryToString(1, &contents));
750   EXPECT_EQ("", contents);
751 
752   base::FilePath file_name1 = base::FilePath::FromUTF8Unsafe("1.txt");
753   ASSERT_TRUE(LocateAndOpenEntry(&reader, file_name1));
754   EXPECT_TRUE(reader.ExtractCurrentEntryToString(0, &contents));
755   EXPECT_EQ("", contents);
756   EXPECT_TRUE(reader.ExtractCurrentEntryToString(1, &contents));
757   EXPECT_EQ("0", contents);
758   EXPECT_TRUE(reader.ExtractCurrentEntryToString(2, &contents));
759   EXPECT_EQ("0", contents);
760 
761   base::FilePath file_name4 = base::FilePath::FromUTF8Unsafe("4.txt");
762   ASSERT_TRUE(LocateAndOpenEntry(&reader, file_name4));
763   EXPECT_TRUE(reader.ExtractCurrentEntryToString(0, &contents));
764   EXPECT_EQ("", contents);
765   EXPECT_FALSE(reader.ExtractCurrentEntryToString(2, &contents));
766   EXPECT_EQ("01", contents);
767   EXPECT_TRUE(reader.ExtractCurrentEntryToString(4, &contents));
768   EXPECT_EQ("0123", contents);
769   // Checks that entire file is extracted and function returns true when
770   // |max_read_bytes| is larger than file size.
771   EXPECT_TRUE(reader.ExtractCurrentEntryToString(5, &contents));
772   EXPECT_EQ("0123", contents);
773 
774   reader.Close();
775 }
776 
TEST_F(ZipReaderTest,ExtractPosixPermissions)777 TEST_F(ZipReaderTest, ExtractPosixPermissions) {
778   base::ScopedTempDir temp_dir;
779   ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
780 
781   ZipReader reader;
782   ASSERT_TRUE(reader.Open(data_dir_.AppendASCII("test_posix_permissions.zip")));
783   for (auto entry : {"0.txt", "1.txt", "2.txt", "3.txt"}) {
784     ASSERT_TRUE(LocateAndOpenEntry(&reader, base::FilePath::FromASCII(entry)));
785     FilePathWriterDelegate delegate(temp_dir.GetPath().AppendASCII(entry));
786     ASSERT_TRUE(reader.ExtractCurrentEntry(&delegate));
787   }
788   reader.Close();
789 
790 #if defined(OS_POSIX)
791   // This assumes a umask of at least 0400.
792   int mode = 0;
793   EXPECT_TRUE(base::GetPosixFilePermissions(
794       temp_dir.GetPath().AppendASCII("0.txt"), &mode));
795   EXPECT_EQ(mode & 0700, 0700);
796   EXPECT_TRUE(base::GetPosixFilePermissions(
797       temp_dir.GetPath().AppendASCII("1.txt"), &mode));
798   EXPECT_EQ(mode & 0700, 0600);
799   EXPECT_TRUE(base::GetPosixFilePermissions(
800       temp_dir.GetPath().AppendASCII("2.txt"), &mode));
801   EXPECT_EQ(mode & 0700, 0700);
802   EXPECT_TRUE(base::GetPosixFilePermissions(
803       temp_dir.GetPath().AppendASCII("3.txt"), &mode));
804   EXPECT_EQ(mode & 0700, 0600);
805 #endif
806 }
807 
808 // This test exposes http://crbug.com/430959, at least on OS X
TEST_F(ZipReaderTest,DISABLED_LeakDetectionTest)809 TEST_F(ZipReaderTest, DISABLED_LeakDetectionTest) {
810   for (int i = 0; i < 100000; ++i) {
811     FileWrapper zip_fd_wrapper(test_zip_file_, FileWrapper::READ_ONLY);
812     ZipReader reader;
813     ASSERT_TRUE(reader.OpenFromPlatformFile(zip_fd_wrapper.platform_file()));
814   }
815 }
816 
817 // Test that when WriterDelegate::PrepareMock returns false, no other methods on
818 // the delegate are called and the extraction fails.
TEST_F(ZipReaderTest,ExtractCurrentEntryPrepareFailure)819 TEST_F(ZipReaderTest, ExtractCurrentEntryPrepareFailure) {
820   testing::StrictMock<MockWriterDelegate> mock_writer;
821 
822   EXPECT_CALL(mock_writer, PrepareOutput()).WillOnce(Return(false));
823 
824   base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt"));
825   ZipReader reader;
826 
827   ASSERT_TRUE(reader.Open(test_zip_file_));
828   ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path));
829   ASSERT_FALSE(reader.ExtractCurrentEntry(&mock_writer));
830 }
831 
832 // Test that when WriterDelegate::WriteBytes returns false, only the OnError
833 // method on the delegate is called and the extraction fails.
TEST_F(ZipReaderTest,ExtractCurrentEntryWriteBytesFailure)834 TEST_F(ZipReaderTest, ExtractCurrentEntryWriteBytesFailure) {
835   testing::StrictMock<MockWriterDelegate> mock_writer;
836 
837   EXPECT_CALL(mock_writer, PrepareOutput()).WillOnce(Return(true));
838   EXPECT_CALL(mock_writer, WriteBytes(_, _)).WillOnce(Return(false));
839   EXPECT_CALL(mock_writer, OnError());
840 
841   base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt"));
842   ZipReader reader;
843 
844   ASSERT_TRUE(reader.Open(test_zip_file_));
845   ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path));
846   ASSERT_FALSE(reader.ExtractCurrentEntry(&mock_writer));
847 }
848 
849 // Test that extraction succeeds when the writer delegate reports all is well.
TEST_F(ZipReaderTest,ExtractCurrentEntrySuccess)850 TEST_F(ZipReaderTest, ExtractCurrentEntrySuccess) {
851   testing::StrictMock<MockWriterDelegate> mock_writer;
852 
853   EXPECT_CALL(mock_writer, PrepareOutput()).WillOnce(Return(true));
854   EXPECT_CALL(mock_writer, WriteBytes(_, _)).WillRepeatedly(Return(true));
855   EXPECT_CALL(mock_writer, SetPosixFilePermissions(_));
856   EXPECT_CALL(mock_writer, SetTimeModified(_));
857 
858   base::FilePath target_path(FILE_PATH_LITERAL("foo/bar/quux.txt"));
859   ZipReader reader;
860 
861   ASSERT_TRUE(reader.Open(test_zip_file_));
862   ASSERT_TRUE(LocateAndOpenEntry(&reader, target_path));
863   ASSERT_TRUE(reader.ExtractCurrentEntry(&mock_writer));
864 }
865 
TEST_F(ZipReaderTest,WrongCrc)866 TEST_F(ZipReaderTest, WrongCrc) {
867   ZipReader reader;
868   ASSERT_TRUE(reader.Open(data_dir_.AppendASCII("Wrong CRC.zip")));
869 
870   const ZipReader::Entry* const entry =
871       LocateAndOpenEntry(&reader, base::FilePath::FromASCII("Corrupted.txt"));
872   ASSERT_TRUE(entry);
873 
874   std::string contents = "dummy";
875   EXPECT_FALSE(reader.ExtractCurrentEntryToString(&contents));
876   EXPECT_EQ("This file has been changed after its CRC was computed.\n",
877             contents);
878 
879   contents = "dummy";
880   EXPECT_FALSE(
881       reader.ExtractCurrentEntryToString(entry->original_size + 1, &contents));
882   EXPECT_EQ("This file has been changed after its CRC was computed.\n",
883             contents);
884 
885   contents = "dummy";
886   EXPECT_FALSE(
887       reader.ExtractCurrentEntryToString(entry->original_size, &contents));
888   EXPECT_EQ("This file has been changed after its CRC was computed.\n",
889             contents);
890 
891   contents = "dummy";
892   EXPECT_FALSE(
893       reader.ExtractCurrentEntryToString(entry->original_size - 1, &contents));
894   EXPECT_EQ("This file has been changed after its CRC was computed.", contents);
895 }
896 
897 class FileWriterDelegateTest : public ::testing::Test {
898  protected:
SetUp()899   void SetUp() override {
900     ASSERT_TRUE(base::CreateTemporaryFile(&temp_file_path_));
901     file_.Initialize(temp_file_path_,
902                      (base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_READ |
903                       base::File::FLAG_WRITE | base::File::FLAG_WIN_TEMPORARY |
904                       base::File::FLAG_DELETE_ON_CLOSE));
905     ASSERT_TRUE(file_.IsValid());
906   }
907 
908   base::FilePath temp_file_path_;
909   base::File file_;
910 };
911 
TEST_F(FileWriterDelegateTest,WriteToEnd)912 TEST_F(FileWriterDelegateTest, WriteToEnd) {
913   const std::string payload = "This is the actualy payload data.\n";
914 
915   {
916     FileWriterDelegate writer(&file_);
917     EXPECT_EQ(0, writer.file_length());
918     ASSERT_TRUE(writer.PrepareOutput());
919     ASSERT_TRUE(writer.WriteBytes(payload.data(), payload.size()));
920     EXPECT_EQ(payload.size(), writer.file_length());
921   }
922 
923   EXPECT_EQ(payload.size(), file_.GetLength());
924 }
925 
TEST_F(FileWriterDelegateTest,EmptyOnError)926 TEST_F(FileWriterDelegateTest, EmptyOnError) {
927   const std::string payload = "This is the actualy payload data.\n";
928 
929   {
930     FileWriterDelegate writer(&file_);
931     EXPECT_EQ(0, writer.file_length());
932     ASSERT_TRUE(writer.PrepareOutput());
933     ASSERT_TRUE(writer.WriteBytes(payload.data(), payload.size()));
934     EXPECT_EQ(payload.size(), writer.file_length());
935     EXPECT_EQ(payload.size(), file_.GetLength());
936     writer.OnError();
937     EXPECT_EQ(0, writer.file_length());
938   }
939 
940   EXPECT_EQ(0, file_.GetLength());
941 }
942 
943 }  // namespace zip
944