summaryrefslogtreecommitdiff
path: root/platform/default/asset_request_zip.cpp
blob: b29166f673e6ba0da0dcef8c5e643144d9fcde04 (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
#include <mbgl/storage/asset_context_base.hpp>
#include <mbgl/storage/resource.hpp>
#include <mbgl/storage/response.hpp>
#include <mbgl/util/chrono.hpp>
#include <mbgl/util/util.hpp>
#include <mbgl/util/thread.hpp>

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#include <zip.h>
#pragma GCC diagnostic pop

#include <cassert>
#include <forward_list>
#include <map>

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

namespace {

struct ZipHolder {
    ZipHolder(struct zip* archive_) : archive(archive_) {}

    ~ZipHolder() {
        if (archive) ::zip_discard(archive);
    }

    struct zip* archive;
};

struct ZipFileHolder {
    ZipFileHolder(struct zip_file* file_) : file(file_) {}

    ~ZipFileHolder() {
        if (file) ::zip_fclose(file);
    }

    struct zip_file* file;
};

class ZipIOWorker {
public:
    ZipIOWorker() = default;

    void zip_fdopen(const std::string& path,
                    std::function<void(std::unique_ptr<ZipHolder>)> cb) {
        int fd = ::open(path.c_str(), O_RDONLY, S_IRUSR);
        if (fd < 0) {
            cb(std::make_unique<ZipHolder>(nullptr));
        } else {
            int errorp;
            struct zip* archive = ::zip_fdopen(fd, 0, &errorp);
            cb(std::make_unique<ZipHolder>(archive));
        }
    }

    void zip_stat(struct zip* archive, const std::string& path,
                  std::function<void (int, std::unique_ptr<struct zip_stat>)> cb) {
        std::unique_ptr<struct zip_stat> buf = std::make_unique<struct zip_stat>();
        ::zip_stat_init(buf.get());

        int ret = ::zip_stat(archive, path.c_str(), 0,  buf.get());
        cb(ret, std::move(buf));
    }

    void zip_fopen(struct zip* archive, const std::string& path,
                   std::function<void (std::unique_ptr<ZipFileHolder>)> cb) {
        struct zip_file* file = ::zip_fopen(archive, path.c_str(), 0);
        cb(std::make_unique<ZipFileHolder>(file));
    }

    void zip_fread(struct zip_file* file, size_t size,
                   std::function<void (int, std::shared_ptr<std::string>)> cb) {
        std::shared_ptr<std::string> buf = std::make_shared<std::string>();
        buf->resize(size);

        int ret = ::zip_fread(file, &buf->front(), size);
        cb(ret, std::move(buf));
    }

    void zip_fclose(struct zip_file* file, std::function<void (int)> cb) {
        cb(::zip_fclose(file));
    }
};

}

namespace mbgl {

using namespace std::placeholders;

class AssetZipContext;

class AssetRequest : public RequestBase {
    MBGL_STORE_THREAD(tid)

public:
    AssetRequest(const Resource&, Callback, const std::string& assetRoot,
                 AssetZipContext* context, util::Thread<ZipIOWorker>* worker);
    ~AssetRequest();

    // RequestBase implementation.
    void cancel() final;

private:
    void openArchive();
    void archiveOpened(std::unique_ptr<ZipHolder>);
    void fileStated(int result, std::unique_ptr<struct zip_stat>);
    void fileOpened(std::unique_ptr<ZipFileHolder>);
    void fileRead(int result, std::shared_ptr<std::string>);
    void fileClosed();

    void close();
    void cleanup();

    void notifyError(Response::Error::Reason, const char *message);

    const std::string root;
    const std::string path;
    std::unique_ptr<Response> response;

    struct zip* archive = nullptr;
    struct zip_file* file = nullptr;
    size_t size = 0;

    AssetZipContext *context;

    util::Thread<ZipIOWorker> *worker;
    std::unique_ptr<WorkRequest> request;
};

class AssetZipContext : public AssetContextBase {
public:
    AssetZipContext();
    ~AssetZipContext();

    RequestBase* createRequest(const Resource& resource,
                               RequestBase::Callback callback,
                               const std::string& assetRoot) final {
        return new AssetRequest(resource, callback, assetRoot, this, &worker);
    }

    struct zip *getHandle(const std::string &path);
    void returnHandle(const std::string &path, struct zip *zip);

    // A list of resuable zip handles to avoid creating
    // and destroying them all the time.
    std::map<std::string, std::forward_list<struct zip*>> handles;

    util::Thread<ZipIOWorker> worker;
    std::unique_ptr<WorkRequest> request;
};

AssetZipContext::AssetZipContext()
        : worker({"ZipIOWorker", util::ThreadType::Worker, util::ThreadPriority::Regular}) {}

AssetZipContext::~AssetZipContext() {
    // Close all zip handles
    for (auto &list : handles) {
        for (auto archive : list.second) {
            zip_discard(archive);
        }
    }

    handles.clear();
}

struct zip* AssetZipContext::getHandle(const std::string &path) {
    auto &list = handles[path];
    if (!list.empty()) {
        auto archive = list.front();
        list.pop_front();
        return archive;
    } else {
        return nullptr;
    }
}

void AssetZipContext::returnHandle(const std::string &path, struct zip* archive) {
    handles[path].push_front(archive);
}

AssetRequest::AssetRequest(const Resource& resource_, Callback callback_,
    const std::string& assetRoot, AssetZipContext* context_, util::Thread<ZipIOWorker>* worker_)
    : RequestBase(resource_, callback_),
      root(assetRoot),
      path(std::string("assets/") + resource.url.substr(8)),
      context(context_),
      worker(worker_) {
    archive = context->getHandle(root);
    if (archive) {
        request = worker->invokeWithCallback(&ZipIOWorker::zip_stat,
            std::bind(&AssetRequest::fileStated, this, _1, _2), archive, path);
    } else {
        request = worker->invokeWithCallback(&ZipIOWorker::zip_fdopen,
            std::bind(&AssetRequest::archiveOpened, this, _1), root);
    }
}

AssetRequest::~AssetRequest() {
    MBGL_VERIFY_THREAD(tid);
}

void AssetRequest::cancel() {
    MBGL_VERIFY_THREAD(tid);

    request.reset();
    close();
}

void AssetRequest::archiveOpened(std::unique_ptr<ZipHolder> holder) {
    MBGL_VERIFY_THREAD(tid);

    std::swap(archive, holder->archive);

    if (!archive) {
        notifyError(Response::Error::Reason::Other, "Could not open zip archive");
        cleanup();
    } else {
        request = worker->invokeWithCallback(&ZipIOWorker::zip_stat,
            std::bind(&AssetRequest::fileStated, this, _1, _2), archive, path);
    }
}

void AssetRequest::fileStated(int result, std::unique_ptr<struct zip_stat> stat) {
    MBGL_VERIFY_THREAD(tid);

    if (result < 0 || !(stat->valid & ZIP_STAT_SIZE)) {
        notifyError(Response::Error::Reason::NotFound, "Could not stat file in zip archive");
        cleanup();
    } else {
        response = std::make_unique<Response>();

        if (stat->valid & ZIP_STAT_MTIME) {
            response->modified = Seconds(stat->mtime);
        }

        if (stat->valid & ZIP_STAT_INDEX) {
            response->etag = std::to_string(stat->index);
        }

        size = stat->size;

        request = worker->invokeWithCallback(&ZipIOWorker::zip_fopen,
            std::bind(&AssetRequest::fileOpened, this, _1), archive, path);
    }
}

void AssetRequest::fileOpened(std::unique_ptr<ZipFileHolder> holder) {
    MBGL_VERIFY_THREAD(tid);

    std::swap(file, holder->file);

    if (!file) {
        notifyError(Response::Error::Reason::NotFound, "Could not open file in zip archive"),
        cleanup();
    } else {
        request = worker->invokeWithCallback(&ZipIOWorker::zip_fread,
            std::bind(&AssetRequest::fileRead, this, _1, _2), file, size);
    }
}

void AssetRequest::fileRead(int result, std::shared_ptr<std::string> data) {
    MBGL_VERIFY_THREAD(tid);

    if (result < 0) {
        notifyError(Response::Error::Reason::Other, "Could not read file in zip archive");
    } else {
        response->data = data;
        notify(std::move(response));
    }

    close();
}

void AssetRequest::fileClosed() {
    MBGL_VERIFY_THREAD(tid);

    cleanup();
}


void AssetRequest::close() {
    MBGL_VERIFY_THREAD(tid);

    if (file) {
        request = worker->invokeWithCallback(&ZipIOWorker::zip_fclose,
            std::bind(&AssetRequest::fileClosed, this), file);
        file = nullptr;
    } else {
        cleanup();
    }
}

void AssetRequest::cleanup() {
    MBGL_VERIFY_THREAD(tid);

    if (archive) {
        context->returnHandle(root, archive);
    }

    delete this;
}

void AssetRequest::notifyError(Response::Error::Reason reason, const char *message) {
    MBGL_VERIFY_THREAD(tid);

    response = std::make_unique<Response>();
    response->error = std::make_unique<Response::Error>(reason, message);

    notify(std::move(response));
}

std::unique_ptr<AssetContextBase> AssetContextBase::createContext() {
    return std::make_unique<AssetZipContext>();
}

}