aboutsummaryrefslogtreecommitdiffstats
path: root/src/libs/utils/unarchiver.cpp
blob: aa9460012d11afb4bacc29fefd4ed25764df019b (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
// Copyright (C) 2020 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "unarchiver.h"

#include "async.h"
#include "utilstr.h"

#include <QSettings>

#include <archive.h>
#include <archive_entry.h>

using namespace Tasking;

namespace Utils {

static Result<> copy_data(struct archive *ar, struct archive *aw, QPromise<Result<>> &promise)
{
    int r;
    const void *buff;
    size_t size;
    la_int64_t offset;

    while (!promise.isCanceled()) {
        r = archive_read_data_block(ar, &buff, &size, &offset);
        if (r == ARCHIVE_EOF)
            break;
        if (r < ARCHIVE_OK)
            return ResultError(QString::fromUtf8(archive_error_string(ar)));
        r = archive_write_data_block(aw, buff, size, offset);
        if (r < ARCHIVE_OK)
            return ResultError(QString::fromUtf8(archive_error_string(aw)));
    }
    return ResultOk;
}

static void readFree(struct archive *a)
{
    archive_read_close(a);
    archive_read_free(a);
}

static void writeFree(struct archive *a)
{
    archive_write_close(a);
    archive_write_free(a);
}

struct ReadData
{
    QFile file;
    char data[10240];
};

static int _open(struct archive *a, void *client_data)
{
    ReadData *data = static_cast<ReadData *>(client_data);
    if (!data->file.open(QIODevice::ReadOnly)) {
        archive_set_error(a, EIO, "Open error: %s", data->file.errorString().toUtf8().data());
        return ARCHIVE_FATAL;
    }

    return ARCHIVE_OK;
}

static la_ssize_t _read(struct archive *a, void *client_data, const void **buff)
{
    Q_UNUSED(a)
    ReadData *data = static_cast<ReadData *>(client_data);
    *buff = data->data;
    return data->file.read(data->data, 10240);
}

int _close(struct archive *a, void *client_data)
{
    Q_UNUSED(a)
    ReadData *data = static_cast<ReadData *>(client_data);
    data->file.close();
    return ARCHIVE_OK;
}

static int64_t _skip(struct archive *a, void *client_data, int64_t request)
{
    ReadData *data = static_cast<ReadData *>(client_data);
    if (data->file.skip(request))
        return request;
    archive_set_error(a, EIO, "Skip error: %s", data->file.errorString().toUtf8().data());
    return -1;
}

static int64_t _seek(struct archive *a, void *client_data, int64_t request, int whence)
{
    ReadData *data = static_cast<ReadData *>(client_data);
    switch (whence) {
    case SEEK_SET:
        break;
    case SEEK_CUR:
        request += data->file.pos();
        break;
    case SEEK_END:
        request = data->file.size() - request;
        break;
    }
    if (!data->file.seek(request)) {
        archive_set_error(a, EIO, "Seek error: %s", data->file.errorString().toUtf8().data());
        return ARCHIVE_FATAL;
    }
    return data->file.pos();
}

static Result<> unarchive(
    QPromise<Result<>> &promise, const Utils::FilePath &archive, const Utils::FilePath &destination)
{
    struct archive_entry *entry;
    int flags;
    int r;

    /* Select which attributes we want to restore. */
    flags = ARCHIVE_EXTRACT_TIME;
    flags |= ARCHIVE_EXTRACT_PERM;
    flags |= ARCHIVE_EXTRACT_ACL;
    flags |= ARCHIVE_EXTRACT_FFLAGS;

    ReadData data{QFile(archive.toFSPathString()), {}};
    std::unique_ptr<struct archive, decltype(&readFree)> a(archive_read_new(), readFree);

    if (archive_read_support_format_all(a.get()) != ARCHIVE_OK
        || archive_read_support_format_raw(a.get()) != ARCHIVE_OK
        || archive_read_support_filter_all(a.get()) != ARCHIVE_OK) {
        return ResultError(QString("archive_read_ setup failed: %1")
                                 .arg(QString::fromUtf8(archive_error_string(a.get()))));
    }

    std::unique_ptr<struct archive, decltype(&writeFree)> ext(archive_write_disk_new(), writeFree);

    if (archive_write_disk_set_options(ext.get(), flags) != ARCHIVE_OK
        || archive_write_disk_set_standard_lookup(ext.get()) != ARCHIVE_OK) {
        return ResultError(QString("archive_write_disk_ setup failed: %1")
                                 .arg(QString::fromUtf8(archive_error_string(ext.get()))));
    }

    if (archive_read_append_callback_data(a.get(), &data) != (ARCHIVE_OK))
        return ResultError(
            QString("Could not append callback data to %1").arg(archive.toUserOutput()));

    if (archive_read_set_open_callback(a.get(), _open) != ARCHIVE_OK
        || archive_read_set_read_callback(a.get(), _read) != ARCHIVE_OK
        || archive_read_set_skip_callback(a.get(), _skip) != ARCHIVE_OK
        || archive_read_set_seek_callback(a.get(), _seek) != ARCHIVE_OK
        || archive_read_set_close_callback(a.get(), _close)) {
        return ResultError(QString("Could not set callbacks: %1")
                                 .arg(QString::fromUtf8(archive_error_string(a.get()))));
    }

    if ((r = archive_read_open1(a.get())))
        return ResultError(QString::fromUtf8(archive_error_string(a.get())));

    int fileNumber = 0;
    while (!promise.isCanceled()) {
        r = archive_read_next_header(a.get(), &entry);

        const int format = archive_format(a.get());
        const int filter = archive_filter_code(a.get(), 0);

        if (format == ARCHIVE_FORMAT_RAW && filter == ARCHIVE_FILTER_NONE)
            return ResultError(Tr::tr("Not an archive."));

        if (r == ARCHIVE_EOF)
            break;

        if (r < ARCHIVE_OK) {
            return ResultError(QString::fromUtf8(archive_error_string(a.get())));
        }

        ++fileNumber;
        promise.setProgressRange(0, fileNumber);
        promise.setProgressValueAndText(
            fileNumber, QString::fromUtf8(archive_entry_pathname_utf8(entry)));

        archive_entry_set_pathname_utf8(
            entry,
            (destination / QString::fromUtf8(archive_entry_pathname_utf8(entry))).path().toUtf8());

        r = archive_write_header(ext.get(), entry);
        if (r < ARCHIVE_OK) {
            return ResultError(QString::fromUtf8(archive_error_string(ext.get())));
        } else {
            const struct stat *stat = archive_entry_stat(entry);
            // Is regular file ? (See S_ISREG macro in stat.h)
            if ((((stat->st_mode) & 0170000) == 0100000)) {
                r = copy_data(a.get(), ext.get(), promise).has_value();
                if (r < ARCHIVE_OK) {
                    return ResultError(QString::fromUtf8(archive_error_string(ext.get())));
                }
            }
        }
        r = archive_write_finish_entry(ext.get());
        if (r < ARCHIVE_OK) {
            return ResultError(QString::fromUtf8(archive_error_string(ext.get())));
        }
    }
    return ResultOk;
}

static void unarchivePromised(
    QPromise<Result<>> &promise, const Utils::FilePath &archive, const Utils::FilePath &destination)
{
    promise.addResult(unarchive(promise, archive, destination));
}

Unarchiver::Unarchiver()
{
    m_async.setThreadPool(QThreadPool::globalInstance());

    connect(&m_async, &AsyncBase::started, this, &Unarchiver::started);
    connect(&m_async, &AsyncBase::progressTextChanged, this, [this](const QString &text) {
        emit progress(FilePath::fromString(text));
    });
    connect(&m_async, &AsyncBase::done, this, [this] {
        Result<> result = m_async.isCanceled() ? ResultError(QString()) : m_async.result();
        emit done(result ? DoneResult::Success : DoneResult::Error);
    });
}

void Unarchiver::start()
{
    m_async.setConcurrentCallData(unarchivePromised, m_archive, m_destination);
    m_async.start();
}

Result<> Unarchiver::result() const
{
    if (m_async.isCanceled())
        return ResultError(Tr::tr("Canceled."));
    return m_async.result();
}

void Unarchiver::setArchive(const FilePath &archive)
{
    m_archive = archive;
}

void Unarchiver::setDestination(const FilePath &destination)
{
    m_destination = destination;
}

bool Unarchiver::isDone() const
{
    return m_async.isDone();
}

bool Unarchiver::isCanceled() const
{
    return m_async.isCanceled();
}

} // namespace Utils