forked from freebsd/freebsd-src
/
bzip2.c
1718 lines (1488 loc) · 48.8 KB
/
bzip2.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
/*-----------------------------------------------------------*/
/*--- A block-sorting, lossless compressor bzip2.c ---*/
/*-----------------------------------------------------------*/
/* ------------------------------------------------------------------
This file is part of bzip2/libbzip2, a program and library for
lossless, block-sorting data compression.
bzip2/libbzip2 version 1.0.6 of 6 September 2010
Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>
Please read the WARNING, DISCLAIMER and PATENTS sections in the
README file.
This program is released under the terms of the license contained
in the file LICENSE.
------------------------------------------------------------------ */
/* Place a 1 beside your platform, and 0 elsewhere.
Generic 32-bit Unix.
Also works on 64-bit Unix boxes.
This is the default.
*/
#define BZ_UNIX 1
/*--
Win32, as seen by Jacob Navia's excellent
port of (Chris Fraser & David Hanson)'s excellent
lcc compiler. Or with MS Visual C.
This is selected automatically if compiled by a compiler which
defines _WIN32, not including the Cygwin GCC.
--*/
#define BZ_LCCWIN32 0
#if defined(_WIN32) && !defined(__CYGWIN__)
#undef BZ_LCCWIN32
#define BZ_LCCWIN32 1
#undef BZ_UNIX
#define BZ_UNIX 0
#endif
/*---------------------------------------------*/
/*--
Some stuff for all platforms.
--*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <math.h>
#include <errno.h>
#include <ctype.h>
#include "bzlib.h"
#include "bzip2_wrapped.h"
#include "capsicum.h"
#include <assert.h>
#define ERROR_IF_EOF(i) { if ((i) == EOF) wrapped_ioError(); }
#define ERROR_IF_NOT_ZERO(i) { if ((i) != 0) wrapped_ioError(); }
#define ERROR_IF_MINUS_ONE(i) { if ((i) == (-1)) wrapped_ioError(); }
/*---------------------------------------------*/
/*--
Platform-specific stuff.
--*/
#if BZ_UNIX
# include <fcntl.h>
# include <sys/types.h>
# include <utime.h>
# include <unistd.h>
# include <sys/stat.h>
# include <sys/times.h>
# define PATH_SEP '/'
# define MY_LSTAT lstat
# define MY_STAT stat
# define MY_S_ISREG S_ISREG
# define MY_S_ISDIR S_ISDIR
# define APPEND_FILESPEC(root, name) \
root=snocString((root), (name))
# define APPEND_FLAG(root, name) \
root=snocString((root), (name))
# ifdef __DJGPP__
# include <io.h>
# include <fcntl.h>
# undef MY_LSTAT
# undef MY_STAT
# define MY_LSTAT stat
# define MY_STAT stat
# undef SET_BINARY_MODE
# define SET_BINARY_MODE(fd) \
do { \
int retVal = setmode ( fileno ( fd ), \
O_BINARY ); \
ERROR_IF_MINUS_ONE ( retVal ); \
} while ( 0 )
# endif
# ifdef __CYGWIN__
# include <io.h>
# include <fcntl.h>
# undef SET_BINARY_MODE
# define SET_BINARY_MODE(fd) \
do { \
int retVal = setmode ( fileno ( fd ), \
O_BINARY ); \
ERROR_IF_MINUS_ONE ( retVal ); \
} while ( 0 )
# endif
#endif /* BZ_UNIX */
#if BZ_LCCWIN32
# include <io.h>
# include <fcntl.h>
# include <sys\stat.h>
# define NORETURN /**/
# define PATH_SEP '\\'
# define MY_LSTAT _stat
# define MY_STAT _stat
# define MY_S_ISREG(x) ((x) & _S_IFREG)
# define MY_S_ISDIR(x) ((x) & _S_IFDIR)
# define APPEND_FLAG(root, name) \
root=snocString((root), (name))
# define APPEND_FILESPEC(root, name) \
root = snocString ((root), (name))
# define SET_BINARY_MODE(fd) \
do { \
int retVal = setmode ( fileno ( fd ), \
O_BINARY ); \
ERROR_IF_MINUS_ONE ( retVal ); \
} while ( 0 )
#endif /* BZ_LCCWIN32 */
/*---------------------------------------------*/
/*--
Some more stuff for all platforms :-)
--*/
typedef short Int16;
typedef unsigned short UInt16;
/*---------------------------------------------------*/
/*--- Misc (file handling) data decls ---*/
/*---------------------------------------------------*/
#undef blockSize100k
#define blockSize100k _blockSize100k
#undef verbosity
#define verbosity _verbosity
#undef smallMode
#define smallMode _smallMode
#undef noisy
#define noisy _noisy
#undef forceOverwrite
#define forceOverwrite _forceOverwrite
Int32 verbosity;
Bool keepInputFiles, smallMode, deleteOutputOnInterrupt;
Bool forceOverwrite, testFailsExist, unzFailsExist, noisy;
Int32 numFileNames, numFilesProcessed, blockSize100k;
Int32 exitValue;
/*-- source modes; F==file, I==stdin, O==stdout --*/
#define SM_I2O 1
#define SM_F2O 2
#define SM_F2F 3
/*-- operation modes --*/
#define OM_Z 1
#define OM_UNZ 2
#define OM_TEST 3
Int32 opMode;
Int32 srcMode;
Int32 longestFileName;
#undef inName
#define inName _inName
Char inName [FILE_NAME_LEN];
Char outName[FILE_NAME_LEN];
Char tmpName[FILE_NAME_LEN];
#undef progName
#define progName _progName
Char *progName;
Char progNameReally[FILE_NAME_LEN];
FILE *outputHandleJustInCase;
void wrapped_clear_outputHandleJustInCase(void) {
outputHandleJustInCase = NULL;
}
static
void unwrap_clear_outputHandleJustInCase ( int fd ) {
wrapped_clear_outputHandleJustInCase();
lc_write_void(fd);
}
#undef workFactor
#define workFactor _workFactor
Int32 workFactor;
static void cleanUpAndFail ( Int32 ) NORETURN;
static void copyFileName ( Char*, Char* );
static void* myMalloc ( Int32 );
static void unwrap_applySavedFileAttrToOutputFile( int fd );
static void unwrap_clear_outputHandleJustInCase ( int fd );
static void unwrap_configError ( int fd ) NORETURN;
static void unwrap_outOfMemory ( int fd ) NORETURN;
static void unwrap_ioError ( int fd ) NORETURN;
static void unwrap_panic ( int fd ) NORETURN;
static void unwrap_crcError ( int fd ) NORETURN;
static void unwrap_compressedStreamEOF ( int fd ) NORETURN;
static int output_fd;
#define CAP(x) { #x, unwrap_##x }
static struct lc_capability caps[] = {
CAP(applySavedFileAttrToOutputFile),
CAP(clear_outputHandleJustInCase),
CAP(configError),
CAP(outOfMemory),
CAP(ioError),
CAP(panic),
CAP(crcError),
CAP(compressedStreamEOF),
};
#undef CAP
// This is only needed to get the function types to match for
// lc_wrap_filter().
static int call_compressStream(FILE *stream, FILE *zStream) {
wrapped_compressStream(stream, zStream);
return 1;
}
static void compressStream(FILE *stream, FILE *zStream) {
if (!lc_available()) {
wrapped_compressStream(stream, zStream);
return;
}
output_fd = fileno(zStream);
// FIXME: this only needs a subset of caps
lc_wrap_filter(call_compressStream, stream, zStream, caps, 8);
}
static int call_uncompressStream(FILE *zStream, FILE *stream) {
return wrapped_uncompressStream(zStream, stream);
}
static Bool uncompressStream(FILE *zStream, FILE *stream) {
if (!lc_available())
return wrapped_uncompressStream(zStream, stream);
output_fd = fileno(stream);
return lc_wrap_filter(call_uncompressStream, zStream, stream, caps, 8);
}
static int call_testStream(FILE *zStream, FILE *dummy) {
return wrapped_testStream(zStream);
}
static Bool testStream(FILE *zStream) {
if (!lc_available())
return wrapped_testStream(zStream);
// FIXME: this only needs a subset of caps
return lc_wrap_filter(call_testStream, zStream, NULL, caps, 8);
}
/*---------------------------------------------------*/
/*--- Error [non-] handling grunge ---*/
/*---------------------------------------------------*/
/*---------------------------------------------*/
static
void setExit ( Int32 v )
{
if (v > exitValue) exitValue = v;
}
/*---------------------------------------------*/
static
void cadvise ( void )
{
if (noisy)
fprintf (
stderr,
"\nIt is possible that the compressed file(s) have become corrupted.\n"
"You can use the -tvv option to test integrity of such files.\n\n"
"You can use the `bzip2recover' program to attempt to recover\n"
"data from undamaged sections of corrupted files.\n\n"
);
}
/*---------------------------------------------*/
static
void showFileNames ( void )
{
if (noisy)
fprintf (
stderr,
"\tInput file = %s, output file = %s\n",
inName, outName
);
}
/*---------------------------------------------*/
static
void cleanUpAndFail ( Int32 ec )
{
IntNative retVal;
struct MY_STAT statBuf;
if ( srcMode == SM_F2F
&& opMode != OM_TEST
&& deleteOutputOnInterrupt ) {
/* Check whether input file still exists. Delete output file
only if input exists to avoid loss of data. Joerg Prante, 5
January 2002. (JRS 06-Jan-2002: other changes in 1.0.2 mean
this is less likely to happen. But to be ultra-paranoid, we
do the check anyway.) */
retVal = MY_STAT ( inName, &statBuf );
if (retVal == 0) {
if (noisy)
fprintf ( stderr,
"%s: Deleting output file %s, if it exists.\n",
progName, outName );
if (outputHandleJustInCase != NULL)
fclose ( outputHandleJustInCase );
retVal = remove ( outName );
if (retVal != 0)
fprintf ( stderr,
"%s: WARNING: deletion of output file "
"(apparently) failed.\n",
progName );
} else {
fprintf ( stderr,
"%s: WARNING: deletion of output file suppressed\n",
progName );
fprintf ( stderr,
"%s: since input file no longer exists. Output file\n",
progName );
fprintf ( stderr,
"%s: `%s' may be incomplete.\n",
progName, outName );
fprintf ( stderr,
"%s: I suggest doing an integrity test (bzip2 -tv)"
" of it.\n",
progName );
}
}
if (noisy && numFileNames > 0 && numFilesProcessed < numFileNames) {
fprintf ( stderr,
"%s: WARNING: some files have not been processed:\n"
"%s: %d specified on command line, %d not processed yet.\n\n",
progName, progName,
numFileNames, numFileNames - numFilesProcessed );
}
setExit(ec);
exit(exitValue);
}
/*---------------------------------------------*/
void wrapped_panic ( const Char* s )
{
fprintf ( stderr,
"\n%s: PANIC -- internal consistency error:\n"
"\t%s\n"
"\tThis is a BUG. Please report it to me at:\n"
"\tjseward@bzip.org\n",
progName, s );
showFileNames();
cleanUpAndFail( 3 );
}
static
void unwrap_panic ( int fd ) {
int wrapped_errno;
char *str;
lc_read_int( fd, &wrapped_errno );
lc_read_string( fd, &str, 1024 );
wrapped_panic( str );
/* NOTREACHED */
}
/*---------------------------------------------*/
void wrapped_crcError ( void )
{
fprintf ( stderr,
"\n%s: Data integrity error when decompressing.\n",
progName );
showFileNames();
cadvise();
cleanUpAndFail( 2 );
}
static
void unwrap_crcError ( int fd ) {
wrapped_crcError();
/* NOTREACHED */
}
/*---------------------------------------------*/
void wrapped_compressedStreamEOF ( void )
{
if (noisy) {
fprintf ( stderr,
"\n%s: Compressed file ends unexpectedly;\n\t"
"perhaps it is corrupted? *Possible* reason follows.\n",
progName );
perror ( progName );
showFileNames();
cadvise();
}
cleanUpAndFail( 2 );
}
static
void unwrap_compressedStreamEOF ( int fd ) {
wrapped_crcError();
/* NOTREACHED */
}
/*---------------------------------------------*/
void wrapped_ioError ( void )
{
fprintf ( stderr,
"\n%s: I/O or other error, bailing out. "
"Possible reason follows.\n",
progName );
perror ( progName );
showFileNames();
cleanUpAndFail( 1 );
}
static
void unwrap_ioError ( int fd ) {
wrapped_ioError();
/* NOTREACHED */
}
/*---------------------------------------------*/
static
void mySignalCatcher ( IntNative n )
{
fprintf ( stderr,
"\n%s: Control-C or similar caught, quitting.\n",
progName );
cleanUpAndFail(1);
}
/*---------------------------------------------*/
static
void mySIGSEGVorSIGBUScatcher ( IntNative n )
{
if (opMode == OM_Z)
fprintf (
stderr,
"\n%s: Caught a SIGSEGV or SIGBUS whilst compressing.\n"
"\n"
" Possible causes are (most likely first):\n"
" (1) This computer has unreliable memory or cache hardware\n"
" (a surprisingly common problem; try a different machine.)\n"
" (2) A bug in the compiler used to create this executable\n"
" (unlikely, if you didn't compile bzip2 yourself.)\n"
" (3) A real bug in bzip2 -- I hope this should never be the case.\n"
" The user's manual, Section 4.3, has more info on (1) and (2).\n"
" \n"
" If you suspect this is a bug in bzip2, or are unsure about (1)\n"
" or (2), feel free to report it to me at: jseward@bzip.org.\n"
" Section 4.3 of the user's manual describes the info a useful\n"
" bug report should have. If the manual is available on your\n"
" system, please try and read it before mailing me. If you don't\n"
" have the manual or can't be bothered to read it, mail me anyway.\n"
"\n",
progName );
else
fprintf (
stderr,
"\n%s: Caught a SIGSEGV or SIGBUS whilst decompressing.\n"
"\n"
" Possible causes are (most likely first):\n"
" (1) The compressed data is corrupted, and bzip2's usual checks\n"
" failed to detect this. Try bzip2 -tvv my_file.bz2.\n"
" (2) This computer has unreliable memory or cache hardware\n"
" (a surprisingly common problem; try a different machine.)\n"
" (3) A bug in the compiler used to create this executable\n"
" (unlikely, if you didn't compile bzip2 yourself.)\n"
" (4) A real bug in bzip2 -- I hope this should never be the case.\n"
" The user's manual, Section 4.3, has more info on (2) and (3).\n"
" \n"
" If you suspect this is a bug in bzip2, or are unsure about (2)\n"
" or (3), feel free to report it to me at: jseward@bzip.org.\n"
" Section 4.3 of the user's manual describes the info a useful\n"
" bug report should have. If the manual is available on your\n"
" system, please try and read it before mailing me. If you don't\n"
" have the manual or can't be bothered to read it, mail me anyway.\n"
"\n",
progName );
showFileNames();
if (opMode == OM_Z)
cleanUpAndFail( 3 ); else
{ cadvise(); cleanUpAndFail( 2 ); }
}
/*---------------------------------------------*/
void wrapped_outOfMemory ( void )
{
fprintf ( stderr,
"\n%s: couldn't allocate enough memory\n",
progName );
showFileNames();
cleanUpAndFail(1);
}
static
void unwrap_outOfMemory ( int fd ) {
wrapped_outOfMemory();
/* NOTREACHED */
}
/*---------------------------------------------*/
void wrapped_configError ( void )
{
fprintf ( stderr,
"bzip2: I'm not configured correctly for this platform!\n"
"\tI require Int32, Int16 and Char to have sizes\n"
"\tof 4, 2 and 1 bytes to run properly, and they don't.\n"
"\tProbably you can fix this by defining them correctly,\n"
"\tand recompiling. Bye!\n" );
setExit(3);
exit(exitValue);
}
static
void unwrap_configError ( int fd ) {
wrapped_configError();
/* NOTREACHED */
}
/*---------------------------------------------------*/
/*--- The main driver machinery ---*/
/*---------------------------------------------------*/
/* All rather crufty. The main problem is that input files
are stat()d multiple times before use. This should be
cleaned up.
*/
/*---------------------------------------------*/
static
void pad ( Char *s )
{
Int32 i;
if ( (Int32)strlen(s) >= longestFileName ) return;
for (i = 1; i <= longestFileName - (Int32)strlen(s); i++)
fprintf ( stderr, " " );
}
/*---------------------------------------------*/
static
void copyFileName ( Char* to, Char* from )
{
if ( strlen(from) > FILE_NAME_LEN-10 ) {
fprintf (
stderr,
"bzip2: file name\n`%s'\n"
"is suspiciously (more than %d chars) long.\n"
"Try using a reasonable file name instead. Sorry! :-)\n",
from, FILE_NAME_LEN-10
);
setExit(1);
exit(exitValue);
}
strncpy(to,from,FILE_NAME_LEN-10);
to[FILE_NAME_LEN-10]='\0';
}
/*---------------------------------------------*/
static
Bool fileExists ( Char* name )
{
FILE *tmp = fopen ( name, "rb" );
Bool exists = (tmp != NULL);
if (tmp != NULL) fclose ( tmp );
return exists;
}
/*---------------------------------------------*/
/* Open an output file safely with O_EXCL and good permissions.
This avoids a race condition in versions < 1.0.2, in which
the file was first opened and then had its interim permissions
set safely. We instead use open() to create the file with
the interim permissions required. (--- --- rw-).
For non-Unix platforms, if we are not worrying about
security issues, simple this simply behaves like fopen.
*/
static
FILE* fopen_output_safely ( Char* name, const char* mode )
{
# if BZ_UNIX
FILE* fp;
IntNative fh;
fh = open(name, O_WRONLY|O_CREAT|O_EXCL, S_IWUSR|S_IRUSR);
if (fh == -1) return NULL;
fp = fdopen(fh, mode);
if (fp == NULL) close(fh);
return fp;
# else
return fopen(name, mode);
# endif
}
/*---------------------------------------------*/
/*--
if in doubt, return True
--*/
static
Bool notAStandardFile ( Char* name )
{
IntNative i;
struct MY_STAT statBuf;
i = MY_LSTAT ( name, &statBuf );
if (i != 0) return True;
if (MY_S_ISREG(statBuf.st_mode)) return False;
return True;
}
/*---------------------------------------------*/
/*--
rac 11/21/98 see if file has hard links to it
--*/
static
Int32 countHardLinks ( Char* name )
{
IntNative i;
struct MY_STAT statBuf;
i = MY_LSTAT ( name, &statBuf );
if (i != 0) return 0;
return (statBuf.st_nlink - 1);
}
/*---------------------------------------------*/
/* Copy modification date, access date, permissions and owner from the
source to destination file. We have to copy this meta-info off
into fileMetaInfo before starting to compress / decompress it,
because doing it afterwards means we get the wrong access time.
To complicate matters, in compress() and decompress() below, the
sequence of tests preceding the call to saveInputFileMetaInfo()
involves calling fileExists(), which in turn establishes its result
by attempting to fopen() the file, and if successful, immediately
fclose()ing it again. So we have to assume that the fopen() call
does not cause the access time field to be updated.
Reading of the man page for stat() (man 2 stat) on RedHat 7.2 seems
to imply that merely doing open() will not affect the access time.
Therefore we merely need to hope that the C library only does
open() as a result of fopen(), and not any kind of read()-ahead
cleverness.
It sounds pretty fragile to me. Whether this carries across
robustly to arbitrary Unix-like platforms (or even works robustly
on this one, RedHat 7.2) is unknown to me. Nevertheless ...
*/
#if BZ_UNIX
static
struct MY_STAT fileMetaInfo;
#endif
static
void saveInputFileMetaInfo ( Char *srcName )
{
# if BZ_UNIX
IntNative retVal;
/* Note use of stat here, not lstat. */
retVal = MY_STAT( srcName, &fileMetaInfo );
ERROR_IF_NOT_ZERO ( retVal );
# endif
}
static
void applySavedTimeInfoToOutputFile ( Char *dstName )
{
# if BZ_UNIX
IntNative retVal;
struct utimbuf uTimBuf;
uTimBuf.actime = fileMetaInfo.st_atime;
uTimBuf.modtime = fileMetaInfo.st_mtime;
retVal = utime ( dstName, &uTimBuf );
ERROR_IF_NOT_ZERO ( retVal );
# endif
}
void wrapped_applySavedFileAttrToOutputFile ( IntNative fd )
{
# if BZ_UNIX
IntNative retVal;
retVal = fchmod ( fd, fileMetaInfo.st_mode );
ERROR_IF_NOT_ZERO ( retVal );
(void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );
/* chown() will in many cases return with EPERM, which can
be safely ignored.
*/
# endif
}
static void unwrap_applySavedFileAttrToOutputFile(int fd) {
int ofd;
lc_read_int(fd, &ofd);
assert(ofd == output_fd);
wrapped_applySavedFileAttrToOutputFile(ofd);
lc_write_void(fd);
}
/*---------------------------------------------*/
static
Bool containsDubiousChars ( Char* name )
{
# if BZ_UNIX
/* On unix, files can contain any characters and the file expansion
* is performed by the shell.
*/
return False;
# else /* ! BZ_UNIX */
/* On non-unix (Win* platforms), wildcard characters are not allowed in
* filenames.
*/
for (; *name != '\0'; name++)
if (*name == '?' || *name == '*') return True;
return False;
# endif /* BZ_UNIX */
}
/*---------------------------------------------*/
#define BZ_N_SUFFIX_PAIRS 4
const Char* zSuffix[BZ_N_SUFFIX_PAIRS]
= { ".bz2", ".bz", ".tbz2", ".tbz" };
const Char* unzSuffix[BZ_N_SUFFIX_PAIRS]
= { "", "", ".tar", ".tar" };
static
Bool hasSuffix ( Char* s, const Char* suffix )
{
Int32 ns = strlen(s);
Int32 nx = strlen(suffix);
if (ns < nx) return False;
if (strcmp(s + ns - nx, suffix) == 0) return True;
return False;
}
static
Bool mapSuffix ( Char* name,
const Char* oldSuffix,
const Char* newSuffix )
{
if (!hasSuffix(name,oldSuffix)) return False;
name[strlen(name)-strlen(oldSuffix)] = 0;
strcat ( name, newSuffix );
return True;
}
/*---------------------------------------------*/
static
void compress ( Char *name )
{
FILE *inStr;
FILE *outStr;
Int32 n, i;
struct MY_STAT statBuf;
deleteOutputOnInterrupt = False;
if (name == NULL && srcMode != SM_I2O)
wrapped_panic ( "compress: bad modes\n" );
switch (srcMode) {
case SM_I2O:
copyFileName ( inName, (Char*)"(stdin)" );
copyFileName ( outName, (Char*)"(stdout)" );
break;
case SM_F2F:
copyFileName ( inName, name );
copyFileName ( outName, name );
strcat ( outName, ".bz2" );
break;
case SM_F2O:
copyFileName ( inName, name );
copyFileName ( outName, (Char*)"(stdout)" );
break;
}
if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) {
if (noisy)
fprintf ( stderr, "%s: There are no files matching `%s'.\n",
progName, inName );
setExit(1);
return;
}
if ( srcMode != SM_I2O && !fileExists ( inName ) ) {
fprintf ( stderr, "%s: Can't open input file %s: %s.\n",
progName, inName, strerror(errno) );
setExit(1);
return;
}
for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++) {
if (hasSuffix(inName, zSuffix[i])) {
if (noisy)
fprintf ( stderr,
"%s: Input file %s already has %s suffix.\n",
progName, inName, zSuffix[i] );
setExit(1);
return;
}
}
if ( srcMode == SM_F2F || srcMode == SM_F2O ) {
MY_STAT(inName, &statBuf);
if ( MY_S_ISDIR(statBuf.st_mode) ) {
fprintf( stderr,
"%s: Input file %s is a directory.\n",
progName,inName);
setExit(1);
return;
}
}
if ( srcMode == SM_F2F && !forceOverwrite && notAStandardFile ( inName )) {
if (noisy)
fprintf ( stderr, "%s: Input file %s is not a normal file.\n",
progName, inName );
setExit(1);
return;
}
if ( srcMode == SM_F2F && fileExists ( outName ) ) {
if (forceOverwrite) {
remove(outName);
} else {
fprintf ( stderr, "%s: Output file %s already exists.\n",
progName, outName );
setExit(1);
return;
}
}
if ( srcMode == SM_F2F && !forceOverwrite &&
(n=countHardLinks ( inName )) > 0) {
fprintf ( stderr, "%s: Input file %s has %d other link%s.\n",
progName, inName, n, n > 1 ? "s" : "" );
setExit(1);
return;
}
if ( srcMode == SM_F2F ) {
/* Save the file's meta-info before we open it. Doing it later
means we mess up the access times. */
saveInputFileMetaInfo ( inName );
}
switch ( srcMode ) {
case SM_I2O:
inStr = stdin;
outStr = stdout;
if ( isatty ( fileno ( stdout ) ) ) {
fprintf ( stderr,
"%s: I won't write compressed data to a terminal.\n",
progName );
fprintf ( stderr, "%s: For help, type: `%s --help'.\n",
progName, progName );
setExit(1);
return;
};
break;
case SM_F2O:
inStr = fopen ( inName, "rb" );
outStr = stdout;
if ( isatty ( fileno ( stdout ) ) ) {
fprintf ( stderr,
"%s: I won't write compressed data to a terminal.\n",
progName );
fprintf ( stderr, "%s: For help, type: `%s --help'.\n",
progName, progName );
if ( inStr != NULL ) fclose ( inStr );
setExit(1);
return;
};
if ( inStr == NULL ) {
fprintf ( stderr, "%s: Can't open input file %s: %s.\n",
progName, inName, strerror(errno) );
setExit(1);
return;
};
break;
case SM_F2F:
inStr = fopen ( inName, "rb" );
outStr = fopen_output_safely ( outName, "wb" );
if ( outStr == NULL) {
fprintf ( stderr, "%s: Can't create output file %s: %s.\n",
progName, outName, strerror(errno) );
if ( inStr != NULL ) fclose ( inStr );
setExit(1);
return;
}
if ( inStr == NULL ) {
fprintf ( stderr, "%s: Can't open input file %s: %s.\n",
progName, inName, strerror(errno) );
if ( outStr != NULL ) fclose ( outStr );
setExit(1);
return;
};
break;
default:
wrapped_panic ( "compress: bad srcMode" );
break;
}
if (verbosity >= 1) {
fprintf ( stderr, " %s: ", inName );
pad ( inName );
fflush ( stderr );
}
/*--- Now the input and output handles are sane. Do the Biz. ---*/
outputHandleJustInCase = outStr;
deleteOutputOnInterrupt = True;
compressStream ( inStr, outStr );
outputHandleJustInCase = NULL;
/*--- If there was an I/O error, we won't get here. ---*/
if ( srcMode == SM_F2F ) {
applySavedTimeInfoToOutputFile ( outName );
deleteOutputOnInterrupt = False;
if ( !keepInputFiles ) {
IntNative retVal = remove ( inName );
ERROR_IF_NOT_ZERO ( retVal );
}
}
deleteOutputOnInterrupt = False;
}
/*---------------------------------------------*/
static
void uncompress ( Char *name )
{
FILE *inStr;