/
main.cc
530 lines (456 loc) · 14.9 KB
/
main.cc
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
// Copyright 2021 Google LLC
// Copyright 2008-2019 Alexander Galanin <al@galanin.nnov.ru>
// http://galanin.nnov.ru/~al
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include "config.h"
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cstdlib>
#include <exception>
#include <limits>
#include <locale>
#include <new>
#include <string_view>
#include <fuse.h>
#include <fuse_opt.h>
#include <libgen.h>
#include <limits.h>
#include <linux/limits.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syslog.h>
#include <sys/types.h>
#include <syslog.h>
#include <unistd.h>
#include "error.h"
#include "log.h"
#include "path.h"
#include "reader.h"
#include "tree.h"
#if (LIBZIP_VERSION_MAJOR < 1)
#error "libzip >= 1.0 is required!"
#endif
#ifndef O_PATH
#define O_PATH 0
#endif
// Prints usage information.
void print_usage() {
fprintf(stderr,
R"(Mounts a ZIP archive as a FUSE filesystem
Usage: %s [options] <ZIP-file> [mount-point]
General options:
--help -h print help
--version print version
--quiet -q print fewer log messages
--verbose print more log messages
--redact redact file names from log messages
--force mount ZIP even if password is wrong or missing, or
if the encryption or compression method is unsupported
--precache preemptively decompress and cache data
--cache=DIR cache dir (default is $TMPDIR or /tmp)
--memcache cache decompressed data in memory
--nocache no caching of decompressed data
-o encoding=CHARSET original encoding of file names
-o nospecials no special files (FIFOs, sockets, devices)
-o nosymlinks no symbolic links
-o nohardlinks no hard links
)",
PROGRAM);
}
// Prints version information.
void print_version() {
fprintf(stderr, "%s version: %s\n", PROGRAM, VERSION);
fprintf(stderr, "libzip version: %s\n", LIBZIP_VERSION);
}
// Parameters for command-line argument processing function.
struct Param {
// Number of string arguments
int str_arg_count = 0;
// ZIP file name
std::string filename;
// Mount point
std::string mount_point;
// Cache dir
char* cache_dir = nullptr;
// Conversion options.
Tree::Options opts;
~Param() {
if (cache_dir)
free(cache_dir);
}
};
// FUSE operations
struct Operations : fuse_operations {
private:
// Converts a C++ exception into a negative error code.
// Also logs the error.
// Must be called from within a catch block.
static int ToError(std::string_view action, Path path) {
try {
throw;
} catch (const std::bad_alloc&) {
Log(LOG_ERR, "Cannot ", action, ' ', path, ": No memory");
return -ENOMEM;
} catch (const std::exception& e) {
Log(LOG_ERR, "Cannot ", action, ' ', path, ": ", e.what());
return -EIO;
} catch (...) {
Log(LOG_ERR, "Cannot ", action, ' ', path, ": Unexpected error");
return -EIO;
}
}
static const FileNode* GetNode(std::string_view fname) {
Tree* const tree = static_cast<Tree*>(fuse_get_context()->private_data);
assert(tree);
const FileNode* const node = tree->Find(fname);
if (!node)
Log(LOG_DEBUG, "Cannot find ", Path(fname));
return node;
}
static int GetAttr(const char* path, struct stat* st) try {
const FileNode* const node = GetNode(path);
if (!node)
return -ENOENT;
*st = *node;
return 0;
} catch (...) {
return ToError("stat", path);
}
static int ReadDir(const char* path,
void* buf,
fuse_fill_dir_t filler,
[[maybe_unused]] off_t offset,
[[maybe_unused]] fuse_file_info* fi) try {
const FileNode* const node = GetNode(path);
if (!node)
return -ENOENT;
{
const struct stat st = *node;
filler(buf, ".", &st, 0);
}
if (const FileNode* const parent = node->parent) {
const struct stat st = *parent;
filler(buf, "..", &st, 0);
} else {
filler(buf, "..", nullptr, 0);
}
for (const FileNode& child : node->children) {
const struct stat st = child;
filler(buf, child.name.c_str(), &st, 0);
}
return 0;
} catch (...) {
return ToError("read dir", path);
}
static int Open(const char* path, fuse_file_info* fi) try {
const FileNode* const node = GetNode(path);
if (!node)
return -ENOENT;
if (node->is_dir())
return -EISDIR;
Reader::Ptr reader = node->GetReader();
fi->fh = reinterpret_cast<uint64_t>(reader.release());
return 0;
} catch (...) {
return ToError("open", path);
}
static int Read(const char* path,
char* buf,
size_t size,
off_t offset,
fuse_file_info* fi) try {
if (offset < 0)
return -EINVAL;
return static_cast<int>(
reinterpret_cast<Reader*>(fi->fh)->Read(
buf, buf + std::min<size_t>(size, std::numeric_limits<int>::max()),
offset) -
buf);
} catch (...) {
return ToError("read", path);
}
static int Release([[maybe_unused]] const char* path, fuse_file_info* fi) {
const Reader::Ptr p(reinterpret_cast<Reader*>(fi->fh));
return 0;
}
static int ReadLink(const char* path, char* buf, size_t size) try {
const FileNode* const node = GetNode(path);
if (!node)
return -ENOENT;
if (node->type() != FileType::Symlink)
return -EINVAL;
const Reader::Ptr reader = node->GetReader();
buf = reader->Read(buf, buf + size - 1, 0);
*buf = '\0';
return 0;
} catch (...) {
return ToError("read link", path);
}
static int StatFs([[maybe_unused]] const char* const path,
struct statvfs* const st) {
assert(st);
const Tree* const tree =
static_cast<const Tree*>(fuse_get_context()->private_data);
assert(tree);
st->f_bsize = Tree::block_size;
st->f_frsize = Tree::block_size;
st->f_blocks = tree->GetBlockCount();
st->f_bfree = 0;
st->f_bavail = 0;
st->f_files = tree->GetNodeCount();
st->f_ffree = 0;
st->f_favail = 0;
st->f_flag = ST_RDONLY;
st->f_namemax = NAME_MAX;
return 0;
}
public:
Operations() : fuse_operations {
.getattr = GetAttr, .readlink = ReadLink, .open = Open, .read = Read,
.statfs = StatFs, .release = Release, .readdir = ReadDir,
#if FUSE_VERSION >= 28
.flag_nullpath_ok = 0, // Don't allow null path
#endif
#if FUSE_VERSION == 29
.flag_utime_omit_ok = 1,
#endif
}
{}
};
static const Operations operations;
enum {
KEY_HELP,
KEY_VERSION,
KEY_QUIET,
KEY_VERBOSE,
KEY_REDACT,
KEY_FORCE,
KEY_ENCODING,
KEY_PRE_CACHE,
KEY_MEM_CACHE,
KEY_NO_CACHE,
KEY_NO_SPECIALS,
KEY_NO_SYMLINKS,
KEY_NO_HARDLINKS,
};
// Processes command line arguments.
// Called by fuse_opt_parse().
//
// @param data pointer to Param struct
// @param arg whole argument or option
// @param key reason this function is called
// @param outargs current output argument list
// @return -1 on error, 0 if arg is to be discarded, 1 if arg should be kept
static int ProcessArg(void* data,
const char* arg,
int key,
fuse_args* outargs) {
assert(data);
Param& param = *static_cast<Param*>(data);
// 'magic' fuse_opt_proc return codes
const int KEEP = 1;
const int DISCARD = 0;
const int ERROR = -1;
switch (key) {
case KEY_HELP:
print_usage();
fuse_opt_add_arg(outargs, "-ho");
fuse_main(outargs->argc, outargs->argv, &operations, nullptr);
std::exit(EXIT_SUCCESS);
case KEY_VERSION:
print_version();
fuse_opt_add_arg(outargs, "--version");
fuse_main(outargs->argc, outargs->argv, &operations, nullptr);
std::exit(EXIT_SUCCESS);
case FUSE_OPT_KEY_NONOPT:
switch (++param.str_arg_count) {
case 1:
// zip file name
param.filename = arg;
return DISCARD;
case 2:
// mountpoint
param.mount_point = arg;
// keep it and then pass to FUSE initializer
return KEEP;
default:
fprintf(stderr,
"%s: only two arguments allowed: filename and mountpoint\n",
PROGRAM);
return ERROR;
}
case KEY_QUIET:
setlogmask(LOG_UPTO(LOG_ERR));
return DISCARD;
case KEY_VERBOSE:
setlogmask(LOG_UPTO(LOG_DEBUG));
return DISCARD;
case KEY_REDACT:
Path::redact = true;
return DISCARD;
case KEY_FORCE:
param.opts.check_password = false;
param.opts.check_compression = false;
return DISCARD;
case KEY_PRE_CACHE:
param.opts.pre_cache = true;
return DISCARD;
case KEY_MEM_CACHE:
Reader::SetCacheStrategy(CacheStrategy::InMemory);
return DISCARD;
case KEY_NO_CACHE:
Reader::SetCacheStrategy(CacheStrategy::NoCache);
return DISCARD;
case KEY_NO_SPECIALS:
param.opts.include_special_files = false;
return DISCARD;
case KEY_NO_SYMLINKS:
param.opts.include_symlinks = false;
return DISCARD;
case KEY_NO_HARDLINKS:
param.opts.include_hardlinks = false;
return DISCARD;
default:
return KEEP;
}
}
// Removes directory |dir| in destructor.
struct Cleanup {
const int dirfd = open(".", O_DIRECTORY | O_PATH);
fuse_args* args = nullptr;
std::string mount_point;
~Cleanup() {
if (!mount_point.empty()) {
if (unlinkat(dirfd, mount_point.c_str(), AT_REMOVEDIR) == 0) {
Log(LOG_DEBUG, "Removed mount point ", Path(mount_point));
} else {
Log(LOG_ERR, "Cannot remove mount point ", Path(mount_point), ": ",
strerror(errno));
}
}
if (args)
fuse_opt_free_args(args);
if (close(dirfd) < 0)
Log(LOG_ERR, "Cannot close file descriptor: ", strerror(errno));
}
};
class NumPunct : public std::numpunct<char> {
private:
char do_thousands_sep() const override { return ','; }
std::string do_grouping() const override { return "\3"; }
};
int main(int argc, char* argv[]) try {
static_assert(sizeof(void*) <= sizeof(uint64_t));
// Ensure that numbers in debug messages have thousands separators.
// It makes big numbers much easier to read (eg sizes expressed in bytes).
std::locale::global(std::locale(std::locale::classic(), new NumPunct));
openlog(PROGRAM, LOG_PERROR, LOG_USER);
setlogmask(LOG_UPTO(LOG_INFO));
fuse_args args = FUSE_ARGS_INIT(argc, argv);
Cleanup cleanup{.args = &args};
Param param;
const fuse_opt opts[] = {FUSE_OPT_KEY("--help", KEY_HELP),
FUSE_OPT_KEY("-h", KEY_HELP),
FUSE_OPT_KEY("--version", KEY_VERSION),
FUSE_OPT_KEY("--quiet", KEY_QUIET),
FUSE_OPT_KEY("-q", KEY_QUIET),
FUSE_OPT_KEY("--verbose", KEY_VERBOSE),
FUSE_OPT_KEY("-v", KEY_VERBOSE),
FUSE_OPT_KEY("--redact", KEY_REDACT),
FUSE_OPT_KEY("--force", KEY_FORCE),
FUSE_OPT_KEY("--precache", KEY_PRE_CACHE),
FUSE_OPT_KEY("--memcache", KEY_MEM_CACHE),
FUSE_OPT_KEY("--nocache", KEY_NO_CACHE),
FUSE_OPT_KEY("nospecials", KEY_NO_SPECIALS),
FUSE_OPT_KEY("nosymlinks", KEY_NO_SYMLINKS),
FUSE_OPT_KEY("nohardlinks", KEY_NO_HARDLINKS),
{"--cache=%s", offsetof(Param, cache_dir), 0},
{"encoding=%s", offsetof(Param, opts.encoding), 0},
{nullptr, 0, 0}};
if (fuse_opt_parse(&args, ¶m, opts, ProcessArg))
return EXIT_FAILURE;
// No ZIP archive name.
if (param.filename.empty()) {
print_usage();
return EXIT_FAILURE;
}
// Resolve path of cache dir if provided.
if (param.cache_dir) {
char buffer[PATH_MAX + 1];
const char* const p = realpath(param.cache_dir, buffer);
if (!p)
ThrowSystemError("Cannot use cache dir ", Path(param.cache_dir));
Reader::SetCacheDir(p);
}
// Open and index the ZIP archive.
Log(LOG_DEBUG, "Indexing ", Path(param.filename), "...");
Timer timer;
Tree::Ptr tree_ptr = Tree::Init(param.filename.c_str(), param.opts);
Tree& tree = *tree_ptr;
#ifdef NDEBUG
// For optimization, don't bother destructing the tree.
tree_ptr.release();
#endif
Log(LOG_DEBUG, "Indexed ", Path(param.filename), " in ", timer);
if (!param.mount_point.empty()) {
// Try to create the mount point directory if it doesn't exist.
if (mkdirat(cleanup.dirfd, param.mount_point.c_str(), 0777) == 0) {
Log(LOG_DEBUG, "Created mount point ", Path(param.mount_point));
cleanup.mount_point = param.mount_point;
} else if (errno == EEXIST) {
Log(LOG_DEBUG, "Mount point ", Path(param.mount_point),
" already exists");
} else {
Log(LOG_ERR, "Cannot create mount point ", Path(param.mount_point), ": ",
strerror(errno));
}
} else {
param.mount_point = Path(param.filename).WithoutExtension();
const auto n = param.mount_point.size();
for (int i = 0;;) {
if (mkdirat(cleanup.dirfd, param.mount_point.c_str(), 0777) == 0) {
Log(LOG_INFO, "Created mount point ", Path(param.mount_point));
cleanup.mount_point = param.mount_point;
fuse_opt_add_arg(&args, param.mount_point.c_str());
break;
}
if (errno != EEXIST) {
Log(LOG_ERR, "Cannot create mount point ", Path(param.mount_point),
": ", strerror(errno));
return EXIT_FAILURE;
}
Log(LOG_DEBUG, "Mount point ", Path(param.mount_point),
" already exists");
param.mount_point.resize(n);
param.mount_point += StrCat(" (", ++i, ")");
}
}
// Respect inodes number.
fuse_opt_add_arg(&args, "-ouse_ino");
// Read-only mounting.
fuse_opt_add_arg(&args, "-r");
// Single-threaded operation.
fuse_opt_add_arg(&args, "-s");
return fuse_main(args.argc, args.argv, &operations, &tree);
} catch (const ZipError& e) {
Log(LOG_ERR, e.what());
// Shift libzip error codes in order to avoid collision with FUSE errors.
const int ZIP_ER_BASE = 10;
return ZIP_ER_BASE + e.code();
} catch (const std::exception& e) {
Log(LOG_ERR, e.what());
return EXIT_FAILURE;
}