-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathfuse-archive.cc
More file actions
3956 lines (3339 loc) · 111 KB
/
fuse-archive.cc
File metadata and controls
3956 lines (3339 loc) · 111 KB
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 The Fuse-Archive Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// fuse-archive mounts an archive or compressed file (e.g. foo.tar, foo.tar.gz,
// foo.xz, foo.zip) as a read-only FUSE file system
// (https://en.wikipedia.org/wiki/Filesystem_in_Userspace).
#include <archive.h>
#include <archive_entry.h>
#include <fcntl.h>
#include <fuse.h>
#include <langinfo.h>
#include <locale.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syslog.h>
#include <sys/types.h>
#include <syslog.h>
#include <termios.h>
#include <unistd.h>
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cerrno>
#include <chrono>
#include <climits>
#include <compare>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <locale>
#include <memory>
#include <ostream>
#include <span>
#include <sstream>
#include <string>
#include <string_view>
#include <system_error>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <boost/functional/hash.hpp>
#include <boost/intrusive/list.hpp>
#include <boost/intrusive/slist.hpp>
#include <boost/intrusive/unordered_set.hpp>
// ---- Compile-time Configuration
#define PROGRAM_NAME "fuse-archive"
// Even minor versions (e.g. 1.0 or 1.2) are stable versions.
// Odd minor versions (e.g. 1.1 or 1.3) are development versions.
#define PROGRAM_VERSION "1.19"
namespace {
// Type alias for shorter code.
using i64 = std::int64_t;
template <typename... Args>
std::string StrCat(Args&&... args) {
std::ostringstream out;
(out << ... << std::forward<Args>(args));
return std::move(out).str();
}
// Timer for debug logs.
struct Timer {
using Clock = std::chrono::steady_clock;
// Start time.
Clock::time_point start = Clock::now();
// Resets this timer.
void Reset() { start = Clock::now(); }
// Elapsed time in milliseconds.
auto Milliseconds() const {
return std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() -
start)
.count();
}
friend std::ostream& operator<<(std::ostream& out, const Timer& timer) {
return out << timer.Milliseconds() << " ms";
}
};
enum class LogLevel {
DEBUG = LOG_DEBUG,
INFO = LOG_INFO,
WARNING = LOG_WARNING,
ERROR = LOG_ERR,
};
LogLevel g_log_level = LogLevel::INFO;
void SetLogLevel(LogLevel const level) {
g_log_level = level;
setlogmask(LOG_UPTO(static_cast<int>(level)));
}
#define LOG_IS_ON(level) (LogLevel::level <= g_log_level)
bool g_latest_log_is_ephemeral = false;
enum class ProgressMessage : int;
// Accumulates a log message and logs it.
class Logger {
public:
explicit Logger(LogLevel const level, int err = -1)
: level_(level), err_(err) {}
Logger(const Logger&) = delete;
~Logger() {
if (err_ >= 0) {
if (LOG_IS_ON(DEBUG)) {
oss_ << ": Error " << err_;
}
oss_ << ": " << strerror(err_);
}
if (g_latest_log_is_ephemeral && isatty(STDERR_FILENO)) {
std::string_view const s = "\e[F\e[K";
std::ignore = write(STDERR_FILENO, s.data(), s.size());
}
syslog(static_cast<int>(level_), "%s", std::move(oss_).str().c_str());
g_latest_log_is_ephemeral = ephemeral_;
}
Logger&& operator<<(const auto& a) && {
oss_ << a;
return std::move(*this);
}
Logger&& operator<<(ProgressMessage const a) && {
oss_ << static_cast<int>(a) << "%";
ephemeral_ = true;
return std::move(*this);
}
private:
LogLevel const level_;
int const err_;
std::ostringstream oss_;
bool ephemeral_ = false;
};
#define LOG(level) \
if (LogLevel::level <= g_log_level) \
Logger(LogLevel::level)
#define PLOG(level) \
if (LogLevel::level <= g_log_level) \
Logger(LogLevel::level, errno)
// A scoped file descriptor.
class ScopedFile {
public:
// Closes this file descriptor if it is valid.
~ScopedFile() {
if (IsValid() && close(fd_) < 0) {
PLOG(ERROR) << "Cannot close file";
}
}
// Creates an invalid file descriptor.
ScopedFile() noexcept : fd_(-1) {}
// Takes ownership of the given file descriptor, if it is valid.
explicit ScopedFile(int fd) noexcept : fd_(fd) {}
// Move constructor.
ScopedFile(ScopedFile&& other) noexcept : fd_(std::exchange(other.fd_, -1)) {}
// Swaps this file descriptor with the other one.
void SwapWith(ScopedFile& other) noexcept { std::swap(fd_, other.fd_); }
// Closes this file descriptor if it is valid.
void Close() noexcept {
ScopedFile other;
SwapWith(other);
}
// Universal assignment operator.
ScopedFile& operator=(ScopedFile other) noexcept {
SwapWith(other);
return *this;
}
// Is this file descriptor valid?
bool IsValid() const noexcept { return fd_ >= 0; }
// Gets the underlying raw file descriptor.
operator int() const noexcept { return fd_; }
private:
// Raw file descriptor.
int fd_;
};
// ---- Exit Codes
// These are values passed to the exit function, or returned by main. These are
// (Linux or Linux-like) application exit codes, not library error codes.
//
// Note that, unless the -f command line option was passed for foreground
// operation, the parent process may very well ignore the exit code value after
// daemonization succeeds.
enum class ExitCode {
GENERIC_FAILURE = 1,
CANNOT_CREATE_MOUNT_POINT = 10,
CANNOT_OPEN_ARCHIVE = 11,
CANNOT_CREATE_CACHE = 12,
CANNOT_WRITE_CACHE = 13,
PASSPHRASE_REQUIRED = 20,
PASSPHRASE_INCORRECT = 21,
PASSPHRASE_NOT_SUPPORTED = 22,
UNKNOWN_ARCHIVE_FORMAT = 30,
INVALID_ARCHIVE_HEADER = 31,
INVALID_ARCHIVE_CONTENTS = 32,
};
std::ostream& operator<<(std::ostream& out, ExitCode const e) {
switch (e) {
#define PRINT(s) \
case ExitCode::s: \
return out << #s << " (" << int(ExitCode::s) << ")";
PRINT(GENERIC_FAILURE)
PRINT(CANNOT_CREATE_MOUNT_POINT)
PRINT(CANNOT_OPEN_ARCHIVE)
PRINT(CANNOT_CREATE_CACHE)
PRINT(CANNOT_WRITE_CACHE)
PRINT(PASSPHRASE_REQUIRED)
PRINT(PASSPHRASE_INCORRECT)
PRINT(PASSPHRASE_NOT_SUPPORTED)
PRINT(UNKNOWN_ARCHIVE_FORMAT)
PRINT(INVALID_ARCHIVE_HEADER)
PRINT(INVALID_ARCHIVE_CONTENTS)
#undef PRINT
}
return out << "Exit Code " << int(e);
}
std::string_view GetErrorString(archive* const a) {
// Work around bug https://github.com/libarchive/libarchive/issues/2495.
return archive_error_string(a) ?: "Unspecified error";
}
// ---- Platform specifics
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
#define lseek64 lseek
#endif
// ---- Globals
enum {
KEY_HELP,
KEY_VERSION,
KEY_QUIET,
KEY_VERBOSE,
KEY_REDACT,
KEY_FORCE,
KEY_LAZY_CACHE,
KEY_NO_CACHE,
KEY_NO_MERGE,
KEY_NO_TRIM,
KEY_NO_DIRS,
KEY_NO_SPECIALS,
KEY_NO_SYMLINKS,
KEY_NO_HARDLINKS,
KEY_NO_XATTRS,
KEY_DEFAULT_PERMISSIONS,
#if FUSE_USE_VERSION >= 30
KEY_DIRECT_IO,
#endif
};
struct Options {
unsigned int dmask = 0022;
unsigned int fmask = 0022;
int max_filter_count = 1;
};
Options g_options;
fuse_opt const g_fuse_opts[] = {
FUSE_OPT_KEY("--help", KEY_HELP),
FUSE_OPT_KEY("-h", KEY_HELP),
FUSE_OPT_KEY("--version", KEY_VERSION),
FUSE_OPT_KEY("-V", KEY_VERSION),
FUSE_OPT_KEY("--quiet", KEY_QUIET),
FUSE_OPT_KEY("quiet", KEY_QUIET),
FUSE_OPT_KEY("-q", KEY_QUIET),
FUSE_OPT_KEY("--verbose", KEY_VERBOSE),
FUSE_OPT_KEY("verbose", KEY_VERBOSE),
FUSE_OPT_KEY("-v", KEY_VERBOSE),
FUSE_OPT_KEY("--redact", KEY_REDACT),
FUSE_OPT_KEY("redact", KEY_REDACT),
FUSE_OPT_KEY("force", KEY_FORCE),
FUSE_OPT_KEY("lazycache", KEY_LAZY_CACHE),
FUSE_OPT_KEY("nocache", KEY_NO_CACHE),
FUSE_OPT_KEY("nomerge", KEY_NO_MERGE),
FUSE_OPT_KEY("notrim", KEY_NO_TRIM),
FUSE_OPT_KEY("nodirs", KEY_NO_DIRS),
FUSE_OPT_KEY("nospecials", KEY_NO_SPECIALS),
FUSE_OPT_KEY("nosymlinks", KEY_NO_SYMLINKS),
FUSE_OPT_KEY("nohardlinks", KEY_NO_HARDLINKS),
FUSE_OPT_KEY("noxattrs", KEY_NO_XATTRS),
FUSE_OPT_KEY("default_permissions", KEY_DEFAULT_PERMISSIONS),
#if FUSE_USE_VERSION >= 30
FUSE_OPT_KEY("direct_io", KEY_DIRECT_IO),
#endif
{"dmask=%o", offsetof(Options, dmask)},
{"fmask=%o", offsetof(Options, fmask)},
{"maxfilters=%d", offsetof(Options, max_filter_count)},
FUSE_OPT_END,
};
// Command line options.
bool g_help = false;
bool g_version = false;
bool g_redact = false;
bool g_force = false;
bool g_merge = true;
bool g_trim = true;
bool g_dirs = true;
bool g_specials = true;
bool g_symlinks = true;
bool g_hardlinks = true;
bool g_xattrs = true;
bool g_default_permissions = false;
#if FUSE_USE_VERSION >= 30
bool g_direct_io = false;
#endif
// Path of the mount point.
std::string g_mount_point;
// Possible caching strategies.
enum class Cache {
None, // No caching.
Lazy, // Incremental caching.
Full, // Full caching.
};
// Caching strategy.
Cache g_cache = Cache::Full;
// File descriptor of the cache file.
ScopedFile g_cache_fd;
// Size of the cache file.
i64 g_cache_size = 0;
// Decryption password.
std::string g_password;
// Number of times the decryption password has been requested.
int g_password_count = 0;
// Has the password been actually checked yet?
bool g_password_checked = false;
// We support 'cooked' archive files (e.g. foo.tar.gz or foo.zip) but also what
// libarchive calls 'raw' files (e.g. foo.gz), which are compressed but not
// explicitly an archive (a collection of files). libarchive can still present
// it as an implicit archive containing 1 file.
enum class ArchiveFormat : int {
NONE = 0,
RAW = ARCHIVE_FORMAT_RAW,
};
std::ostream& operator<<(std::ostream& out, ArchiveFormat const f) {
switch (static_cast<int>(f)) {
case 0:
return out << "NONE";
#define PRINT(s) \
case ARCHIVE_FORMAT_##s: \
return out << #s;
PRINT(CPIO)
PRINT(CPIO_POSIX)
PRINT(CPIO_BIN_LE)
PRINT(CPIO_BIN_BE)
PRINT(CPIO_SVR4_NOCRC)
PRINT(CPIO_SVR4_CRC)
PRINT(CPIO_AFIO_LARGE)
PRINT(CPIO_PWB)
PRINT(SHAR)
PRINT(SHAR_BASE)
PRINT(SHAR_DUMP)
PRINT(TAR)
PRINT(TAR_USTAR)
PRINT(TAR_PAX_INTERCHANGE)
PRINT(TAR_PAX_RESTRICTED)
PRINT(TAR_GNUTAR)
PRINT(ISO9660)
PRINT(ISO9660_ROCKRIDGE)
PRINT(ZIP)
PRINT(EMPTY)
PRINT(AR)
PRINT(AR_GNU)
PRINT(AR_BSD)
PRINT(MTREE)
PRINT(RAW)
PRINT(XAR)
PRINT(LHA)
PRINT(CAB)
PRINT(RAR)
PRINT(7ZIP)
PRINT(WARC)
PRINT(RAR_V5)
#undef PRINT
}
return out << static_cast<int>(f);
}
// g_uid and g_gid are the user/group IDs for the files we serve. They're the
// same as the current uid/gid.
//
// libfuse will override GetAttr's use of these variables if the "-o uid=N" or
// "-o gid=N" command line options are set.
uid_t const g_uid = getuid();
gid_t const g_gid = getgid();
using Clock = std::chrono::system_clock;
time_t const g_now = Clock::to_time_t(Clock::now());
size_t hash(std::string_view const s) {
size_t h = 0;
for (char const c : s) {
boost::hash_combine(h, c);
}
return h;
}
// A string view and its hashed value.
struct HashedStringView {
std::string_view string;
size_t string_hash = hash(string);
};
// A string and its hashed value.
struct HashedString {
std::string string;
size_t string_hash;
HashedString(const HashedStringView& x)
: string(x.string), string_hash(x.string_hash) {}
};
// Function object that compares HashedStringView and HashedString objects for
// equality.
struct IsEqual {
using is_transparent = std::true_type;
bool operator()(const auto& a, const auto& b) const {
return a.string_hash == b.string_hash && a.string == b.string;
}
};
// Function object that gets the hashed value of HashedStringView and
// HashedString objects.
struct Hash {
using is_transparent = std::true_type;
size_t operator()(const auto& x) const { return x.string_hash; }
};
// Set of unique (i.e. deduplicated) strings. Lazily constructed and populated.
// Never destructed.
using HashedStrings = std::unordered_set<HashedString, Hash, IsEqual>;
HashedStrings* g_unique_strings = nullptr;
// Gets a pointer to the unique registered string matching the given string, or
// null if no such string has been registered.
const HashedString* GetUniqueOrNull(std::string_view const s) {
if (!g_unique_strings) {
return nullptr;
}
HashedStrings::const_iterator const it =
g_unique_strings->find(HashedStringView(s));
if (it == g_unique_strings->cend()) {
return nullptr;
}
assert(it->string == s);
assert(it->string.data() != s.data());
return &*it;
}
// Gets a non-null pointer to the unique registered string matching the given
// string, creating and registering it if necessary.
const HashedString* GetOrCreateUnique(std::string_view const s) {
if (!g_unique_strings) {
g_unique_strings = new HashedStrings();
}
HashedStrings::const_iterator const it =
g_unique_strings->insert(HashedStringView(s)).first;
assert(it != g_unique_strings->cend());
assert(it->string == s);
assert(it->string.data() != s.data());
return &*it;
}
// Converts a string to ASCII lower case.
std::string ToLower(std::string_view const s) {
std::string r(s);
for (char& c : r) {
if ('A' <= c && c <= 'Z') {
c += 'a' - 'A';
}
}
return r;
}
// Path manipulations.
class Path : public std::string_view {
public:
Path() = default;
Path(const char* const path) : std::string_view(path) {}
Path(std::string_view const path) : std::string_view(path) {}
// Removes trailing separators.
Path WithoutTrailingSeparator() const {
Path path = *this;
// Don't remove the first character, even if it is a '/'.
while (path.size() > 1 && path.back() == '/') {
path.remove_suffix(1);
}
return path;
}
// Gets the position of the dot where the filename extension starts, or
// `size()` if there is no extension.
//
// If the path ends with a slash, then it does not have an extension:
// * "/" -> no extension
// * "foo/" -> no extension
// * "a.b/" -> no extension
//
// If the path ends with a dot, then it does not have an extension:
// * "." -> no extension
// * ".." -> no extension
// * "..." -> no extension
// * "foo." -> no extension
// * "foo..." -> no extension
//
// If the filename starts with a dot or a sequence of dots, but does not have
// any other dot after that, then it does not have an extension:
// ".foo" -> no extension
// "...foo" -> no extension
// "a.b/...foo" -> no extension
//
// An extension cannot contain a space:
// * "foo. " -> no extension
// * "foo.a b" -> no extension
// * "foo. (1)" -> no extension
//
// An extension cannot be longer than 8 bytes, including the leading dot:
// * "foo.tool" -> ".tool"
// * "foo.toolongforanextension" -> no extension
size_type FinalExtensionPosition() const {
size_type const last_dot = find_last_of("/. ");
if (last_dot == npos || at(last_dot) != '.' || last_dot == 0 ||
last_dot == size() - 1 || size() - last_dot > 8) {
return size();
}
if (size_type const i = find_last_not_of('.', last_dot - 1);
i == npos || at(i) == '/') {
return size();
}
return last_dot;
}
// Same as FinalExtensionPosition, but also takes in account some double
// extensions such as ".tar.gz".
size_type ExtensionPosition() const {
size_type const last_dot = FinalExtensionPosition();
if (last_dot >= size()) {
return last_dot;
}
// Extract extension without dot and in ASCII lowercase.
assert(at(last_dot) == '.');
const std::string ext = ToLower(substr(last_dot + 1));
// Is it a special extension?
static std::unordered_set<std::string_view> const special_exts = {
"asc", "b64", "base64", "br", "brotli", "bz2", "bzip2",
"gpg", "grz", "grzip", "gz", "gzip", "lrz", "lrzip",
"lz", "lzip", "lz4", "lzma", "lzo", "lzop", "pgp",
"uu", "xz", "z", "zst", "zstd"};
if (special_exts.contains(ext)) {
return Path(substr(0, last_dot)).FinalExtensionPosition();
}
return last_dot;
}
// Removes the final extension, if any.
Path WithoutFinalExtension() const {
return substr(0, FinalExtensionPosition());
}
// Removes the extension, if any.
Path WithoutExtension() const { return substr(0, ExtensionPosition()); }
// Gets a safe truncation position `x` such that `0 <= x && x <= i`. Avoids
// truncating in the middle of a multi-byte UTF-8 sequence. Returns `size()`
// if `i >= size()`.
size_type TruncationPosition(size_type i) const {
if (i >= size()) {
return size();
}
while (true) {
// Avoid truncating at a UTF-8 trailing byte.
while (i > 0 && (at(i) & 0b1100'0000) == 0b1000'0000) {
--i;
}
if (i == 0) {
return i;
}
std::string_view const zero_width_joiner = "\u200D";
// Avoid truncating at a zero-width joiner.
if (substr(i).starts_with(zero_width_joiner)) {
--i;
continue;
}
// Avoid truncating just after a zero-width joiner.
if (substr(0, i).ends_with(zero_width_joiner)) {
i -= zero_width_joiner.size();
if (i > 0) {
--i;
continue;
}
}
return i;
}
}
// Splits path between parent path and basename.
std::pair<Path, Path> Split() const {
std::string_view::size_type const i = find_last_of('/') + 1;
return {Path(substr(0, i)).WithoutTrailingSeparator(), substr(i)};
}
// Appends the |tail| path to |*head|. If |tail| is an absolute path, then
// |*head| takes the value of |tail|. If |tail| is a relative path, then it is
// appended to |*head|. A '/' separator is added if |*head| doesn't already
// end with one.
static void Append(std::string* const head, std::string_view const tail) {
assert(head);
if (tail.empty()) {
return;
}
if (head->empty() || tail.starts_with('/')) {
*head = tail;
return;
}
assert(!head->empty());
assert(!tail.empty());
if (!head->ends_with('/')) {
*head += '/';
}
*head += tail;
}
bool Consume(std::string_view const prefix) {
bool const ok = starts_with(prefix);
if (ok) {
remove_prefix(prefix.size());
}
return ok;
}
bool Consume(char const prefix) {
bool const ok = starts_with(prefix);
if (ok) {
remove_prefix(1);
}
return ok;
}
// Gets normalized path.
std::string Normalized(std::string prefix = "/") const {
NormalizeAppend(&prefix);
return prefix;
}
void NormalizeAppend(std::string* const to) const {
assert(to);
std::string& result = *to;
Path in = *this;
if (in.empty()) {
Append(&result, "?");
return;
}
if (in == ".") {
return;
}
do {
while (in.Consume('/')) {
}
} while (in.Consume("./") || in.Consume("../"));
const size_t initial_size = result.size();
// Extract part after part
while (true) {
size_type i = in.find_first_not_of('/');
if (i == npos) {
break;
}
in.remove_prefix(i);
assert(!in.empty());
i = in.find_first_of('/');
std::string_view part = in.substr(0, i);
assert(!part.empty());
in.remove_prefix(part.size());
std::string_view extension;
if (i == npos) {
const size_type last_dot = Path(part).ExtensionPosition();
extension = part.substr(last_dot);
part.remove_suffix(extension.size());
}
part = part.substr(
0, Path(part).TruncationPosition(NAME_MAX - extension.size()));
if (part.empty() || part == "." || part == "..") {
part = "?";
}
if (extension.empty()) {
Append(&result, part);
} else {
Append(&result, StrCat(part, extension));
}
}
if (result.size() > PATH_MAX) {
std::string last_part(Path(result).Split().second);
result.resize(initial_size);
Append(&result, "Too Deep");
Append(&result, last_part);
}
}
};
std::ostream& operator<<(std::ostream& out, Path const path) {
if (g_redact) {
return out << "(redacted)";
}
out.put('\'');
for (char const c : path) {
switch (c) {
case '\\':
case '\'':
out.put('\\');
out.put(c);
break;
default:
int const i = static_cast<unsigned char>(c);
if (std::iscntrl(i)) {
out << "\\x" << std::hex << std::setw(2) << std::setfill('0') << i
<< std::dec;
} else {
out.put(c);
}
}
}
out.put('\'');
return out;
}
// An open archive file descriptor with other archive metadata.
struct ArchiveDescriptor {
// Command line argument naming the archive file.
std::string path;
// Archive name without its extension.
std::string name_without_extension;
// File descriptor of the opened archive file.
ScopedFile fd;
// Size of this archive file.
i64 size = 0;
// Format of this archive.
ArchiveFormat format = ArchiveFormat::NONE;
// Number of decompression or decoding filters (e.g. `gz`, `bz2`, `br`, `uu`,
// `b64`).
int filter_count = 0;
// Is there an archive format that requires caching and random access to the
// decompressed data?
bool filtered_zip = false;
};
std::vector<ArchiveDescriptor> g_archives;
enum class FileType : mode_t {
BlockDevice = S_IFBLK, // Block-oriented device
CharDevice = S_IFCHR, // Character-oriented device
Directory = S_IFDIR, // Directory
Fifo = S_IFIFO, // FIFO or pipe
File = S_IFREG, // Regular file
Socket = S_IFSOCK, // Socket
Symlink = S_IFLNK, // Symbolic link
};
FileType GetFileType(mode_t const mode) {
// Consider an unknown file type as a regular file.
// https://github.com/google/fuse-archive/issues/47
const mode_t ft = mode & S_IFMT;
return ft ? FileType(ft) : FileType::File;
}
std::ostream& operator<<(std::ostream& out, FileType const t) {
switch (t) {
case FileType::BlockDevice:
return out << "Block Device";
case FileType::CharDevice:
return out << "Character Device";
case FileType::Directory:
return out << "Directory";
case FileType::Fifo:
return out << "FIFO";
case FileType::File:
return out << "File";
case FileType::Socket:
return out << "Socket";
case FileType::Symlink:
return out << "Symlink";
}
return out << "Unknown";
}
constexpr blksize_t block_size = 512;
// Total number of blocks taken by the tree of nodes.
blkcnt_t g_block_count = 1;
// Total number of original inodes (i.e. not counting hard links) taken by the
// tree of nodes.
fsfilcnt_t g_inode_count = 1;
using Archive = struct archive;
using Entry = struct archive_entry;
struct ArchiveDeleter {
void operator()(Archive* const a) const { archive_read_free(a); }
};
using ArchivePtr = std::unique_ptr<Archive, ArchiveDeleter>;
const char* ReadPassword(Archive*, void*);
// Converts libarchive errors to fuse-archive exit codes. libarchive doesn't
// have designated passphrase-related error numbers. As for whether a particular
// archive file's encryption is supported, libarchive isn't consistent in
// archive_read_has_encrypted_entries returning
// ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED. Instead, we do a string
// comparison on the various possible error messages.
void ThrowExitCode(std::string_view const e) {
if (e.starts_with("Incorrect passphrase")) {
throw ExitCode::PASSPHRASE_INCORRECT;
}
if (e.starts_with("Passphrase required")) {
throw ExitCode::PASSPHRASE_REQUIRED;
}
std::string_view const not_supported_prefixes[] = {
"Crypto codec not supported",
"Decryption is unsupported",
"Encrypted file is unsupported",
"Encryption is not supported",
"RAR encryption support unavailable",
"The archive header is encrypted, but currently not supported",
"The file content is encrypted, but currently not supported",
"Unsupported encryption format",
};
for (std::string_view const prefix : not_supported_prefixes) {
if (e.starts_with(prefix)) {
throw ExitCode::PASSPHRASE_NOT_SUPPORTED;
}
}
}
namespace bi = boost::intrusive;
#ifdef NDEBUG
using LinkMode = bi::link_mode<bi::normal_link>;
#else
using LinkMode = bi::link_mode<bi::safe_link>;
#endif
// A Reader bundles libarchive concepts (an archive and an archive entry) and
// other state to point to a particular offset (in decompressed space) of a
// particular archive entry (identified by its index) in an archive.
//
// A Reader is backed by its own archive_read_open call so each can be
// positioned independently.
struct Reader : bi::list_base_hook<LinkMode> {
// Number of Readers created so far.
static int count;
int id = ++count;
ArchiveDescriptor* const descriptor;
ArchivePtr archive = ArchivePtr(archive_read_new());
Entry* entry = nullptr;
i64 index_within_archive = 0;
i64 offset_within_entry = 0;
bool should_print_progress = false;
i64 raw_pos = 0;
char raw_bytes[16 * 1024];
// Rolling buffer of uncompressed bytes. See (https://crbug.com/1245925#c18).
// Even when libfuse is single-threaded, we have seen kernel readahead
// causing the offset arguments in a sequence of read calls to sometimes
// arrive out-of-order, where conceptually consecutive reads are swapped. With
// a rolling buffer, we can serve the second-to-arrive request by a cheap
// memcpy instead of an expensive "re-do decompression from the start".
static ssize_t const rolling_buffer_size = 256 * 1024;
static ssize_t const rolling_buffer_mask = rolling_buffer_size - 1;
static_assert((rolling_buffer_size & rolling_buffer_mask) == 0);
char rolling_buffer[rolling_buffer_size];
~Reader() { LOG(DEBUG) << "Deleted " << *this; }
Reader(ArchiveDescriptor* const descriptor) : descriptor(descriptor) {
if (!archive) {
LOG(ERROR) << "Out of memory";
throw std::bad_alloc();
}
if (g_password.empty()) {
Check(archive_read_set_passphrase_callback(archive.get(), nullptr,
&ReadPassword));
} else {
Check(archive_read_add_passphrase(archive.get(), g_password.c_str()));