-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathafsctool.c
3461 lines (3331 loc) · 113 KB
/
afsctool.c
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
// kate: auto-insert-doxygen true; backspace-indents true; indent-width 4; keep-extra-spaces true; replace-tabs false; tab-indents true; tab-width 4;
/*
* @file afsctool.c
* Copyright "brkirch" (https://brkirch.wordpress.com/afsctool/)
* Parallel processing modifications and other tweaks (C) 2015-now René J.V. Bertin
* This code is made available under the GPL3 License
* (See License.txt)
*/
#ifndef __APPLE__
#define __USE_BSD
#ifndef _BSD_SOURCE
# define _BSD_SOURCE
#endif
#endif
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <libgen.h>
#include <signal.h>
#include <zlib.h>
#ifdef HAS_LZVN
# include "private/lzfse/src/lzfse_internal.h"
#endif
#ifdef HAS_LZFSE
# include "private/lzfse/src/lzfse.h"
#endif
#include <sys/mman.h>
#ifdef __APPLE__
#include <sys/attr.h>
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
#define BlockMutable __block
#else
// for cross-platform debugging only!
#include <bsd/stdlib.h>
#include <endian.h>
#include <sys/vfs.h>
#include <sys/stat.h>
#include <fcntl.h>
#define O_EXLOCK 0
#define HFSPlusAttrKey 0
#define HFSPlusCatalogFile 0
#define OSSwapHostToBigInt16(x) htobe16(x)
#define OSSwapHostToBigInt32(x) htobe32(x)
#define OSSwapHostToLittleInt32(x) htole32(x)
#define OSSwapHostToLittleInt64(x) htole64(x)
#define OSSwapLittleToHostInt32(x) le32toh(x)
#define MAP_NOCACHE 0
#define BlockMutable /**/
#endif
#include "afsctool.h"
#ifdef SUPPORT_PARALLEL
# include "ParallelProcess.h"
static ParallelFileProcessor *PP = NULL;
static bool exclusive_io = true;
#endif
#include "afsctool_fullversion.h"
#include "utils.h"
#define xfree(x) if((x)){free((x)); (x)=NULL;}
#define xclose(x) if((x)!=-1){close((x)); (x)=-1;}
#define xmunmap(x,s) if((x)){munmap((x),(s)); (x)=NULL;}
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_5
static bool legacy_output = true;
#else
static bool legacy_output = false;
#endif
// some constants borrowed from libarchive
#define MAX_DECMPFS_XATTR_SIZE 3802 /* max size that can be stored in the xattr. */
#ifndef DECMPFS_MAGIC
# define DECMPFS_MAGIC 'cmpf'
#endif
#ifndef DECMPFS_XATTR_NAME
# define DECMPFS_XATTR_NAME "com.apple.decmpfs"
#endif
// use a hard-coded count so all arrays are always sized equally (and the compiler can warn better)
#define sizeunits 6
const char *sizeunit10_short[sizeunits] = {"KB", "MB", "GB", "TB", "PB", "EB"};
const char *sizeunit10_long[sizeunits] = {"kilobytes", "megabytes", "gigabytes", "terabytes", "petabytes", "exabytes"};
const long long int sizeunit10[sizeunits] = {1000, 1000 * 1000, 1000 * 1000 * 1000, (long long int) 1000 * 1000 * 1000 * 1000,
(long long int) 1000 * 1000 * 1000 * 1000 * 1000, (long long int) 1000 * 1000 * 1000 * 1000 * 1000 * 1000};
const char *sizeunit2_short[sizeunits] = {"KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
const char *sizeunit2_long[sizeunits] = {"kibibytes", "mebibytes", "gibibytes", "tebibytes", "pebibytes", "exbibytes"};
const long long int sizeunit2[sizeunits] = {1024, 1024 * 1024, 1024 * 1024 * 1024, (long long int) 1024 * 1024 * 1024 * 1024,
(long long int) 1024 * 1024 * 1024 * 1024 * 1024, (long long int) 1024 * 1024 * 1024 * 1024 * 1024 * 1024};
int printVerbose = 0;
static size_t maxOutBufSize = 0;
void printFileInfo(const char *filepath, struct stat *fileinfo, bool appliedcomp, bool onAPFS);
#if !__has_builtin(__builtin_available)
# warning "Please use clang 5 or newer if you can"
// determine the Darwin major version number
static int darwinMajor = 0;
#endif
char* getSizeStr(long long int size, long long int size_rounded, int likeFinder)
{
static char sizeStr[128];
static int len = sizeof(sizeStr)/sizeof(char);
int unit2, unit10;
for (unit2 = 0; unit2 + 1 < sizeunits && (size_rounded / sizeunit2[unit2 + 1]) > 0; unit2++);
for (unit10 = 0; unit10 + 1 < sizeunits && (size_rounded / sizeunit10[unit10 + 1]) > 0; unit10++);
int remLen = len - snprintf(sizeStr, len, "%lld bytes", size);
char *cursor = &sizeStr[strlen(sizeStr)];
#ifdef PRINT_SI_SIZES
int print_si_sizes = 1;
#else
int print_si_sizes = likeFinder;
#endif
if (print_si_sizes) {
// the Finder will happily print "0 bytes on disk" so here we don't bother
// determining if the human-readable value is > 0.
switch (unit10)
{
case 0:
snprintf(cursor, remLen, " / %0.0f %s (%s, base-10)",
(double) size_rounded / sizeunit10[unit10], sizeunit10_short[unit10], sizeunit10_long[unit10]);
break;
case 1:
snprintf(cursor, remLen, " / %.12g %s (%s, base-10)",
(double) (((long long int) ((double) size_rounded / sizeunit10[unit10] * 100) + 5) / 10) / 10,
sizeunit10_short[unit10], sizeunit10_long[unit10]);
break;
default:
snprintf(cursor, remLen, " / %0.12g %s (%s, base-10)",
(double) (((long long int) ((double) size_rounded / sizeunit10[unit10] * 1000) + 5) / 10) / 100,
sizeunit10_short[unit10], sizeunit10_long[unit10]);
break;
}
}
if (!likeFinder) {
double humanReadable;
switch (unit2)
{
case 0:
// this should actually be the only case were we'd need
// to check if the human readable value is sensical...
humanReadable = (double) size_rounded / sizeunit2[unit2];
if( humanReadable >= 1 ) {
snprintf(cursor, remLen, " / %0.0f %s", humanReadable, sizeunit2_short[unit2]);
}
break;
case 1:
humanReadable = (double) (((long long int) ((double) size_rounded / sizeunit2[unit2] * 100) + 5) / 10) / 10;
if( humanReadable > 0 ) {
snprintf(cursor, remLen, " / %.12g %s", humanReadable, sizeunit2_short[unit2]);
}
break;
default:
humanReadable = (double) (((long long int) ((double) size_rounded / sizeunit2[unit2] * 1000) + 5) / 10) / 100;
if( humanReadable > 0 ) {
snprintf(cursor, remLen, " / %0.12g %s", humanReadable, sizeunit2_short[unit2]);
}
break;
}
}
return sizeStr;
}
long long int roundToBlkSize(long long int size, struct stat *fileinfo)
{
if (size <= 0) {
return size;
} else if (size < fileinfo->st_blksize) {
// fprintf( stderr, "size=%lld -> blksize %d\n", size, fileinfo->st_blksize );
return fileinfo->st_blksize;
} else {
// round up to the next multiple of st_blksize:
long long int remainder = size % fileinfo->st_blksize;
// fprintf( stderr, "size=%lld -> multiple of blksize %d: %lld (%g ; %d)\n", size,
// fileinfo->st_blksize, (remainder != 0) ? size + (fileinfo->st_blksize - remainder) : size,
// (double) ((remainder != 0) ? size + (fileinfo->st_blksize - remainder) : size) / fileinfo->st_blocks,
// fileinfo->st_blksize);
return (remainder != 0) ? size + (fileinfo->st_blksize - remainder) : size;
}
}
static bool quitRequested = FALSE;
static void signal_handler(int sig)
{
fprintf( stderr, "Received signal %d: " AFSCTOOL_PROG_NAME " will quit\n", sig );
#ifdef SUPPORT_PARALLEL
stopParallelProcessor(PP);
#endif
}
bool fileIsCompressable(const char *inFile, struct stat *inFileInfo, int comptype, bool *isAPFS)
{
struct statfs fsInfo;
errno = 0;
int ret = statfs(inFile, &fsInfo);
#ifdef __APPLE__
// https://github.com/RJVB/afsctool/pull/1#issuecomment-352727426
uint32_t MNTTYPE_ZFS_SUBTYPE = 'Z'<<24|'F'<<16|'S'<<8;
// // fprintf( stderr, "statfs=%d f_type=%u f_fssubtype=%u \"%s\" ISREG=%d UF_COMPRESSED=%d compressable=%d\n",
// // ret, fsInfo.f_type, fsInfo.f_fssubtype, fsInfo.f_fstypename,
// // S_ISREG(inFileInfo->st_mode), (inFileInfo->st_flags & UF_COMPRESSED),
// // ret >= 0 && fsInfo.f_type == 17
// // && S_ISREG(inFileInfo->st_mode)
// // && (inFileInfo->st_flags & UF_COMPRESSED) == 0 );
bool _isAPFS = !strncasecmp(fsInfo.f_fstypename, "apfs", 4);
bool _isZFS = (fsInfo.f_fssubtype == MNTTYPE_ZFS_SUBTYPE);
if (isAPFS) {
*isAPFS = ret >= 0 ? _isAPFS && !_isZFS : false;
}
if (ret < 0) {
fprintf( stderr, "\"%s\": %s\n", inFile, strerror(errno) );
return false;
}
#ifndef HFSCOMPRESS_TO_ZFS
if (_isZFS) {
// ZFS doesn't do HFS/decmpfs compression. It may pretend to, but in
// that case it will *de*compress the data before committing it. We
// won't play that game, wasting cycles and rewriting data for nothing.
return false;
}
#endif
#ifdef HAS_LZVN
// the LZVN compressor we use fails on buffers that are too small, so we need to verify
// if the file gets to be split into chunks that are all large enough.
if (comptype == LZVN){
int lastChunkSize = inFileInfo->st_size % 0x10000;
if (lastChunkSize > 0 && lastChunkSize < LZVN_ENCODE_MIN_SRC_SIZE) {
if (printVerbose >= 2) {
fprintf( stderr, "\"%s\": file too small or will contain a too small compression chunk (try ZLIB compression)\n",
inFile);
}
return false;
}
}
#endif
#ifdef VOL_CAP_FMT_DECMPFS_COMPRESSION
// https://opensource.apple.com/source/copyfile/copyfile-146/copyfile.c.auto.html
int rv;
struct attrlist attrs;
char volroot[MAXPATHLEN + 1];
struct {
uint32_t length;
vol_capabilities_attr_t volAttrs;
} volattrs;
strlcpy(volroot, fsInfo.f_mntonname, sizeof(volroot));
memset(&attrs, 0, sizeof(attrs));
attrs.bitmapcount = ATTR_BIT_MAP_COUNT;
attrs.volattr = ATTR_VOL_CAPABILITIES;
errno = 0;
rv = getattrlist(volroot, &attrs, &volattrs, sizeof(volattrs), 0);
// fprintf( stderr, "volattrs for \"%s\": rv=%d VOL_CAP_FMT_DECMPFS_COMPRESSION=%d:%d\n", volroot,
// rv,
// (bool)(volattrs.volAttrs.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_DECMPFS_COMPRESSION),
// (bool)(volattrs.volAttrs.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_DECMPFS_COMPRESSION)
// );
if (errno) {
fprintf( stderr, "Error getting volattrs for \"%s\": %s\n", volroot, strerror(errno) );
}
return (rv != -1 &&
(volattrs.volAttrs.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_DECMPFS_COMPRESSION) &&
(volattrs.volAttrs.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_DECMPFS_COMPRESSION)
&& S_ISREG(inFileInfo->st_mode)
&& (inFileInfo->st_flags & UF_COMPRESSED) == 0 );
#else
return (ret >= 0
&& (!strncasecmp(fsInfo.f_fstypename, "hfs", 3) || _isAPFS)
&& S_ISREG(inFileInfo->st_mode)
&& (inFileInfo->st_flags & UF_COMPRESSED) == 0);
#endif
#else // !APPLE
return (ret >= 0 && S_ISREG(inFileInfo->st_mode));
#endif
}
/** Mac OS X basename() can modify the input string when not in 'legacy' mode on 10.6
* and indeed it does. So we use our own which doesn't, and also doesn't require internal
* storage.
*/
static const char *lbasename(const char *url)
{ const char *c = NULL;
if (url)
{
if ((c = strrchr( url, '/' )))
{
c++;
}
else
{
c = url;
}
}
return c;
}
const char *compressionTypeName(int type)
{
char *name = "";
switch (type) {
#define STR(v) #v
#define STRVAL(v) STR(v)
case CMP_ZLIB_XATTR:
name = "ZLIB in decmpfs xattr (" STRVAL(CMP_ZLIB_XATTR) ")";
break;
case CMP_ZLIB_RESOURCE_FORK:
name = "ZLIB in resource fork (" STRVAL(CMP_ZLIB_RESOURCE_FORK) ")";
break;
case CMP_LZVN_XATTR:
name = "LZVN in decmpfs xattr (" STRVAL(CMP_LZVN_XATTR) ")";
break;
case CMP_LZVN_RESOURCE_FORK:
name = "LZVN in resource fork (" STRVAL(CMP_LZVN_RESOURCE_FORK) ")";
break;
case CMP_LZFSE_XATTR:
name = "LZFSE in decmpfs xattr (" STRVAL(CMP_LZFSE_XATTR) ")";
break;
case CMP_LZFSE_RESOURCE_FORK:
name = "LZFSE in resource fork (" STRVAL(CMP_LZFSE_RESOURCE_FORK) ")";
break;
}
return name;
}
#ifdef SUPPORT_PARALLEL
void compressFile(const char *inFile, struct stat *inFileInfo, struct folder_info *folderinfo, FileProcessor *worker )
#else
void compressFile(const char *inFile, struct stat *inFileInfo, struct folder_info *folderinfo, void *ignored)
#endif
{
long long int maxSize = folderinfo->maxSize;
int compressionlevel = folderinfo->compressionlevel;
int comptype = folderinfo->compressiontype;
bool allowLargeBlocks = folderinfo->allowLargeBlocks;
double minSavings = folderinfo->minSavings;
bool checkFiles = folderinfo->check_files;
bool backupFile = folderinfo->backup_file;
BlockMutable int fdIn;
BlockMutable char *backupName = NULL;
// 64Kb block size (HFS compression is "64K chunked")
const int compblksize = 0x10000;
unsigned int numBlocks, outdecmpfsSize = 0;
void *inBuf = NULL, *outBuf = NULL, *outBufBlock = NULL, *outdecmpfsBuf = NULL, *currBlock = NULL, *blockStart = NULL;
long long int inBufPos;
off_t filesize = inFileInfo->st_size;
unsigned long int cmpedsize;
char *xattrnames, *curr_attr;
ssize_t xattrnamesize, outBufSize = 0;
UInt32 cmpf = DECMPFS_MAGIC, orig_mode;
struct timeval times[2];
#if defined HAS_LZVN || defined HAS_LZFSE
void *lz_WorkSpace = NULL;
#endif
bool supportsLargeBlocks;
bool useMmap = false;
if (quitRequested)
{
return;
}
#ifdef __APPLE__
void (^restoreFile)() = ^{
if (write(fdIn, inBuf, filesize) != filesize) {
fprintf(stderr, "%s: Error restoring file (%lld bytes; %s)\n", inFile, filesize, strerror(errno));
if (backupName) {
fprintf(stderr, "\ta backup is available as %s\n", backupName);
xfree(backupName);
}
xclose(fdIn);
}
};
times[0].tv_sec = inFileInfo->st_atimespec.tv_sec;
times[0].tv_usec = inFileInfo->st_atimespec.tv_nsec / 1000;
times[1].tv_sec = inFileInfo->st_mtimespec.tv_sec;
times[1].tv_usec = inFileInfo->st_mtimespec.tv_nsec / 1000;
#elif defined(linux)
times[0].tv_sec = inFileInfo->st_atim.tv_sec;
times[0].tv_usec = inFileInfo->st_atim.tv_nsec / 1000;
times[1].tv_sec = inFileInfo->st_mtim.tv_sec;
times[1].tv_usec = inFileInfo->st_mtim.tv_nsec / 1000;
#endif
if (!fileIsCompressable(inFile, inFileInfo, comptype, &folderinfo->onAPFS)){
return;
}
if (filesize > maxSize && maxSize != 0){
if (folderinfo->print_info > 2)
{
fprintf( stderr, "Skipping file %s size %lld > max size %lld\n", inFile, (long long) filesize, maxSize );
}
return;
}
if (filesize == 0){
if (folderinfo->print_info > 2)
{
fprintf( stderr, "Skipping empty file %s\n", inFile );
}
return;
}
orig_mode = inFileInfo->st_mode;
if ((orig_mode & S_IWUSR) == 0) {
chmod(inFile, orig_mode | S_IWUSR);
lstat(inFile, inFileInfo);
}
if ((orig_mode & S_IRUSR) == 0) {
chmod(inFile, orig_mode | S_IRUSR);
lstat(inFile, inFileInfo);
}
#ifdef __APPLE__
if (chflags(inFile, UF_COMPRESSED | inFileInfo->st_flags) < 0 || chflags(inFile, inFileInfo->st_flags) < 0)
{
fprintf(stderr, "%s: chflags: %s\n", inFile, strerror(errno));
return;
}
xattrnamesize = listxattr(inFile, NULL, 0, XATTR_SHOWCOMPRESSION | XATTR_NOFOLLOW);
if (xattrnamesize > 0)
{
xattrnames = (char *) malloc(xattrnamesize);
if (xattrnames == NULL)
{
fprintf(stderr, "%s: malloc error, unable to get file information (%lu bytes; %s)\n",
inFile, (unsigned long) xattrnamesize, strerror(errno));
return;
}
if ((xattrnamesize = listxattr(inFile, xattrnames, xattrnamesize, XATTR_SHOWCOMPRESSION | XATTR_NOFOLLOW)) <= 0)
{
fprintf(stderr, "%s: listxattr: %s\n", inFile, strerror(errno));
free(xattrnames);
return;
}
for (curr_attr = xattrnames; curr_attr < xattrnames + xattrnamesize; curr_attr += strlen(curr_attr) + 1)
{
if ((strcmp(curr_attr, XATTR_RESOURCEFORK_NAME) == 0 && strlen(curr_attr) == 22) ||
(strcmp(curr_attr, DECMPFS_XATTR_NAME) == 0 && strlen(curr_attr) == 17))
return;
}
free(xattrnames);
}
#endif // APPLE
numBlocks = (filesize + compblksize - 1) / compblksize;
// TODO: make compression-type specific (as far as that's possible).
if ((filesize + 0x13A + (numBlocks * 9)) > CMP_MAX_SUPPORTED_SIZE) {
fprintf( stderr, "Skipping file %s with unsupportable size %lld\n", inFile, (long long) filesize );
return;
} else if (filesize >= 64 * 1024 * 1024) {
// use a rather arbitrary threshold above which using mmap may be of interest
useMmap = true;
}
#ifdef SUPPORT_PARALLEL
bool locked = false;
if( exclusive_io && worker ){
// Lock the IO lock. We'll unlock it when we're done, but we don't bother
// when we have to return before that as our caller (a worker thread)
// will clean up for us.
locked = lockParallelProcessorIO(worker);
}
#endif
// use open() with an exclusive lock so noone can modify the file while we're at it
fdIn = open(inFile, O_RDWR|O_EXLOCK|O_NONBLOCK);
if (fdIn == -1)
{
fprintf(stderr, "%s: %s\n", inFile, strerror(errno));
goto bail;
}
#ifndef NO_USE_MMAP
if (useMmap) {
// get a private mmap. We rewrite to the file's attributes and/or resource fork,
// so there is no point in using a shared mapping where changes to the memory
// are mapped back to disk. The use of NOCACHE is experimental; if I understand
// the documentation correctly this just means that released memory can be
// reused more easily.
inBuf = mmap(NULL, filesize, PROT_READ, MAP_PRIVATE|MAP_NOCACHE, fdIn, 0);
if (inBuf == MAP_FAILED) {
fprintf(stderr, "%s: Error m'mapping file (size %lld; %s)\n", inFile, (long long) filesize, strerror(errno));
useMmap = false;
} else {
madvise(inBuf, filesize, MADV_RANDOM);
}
}
if (!useMmap)
#endif
{
inBuf = malloc(filesize);
if (inBuf == NULL)
{
fprintf(stderr, "%s: malloc error, unable to allocate input buffer of %lld bytes (%s)\n", inFile, (long long) filesize, strerror(errno));
xclose(fdIn);
utimes(inFile, times);
return;
}
madvise(inBuf, filesize, MADV_RANDOM);
if (read(fdIn, inBuf, filesize) != filesize)
{
fprintf(stderr, "%s: Error reading file (%s)\n", inFile, strerror(errno));
xclose(fdIn);
utimes(inFile, times);
free(inBuf);
return;
}
}
// keep our filedescriptor open to maintain the lock!
#ifdef __APPLE__
if (backupFile)
{ int fd, bkNameLen;
FILE *fp;
char *infile, *inname = NULL;
if ((infile = strdup(inFile)))
{
inname = (char*) lbasename(infile);
// avoid filename overflow; assume 32 fixed template char for mkstemps
// just to be on the safe side (even in parallel mode).
if (strlen(inname) > 1024 - 32)
{
// truncate
inname[1024-32] = '\0';
}
#ifdef SUPPORT_PARALLEL
// add the processor ID for the unlikely case that 2 threads try to backup a file with the same name
// at the same time, and mkstemps() somehow generates the same temp. name. I've seen it generate EEXIST
// errors which suggest that might indeed happen.
bkNameLen = asprintf(&backupName, "/tmp/afsctbk.%d.XXXXXX.%s", currentParallelProcessorID(worker), inname);
#else
bkNameLen = asprintf(&backupName, "/tmp/afsctbk.XXXXXX.%s", inname);
#endif
}
if (!infile || bkNameLen < 0)
{
fprintf(stderr, "%s: malloc error, unable to generate temporary backup filename (%s)\n", inFile, strerror(errno));
xfree(infile);
goto bail;
}
if ((fd = mkstemps(backupName, strlen(inname)+1)) < 0 || !(fp = fdopen(fd, "w")))
{
fprintf(stderr, "%s: error creating temporary backup file %s (%s)\n", inFile, backupName, strerror(errno));
xfree(infile);
goto bail;
}
xfree(infile);
if (fwrite(inBuf, filesize, 1, fp) != 1)
{
fprintf(stderr, "%s: Error writing to backup file %s (%lld bytes; %s)\n", inFile, backupName, filesize, strerror(errno));
fclose(fp);
goto bail;
}
fclose(fp);
utimes(backupName, times);
chmod(backupName, orig_mode);
}
#endif
#ifdef SUPPORT_PARALLEL
if( exclusive_io && worker ){
locked = unLockParallelProcessorIO(worker);
}
#endif
outdecmpfsBuf = malloc(MAX_DECMPFS_XATTR_SIZE);
if (outdecmpfsBuf == NULL)
{
fprintf(stderr, "%s: malloc error, unable to allocate xattr buffer (%d bytes; %s)\n",
inFile, MAX_DECMPFS_XATTR_SIZE, strerror(errno));
utimes(inFile, times);
goto bail;
}
struct compressionType {
UInt32 xattr, resourceFork;
} compressionType;
uLong zlib_EstimatedCompressedChunkSize;
#if defined HAS_LZVN || defined HAS_LZFSE
size_t lz_EstimatedCompressedSize;
lz_chunk_table *chunkTable = (lz_chunk_table*) outBuf;
ssize_t chunkTableByteSize;
#endif
switch (comptype) {
case ZLIB: {
cmpedsize = zlib_EstimatedCompressedChunkSize = compressBound(compblksize);
struct compressionType t = {CMP_ZLIB_XATTR, CMP_ZLIB_RESOURCE_FORK};
compressionType = t;
#ifdef ZLIB_SINGLESHOT_OUTBUF
outBufSize = filesize + 0x13A + (numBlocks * 9);
#else
outBufSize = 0x104 + sizeof(UInt32) + numBlocks * 8;
#endif
#define SET_BLOCKSTART() blockStart = outBuf + 0x104
outBuf = malloc(outBufSize);
break;
}
#ifdef HAS_LZVN
case LZVN: {
cmpedsize = lz_EstimatedCompressedSize = MAX(lzvn_encode_scratch_size(), compblksize);
lz_WorkSpace = malloc(cmpedsize);
// for this compressor we will let the outBuf grow incrementally. Slower,
// but use only as much memory as required.
outBuf = calloc(numBlocks, sizeof(chunkTable));
chunkTable = outBuf;
if (!lz_WorkSpace || !chunkTable) {
fprintf(stderr,
"%s: malloc error, unable to allocate %lu bytes for lzvn workspace or %u element chunk table(%s)\n",
inFile, cmpedsize, numBlocks, strerror(errno));
utimes(inFile, times);
goto bail;
}
struct compressionType t = {CMP_LZVN_XATTR, CMP_LZVN_RESOURCE_FORK};
compressionType = t;
outBufSize = chunkTableByteSize = numBlocks * sizeof(chunkTable);
chunkTable[0] = chunkTableByteSize;
break;
}
#endif
#ifdef HAS_LZFSE
case LZFSE:
cmpedsize = lz_EstimatedCompressedSize = MAX(lzfse_encode_scratch_size(), compblksize);
lz_WorkSpace = lz_EstimatedCompressedSize ? malloc(lz_EstimatedCompressedSize) : 0;
// for this compressor we will let the outBuf grow incrementally. Slower,
// but use only as much memory as required.
outBuf = calloc(numBlocks, sizeof(chunkTable));
chunkTable = outBuf;
if ((!lz_WorkSpace && lz_EstimatedCompressedSize) || !chunkTable) {
fprintf(stderr,
"%s: malloc error, unable to allocate %lu bytes for lzfse workspace or %u element chunk table(%s)\n",
inFile, cmpedsize, numBlocks, strerror(errno));
utimes(inFile, times);
goto bail;
}
struct compressionType t = {CMP_LZFSE_XATTR, CMP_LZFSE_RESOURCE_FORK};
compressionType = t;
outBufSize = chunkTableByteSize = numBlocks * sizeof(chunkTable);
chunkTable[0] = chunkTableByteSize;
break;
#endif
default:
fprintf(stderr, "%s: unsupported compression type %d (%s)\n",
inFile, comptype, compressionTypeName(comptype));
utimes(inFile, times);
goto bail;
break;
}
if (outBuf == NULL && outBufSize != 0)
{
fprintf(stderr, "%s: malloc error, unable to allocate output buffer of %lu bytes (%s)\n",
inFile, outBufSize, strerror(errno));
utimes(inFile, times);
goto bail;
}
outBufBlock = malloc(cmpedsize);
if (outBufBlock == NULL)
{
fprintf(stderr, "%s: malloc error, unable to allocate compression buffer of %lu bytes (%s)\n",
inFile, cmpedsize, strerror(errno));
utimes(inFile, times);
goto bail;
}
// The header of the compression resource fork (16 bytes):
// compression magic number
decmpfs_disk_header *decmpfsAttr = (decmpfs_disk_header*) outdecmpfsBuf;
decmpfsAttr->compression_magic = OSSwapHostToLittleInt32(cmpf);
// the compression type: 4 == compressed data in the resource fork.
// FWIW, libarchive has the following comment in archive_write_disk_posix.c :
//* If the compressed size is smaller than MAX_DECMPFS_XATTR_SIZE [3802]
//* and the block count in the file is only one, store compressed
//* data to decmpfs xattr instead of the resource fork.
// We do the same below.
decmpfsAttr->compression_type = OSSwapHostToLittleInt32(compressionType.resourceFork);
// the uncompressed filesize
decmpfsAttr->uncompressed_size = OSSwapHostToLittleInt64(filesize);
// outdecmpfsSize = 0x10;
outdecmpfsSize = sizeof(decmpfs_disk_header);
unsigned long currBlockLen, currBlockOffset;
switch (comptype) {
case ZLIB:
*(UInt32 *) outBuf = OSSwapHostToBigInt32(0x100);
*(UInt32 *) (outBuf + 12) = OSSwapHostToBigInt32(0x32);
memset(outBuf + 16, 0, 0xF0);
SET_BLOCKSTART();
// block table: numBlocks + offset,blocksize pairs for each of the blocks
*(UInt32 *) blockStart = OSSwapHostToLittleInt32(numBlocks);
// actual compressed data starts after the block table
currBlock = blockStart + sizeof(UInt32) + (numBlocks * 8);
currBlockLen = outBufSize - (currBlock - outBuf);
supportsLargeBlocks = true;
break;
#ifdef HAS_LZVN
case LZVN:
supportsLargeBlocks = false;
break;
#endif
#ifdef HAS_LZFSE
case LZFSE:
supportsLargeBlocks = false;
break;
#endif
default:
// noop
break;
}
int blockNr;
// chunking loop that compresses the 64K chunks and handles the result(s).
// Note that LZVN appears not to be chunked like that (maybe inside lzvn_encode()?)
// TODO: refactor and merge with the switch() above if LZFSE compression doesn't need chunking either.
for (inBufPos = 0, blockNr = 0, currBlockOffset = 0
; inBufPos < filesize
; inBufPos += compblksize, currBlock += cmpedsize, currBlockOffset += cmpedsize, ++blockNr)
{
void *cursor = inBuf + inBufPos;
uLong bytesAfterCursor = ((filesize - inBufPos) > compblksize) ? compblksize : filesize - inBufPos;
switch (comptype) {
case ZLIB:
// reset cmpedsize; it may be changed by compress2().
cmpedsize = zlib_EstimatedCompressedChunkSize;
if (compress2(outBufBlock, &cmpedsize, cursor, bytesAfterCursor, compressionlevel) != Z_OK)
{
utimes(inFile, times);
goto bail;
}
#ifndef ZLIB_SINGLESHOT_OUTBUF
if (currBlockOffset == 0) {
currBlockOffset = outBufSize;
}
outBufSize += cmpedsize;
if (!(outBuf = reallocf(outBuf, outBufSize + 1))) {
fprintf(stderr, "%s: malloc error, unable to increase output buffer to %lu bytes (%s)\n",
inFile, outBufSize, strerror(errno));
utimes(inFile, times);
goto bail;
}
// update this one!
SET_BLOCKSTART();
currBlock = outBuf + currBlockOffset;
currBlockLen = outBufSize;
#endif
break;
#ifdef HAS_LZVN
case LZVN:{
// store the current last 4 bytes of compressed file content (bogus the 1st time we come here)
UInt32 prevLast = ((UInt32*)outBufBlock)[cmpedsize/sizeof(UInt32)-1];
cmpedsize =
lzvn_encode_buffer(outBufBlock, lz_EstimatedCompressedSize, cursor, bytesAfterCursor, lz_WorkSpace);
if (cmpedsize <= 0)
{
fprintf( stderr, "%s: lzvn compression failed on chunk #%d (of %u; %lu bytes)\n",
inFile, blockNr, numBlocks, bytesAfterCursor);
// if (bytesAfterCursor < LZVN_MINIMUM_COMPRESSABLE_SIZE) {
// cmpedsize = bytesAfterCursor;
// memcpy(outBufBlock, cursor, bytesAfterCursor);
// } else {
utimes(inFile, times);
goto bail;
// }
}
// next offset will start at this offset
if (blockNr < numBlocks) {
chunkTable[blockNr+1] = chunkTable[blockNr] + cmpedsize;
}
if (currBlockOffset == 0) {
currBlockOffset = outBufSize;
}
outBufSize += cmpedsize;
if (!(outBuf = reallocf(outBuf, outBufSize))) {
fprintf(stderr, "%s: malloc error, unable to increase output buffer to %lu bytes (%s)\n",
inFile, outBufSize, strerror(errno));
utimes(inFile, times);
goto bail;
}
// update this one!
chunkTable = outBuf;
currBlock = outBuf + currBlockOffset;
currBlockLen = outBufSize;
// if not the 1st time we're here, check if the 4 bytes of compressed file contents
// just before the current position in the output buffer correspond to prevLast.
// If the test fails we may have a chunking overlap issue.
// It never happened to my knowledge, but this sanity check is cheap enough to keep.
if (blockNr > 1 && ((UInt32*)currBlock)[-1] != prevLast) {
fprintf(stderr, "%s: warning, possible chunking overlap: prevLast=%u currBlock[-1]=%u currBlock[0]=%u\n",
inFile, prevLast, ((UInt32*)currBlock)[-1], ((UInt32*)currBlock)[0]);
}
break;
}
#endif
#ifdef HAS_LZFSE
case LZFSE:{
cmpedsize = lz_EstimatedCompressedSize;
while (1) {
cmpedsize = lzfse_encode_buffer(outBufBlock, cmpedsize, cursor, bytesAfterCursor, lz_WorkSpace);
// If output buffer was too small, grow and retry.
if (cmpedsize == 0) {
cmpedsize <<= 1;
if (!(outBufBlock = reallocf(outBufBlock, cmpedsize))) {
fprintf(stderr, "%s: malloc error, unable to increase output buffer to %lu bytes (%s)\n",
inFile, cmpedsize, strerror(errno));
utimes(inFile, times);
goto bail;
}
continue;
}
break;
}
// next offset will start at this offset
if (blockNr < numBlocks) {
chunkTable[blockNr + 1] = chunkTable[blockNr] + cmpedsize;
}
if (currBlockOffset == 0) {
currBlockOffset = outBufSize;
}
outBufSize += cmpedsize;
if (!(outBuf = reallocf(outBuf, outBufSize))) {
fprintf(stderr, "%s: malloc error, unable to increase output buffer to %lu bytes (%s)\n",
inFile, outBufSize, strerror(errno));
utimes(inFile, times);
goto bail;
}
// update this one!
chunkTable = outBuf;
currBlock = outBuf + currBlockOffset;
currBlockLen = outBufSize;
break;
}
#endif
default:
// noop
break;
}
if (supportsLargeBlocks && cmpedsize > (((filesize - inBufPos) > compblksize) ? compblksize : filesize - inBufPos))
{
if (!allowLargeBlocks && (((filesize - inBufPos) > compblksize) ? compblksize : filesize - inBufPos) == compblksize)
{
if (printVerbose >= 2) {
fprintf(stderr, "%s: file has a compressed chunk that's larger than the original chunk; -L to compress\n", inFile);
}
utimes(inFile, times);
goto bail;
}
*(unsigned char *) outBufBlock = 0xFF;
memcpy(outBufBlock + 1, inBuf + inBufPos, ((filesize - inBufPos) > compblksize) ? compblksize : filesize - inBufPos);
cmpedsize = ((filesize - inBufPos) > compblksize) ? compblksize : filesize - inBufPos;
cmpedsize++;
}
if (((cmpedsize + outdecmpfsSize) <= MAX_DECMPFS_XATTR_SIZE) && (numBlocks <= 1))
{
// store in directly into the attribute instead of using the resource fork.
// *(UInt32 *) (outdecmpfsBuf + 4) = EndianU32_NtoL(compressionType.xattr);
decmpfsAttr->compression_type = OSSwapHostToLittleInt32(compressionType.xattr);
memcpy(outdecmpfsBuf + outdecmpfsSize, outBufBlock, cmpedsize);
outdecmpfsSize += cmpedsize;
folderinfo->data_compressed_size = outdecmpfsSize;
break;
}
if (currBlockOffset + cmpedsize <= currBlockLen) {
memcpy(currBlock, outBufBlock, cmpedsize);
} else {
fprintf( stderr, "%s: result buffer overrun at chunk #%d (%lu >= %lu)\n", inFile, blockNr,
currBlockOffset + cmpedsize, currBlockLen);
utimes(inFile, times);
goto bail;
}
switch (comptype) {
case ZLIB:
*(UInt32 *) (blockStart + ((inBufPos / compblksize) * 8) + 0x4) = OSSwapHostToLittleInt32(currBlock - blockStart);
*(UInt32 *) (blockStart + ((inBufPos / compblksize) * 8) + 0x8) = OSSwapHostToLittleInt32(cmpedsize);
break;
default:
// noop
break;
}
}
// deallocate memory that isn't needed anymore.
#if defined HAS_LZVN || defined HAS_LZFSE
xfree(lz_WorkSpace);
#endif
free(outBufBlock); outBufBlock = NULL;
#ifdef SUPPORT_PARALLEL
// 20160928: the actual rewrite of the file is never done in parallel
if( worker ){
locked = lockParallelProcessorIO(worker);
}
#else
signal(SIGINT, SIG_IGN);
signal(SIGHUP, SIG_IGN);
#endif
// fdIn is still open
bool isTruncated = false;
//if (EndianU32_LtoN(*(UInt32 *) (outdecmpfsBuf + 4)) == CMP_ZLIB_RESOURCE_FORK)
if (OSSwapLittleToHostInt32(decmpfsAttr->compression_type) == compressionType.resourceFork)
{
long long int newSize = currBlock - outBuf + outdecmpfsSize + 50;
if ((minSavings != 0.0 && ((double) newSize / filesize) >= (1.0 - minSavings / 100))
|| newSize >= filesize)
{
// reject the compression result: doesn't meet user criteria or the compressed
// version is larger than the uncompressed file.
// TODO: shouldn't this be checked for all HFS-compressed types,
// not just for the resource-fork based variant?
utimes(inFile, times);
if (printVerbose > 2) {
fprintf(stderr,
"%s: compressed size (%lld) doesn't give required savings (%g) or larger than original (%lld)\n",
inFile, newSize, minSavings, (long long) filesize);
}
goto bail;
}
// create and write the resource fork:
switch (comptype) {
case ZLIB:
#ifndef ZLIB_SINGLESHOT_OUTBUF
currBlockOffset = currBlock - outBuf;
outBufSize += currBlockOffset + sizeof(decmpfs_resource_zlib_trailer);
if (!(outBuf = reallocf(outBuf, outBufSize + 1))) {
fprintf(stderr, "%s: malloc error, unable to increase output buffer to %lu bytes (%s)\n",
inFile, outBufSize, strerror(errno));
utimes(inFile, times);
goto bail;
}
// update this one!
SET_BLOCKSTART();
currBlock = outBuf + currBlockOffset;
#endif
*(UInt32 *) (outBuf + 4) = OSSwapHostToBigInt32(currBlock - outBuf);
*(UInt32 *) (outBuf + 8) = OSSwapHostToBigInt32(currBlock - outBuf - 0x100);
*(UInt32 *) (blockStart - 4) = OSSwapHostToBigInt32(currBlock - outBuf - 0x104);
decmpfs_resource_zlib_trailer *resourceTrailer = (decmpfs_resource_zlib_trailer*) currBlock;
memset(&resourceTrailer->empty[0], 0, 24);
resourceTrailer->magic1 = OSSwapHostToBigInt16(0x1C);
resourceTrailer->magic2 = OSSwapHostToBigInt16(0x32);
resourceTrailer->spacer1 = 0;
resourceTrailer->compression_magic = OSSwapHostToBigInt32(cmpf);
resourceTrailer->magic3 = OSSwapHostToBigInt32(0xA);
resourceTrailer->magic4 = OSSwapHostToLittleInt64(0xFFFF0100);
resourceTrailer->spacer2 = 0;
#ifdef __APPLE__
ftruncate(fdIn, 0);
lseek(fdIn, SEEK_SET, 0);
if (setxattr(inFile, XATTR_RESOURCEFORK_NAME, outBuf, currBlock - outBuf + 50, 0,
XATTR_NOFOLLOW | XATTR_CREATE) < 0)
{
fprintf(stderr, "%s: setxattr(%d): %s (%d)\n", inFile, fdIn, strerror(errno), __LINE__);
restoreFile();
goto bail;
}
isTruncated = true;
#else
if (printVerbose > 2) {
fprintf(stderr, "# setxattr(XATTR_RESOURCEFORK_NAME) outBuf=%p len=%lu\n",
outBuf, currBlock - outBuf + 50);
}
#endif
folderinfo->data_compressed_size = currBlock - outBuf + 50;
break;
#ifdef HAS_LZVN
case LZVN: {
#ifdef __APPLE__
ftruncate(fdIn, 0);
lseek(fdIn, SEEK_SET, 0);
if (setxattr(inFile, XATTR_RESOURCEFORK_NAME, outBuf, outBufSize, 0,
XATTR_NOFOLLOW | XATTR_CREATE) < 0)
{
fprintf(stderr, "%s: setxattr(%d): %s (%d)\n", inFile, fdIn, strerror(errno), __LINE__);
restoreFile();
goto bail;
}
isTruncated = true;
#else
if (printVerbose > 2) {
fprintf(stderr, "# setxattr(XATTR_RESOURCEFORK_NAME) outBuf=%p len=%lu\n",
outBuf, outBufSize);
}
#endif
folderinfo->data_compressed_size = outBufSize;
break;
}