summaryrefslogtreecommitdiffstats
path: root/src/core/file_sys/vfs_libzip.cpp
blob: 64f19a0eaeda54ad2042e17cb0979a4c1060d2cb (plain) (blame)
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
// Copyright 2019 yuzu emulator team
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

#include <string>
#include <zip.h>
#include "common/logging/backend.h"
#include "core/file_sys/vfs.h"
#include "core/file_sys/vfs_libzip.h"
#include "core/file_sys/vfs_vector.h"

namespace FileSys {

VirtualDir ExtractZIP(VirtualFile file) {
    zip_error_t error{};

    const auto data = file->ReadAllBytes();
    const auto src = zip_source_buffer_create(data.data(), data.size(), 0, &error);
    if (src == nullptr)
        return nullptr;

    const auto zip = zip_open_from_source(src, 0, &error);
    if (zip == nullptr)
        return nullptr;

    std::shared_ptr<VectorVfsDirectory> out = std::make_shared<VectorVfsDirectory>();

    const auto num_entries = zip_get_num_entries(zip, 0);
    if (num_entries == -1)
        return nullptr;

    zip_stat_t stat{};
    zip_stat_init(&stat);

    for (std::size_t i = 0; i < num_entries; ++i) {
        const auto stat_res = zip_stat_index(zip, i, 0, &stat);
        if (stat_res == -1)
            return nullptr;

        const std::string name(stat.name);
        if (name.empty())
            continue;

        if (name[name.size() - 1] != '/') {
            const auto file = zip_fopen_index(zip, i, 0);

            std::vector<u8> buf(stat.size);
            if (zip_fread(file, buf.data(), buf.size()) != buf.size())
                return nullptr;

            zip_fclose(file);

            const auto parts = FileUtil::SplitPathComponents(stat.name);
            const auto new_file = std::make_shared<VectorVfsFile>(buf, parts.back());

            std::shared_ptr<VectorVfsDirectory> dtrv = out;
            for (std::size_t j = 0; j < parts.size() - 1; ++j) {
                if (dtrv == nullptr)
                    return nullptr;
                const auto subdir = dtrv->GetSubdirectory(parts[j]);
                if (subdir == nullptr) {
                    const auto temp = std::make_shared<VectorVfsDirectory>(
                        std::vector<VirtualFile>{}, std::vector<VirtualDir>{}, parts[j]);
                    dtrv->AddDirectory(temp);
                    dtrv = temp;
                } else {
                    dtrv = std::dynamic_pointer_cast<VectorVfsDirectory>(subdir);
                }
            }

            if (dtrv == nullptr)
                return nullptr;
            dtrv->AddFile(new_file);
        }
    }

    zip_source_close(src);
    zip_close(zip);

    return out;
}

} // namespace FileSys