1 /* $NetBSD: gzip.c,v 1.119 2023/06/10 04:45:25 simonb Exp $ */
2
3 /*
4 * Copyright (c) 1997, 1998, 2003, 2004, 2006, 2008, 2009, 2010, 2011, 2015, 2017
5 * Matthew R. Green
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
22 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30 #include <sys/cdefs.h>
31 #ifndef lint
32 __COPYRIGHT("@(#) Copyright (c) 1997, 1998, 2003, 2004, 2006, 2008,\
33 2009, 2010, 2011, 2015, 2017 Matthew R. Green. All rights reserved.");
34 __RCSID("$NetBSD: gzip.c,v 1.119 2023/06/10 04:45:25 simonb Exp $");
35 #endif /* not lint */
36
37 /*
38 * gzip.c -- GPL free gzip using zlib.
39 *
40 * RFC 1950 covers the zlib format
41 * RFC 1951 covers the deflate format
42 * RFC 1952 covers the gzip format
43 *
44 * TODO:
45 * - use mmap where possible
46 * - handle some signals better (remove outfile?)
47 * - make bzip2/compress -v/-t/-l support work as well as possible
48 */
49
50 #include <sys/param.h>
51 #include <sys/stat.h>
52 #include <sys/time.h>
53
54 #include <inttypes.h>
55 #include <unistd.h>
56 #include <stdio.h>
57 #include <string.h>
58 #include <stdlib.h>
59 #include <err.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <zlib.h>
63 #include <fts.h>
64 #include <libgen.h>
65 #include <stdarg.h>
66 #include <getopt.h>
67 #include <time.h>
68 #include <paths.h>
69
70 #ifndef PRIdOFF
71 #define PRIdOFF PRId64
72 #endif
73
74 /* what type of file are we dealing with */
75 enum filetype {
76 FT_GZIP,
77 #ifndef NO_BZIP2_SUPPORT
78 FT_BZIP2,
79 #endif
80 #ifndef NO_COMPRESS_SUPPORT
81 FT_Z,
82 #endif
83 #ifndef NO_PACK_SUPPORT
84 FT_PACK,
85 #endif
86 #ifndef NO_XZ_SUPPORT
87 FT_XZ,
88 #endif
89 #ifndef NO_LZ_SUPPORT
90 FT_LZ,
91 #endif
92 FT_LAST,
93 FT_UNKNOWN
94 };
95
96 #ifndef NO_BZIP2_SUPPORT
97 #include <bzlib.h>
98
99 #define BZ2_SUFFIX ".bz2"
100 #define BZIP2_MAGIC "\102\132\150"
101 #endif
102
103 #ifndef NO_COMPRESS_SUPPORT
104 #define Z_SUFFIX ".Z"
105 #define Z_MAGIC "\037\235"
106 #endif
107
108 #ifndef NO_PACK_SUPPORT
109 #define PACK_MAGIC "\037\036"
110 #endif
111
112 #ifndef NO_XZ_SUPPORT
113 #include <lzma.h>
114 #define XZ_SUFFIX ".xz"
115 #define XZ_MAGIC "\3757zXZ"
116 #endif
117
118 #ifndef NO_LZ_SUPPORT
119 #define LZ_SUFFIX ".lz"
120 #define LZ_MAGIC "LZIP"
121 #endif
122
123 #define GZ_SUFFIX ".gz"
124
125 #define BUFLEN (64 * 1024)
126
127 #define GZIP_MAGIC0 0x1F
128 #define GZIP_MAGIC1 0x8B
129 #define GZIP_OMAGIC1 0x9E
130
131 #define GZIP_TIMESTAMP (off_t)4
132 #define GZIP_ORIGNAME (off_t)10
133
134 #define HEAD_CRC 0x02
135 #define EXTRA_FIELD 0x04
136 #define ORIG_NAME 0x08
137 #define COMMENT 0x10
138
139 #define OS_CODE 3 /* Unix */
140
141 typedef struct {
142 const char *zipped;
143 int ziplen;
144 const char *normal; /* for unzip - must not be longer than zipped */
145 } suffixes_t;
146 static suffixes_t suffixes[] = {
147 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N}
148 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S .xxx */
149 #ifndef SMALL
150 SUFFIX(GZ_SUFFIX, ""),
151 SUFFIX(".z", ""),
152 SUFFIX("-gz", ""),
153 SUFFIX("-z", ""),
154 SUFFIX("_z", ""),
155 SUFFIX(".taz", ".tar"),
156 SUFFIX(".tgz", ".tar"),
157 #ifndef NO_BZIP2_SUPPORT
158 SUFFIX(BZ2_SUFFIX, ""),
159 #endif
160 #ifndef NO_COMPRESS_SUPPORT
161 SUFFIX(Z_SUFFIX, ""),
162 #endif
163 #ifndef NO_XZ_SUPPORT
164 SUFFIX(XZ_SUFFIX, ""),
165 #endif
166 #ifndef NO_LZ_SUPPORT
167 SUFFIX(LZ_SUFFIX, ""),
168 #endif
169 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S "" */
170 #endif /* SMALL */
171 #undef SUFFIX
172 };
173 #define NUM_SUFFIXES (sizeof suffixes / sizeof suffixes[0])
174 #define SUFFIX_MAXLEN 30
175
176 static const char gzip_version[] = "NetBSD gzip 20170803";
177
178 static int cflag; /* stdout mode */
179 static int dflag; /* decompress mode */
180 static int lflag; /* list mode */
181 static int numflag = 6; /* gzip -1..-9 value */
182
183 #ifndef SMALL
184 static int fflag; /* force mode */
185 static int kflag; /* don't delete input files */
186 static int nflag; /* don't save name/timestamp */
187 static int Nflag; /* don't restore name/timestamp */
188 static int qflag; /* quiet mode */
189 static int rflag; /* recursive mode */
190 static int tflag; /* test */
191 static int vflag; /* verbose mode */
192 static sig_atomic_t print_info = 0;
193 #else
194 #define qflag 0
195 #define tflag 0
196 #endif
197
198 static int exit_value = 0; /* exit value */
199
200 static const char *infile; /* name of file coming in */
201
202 static void maybe_err(const char *fmt, ...) __printflike(1, 2) __dead;
203 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
204 !defined(NO_XZ_SUPPORT)
205 static void maybe_errx(const char *fmt, ...) __printflike(1, 2) __dead;
206 #endif
207 static void maybe_warn(const char *fmt, ...) __printflike(1, 2);
208 static void maybe_warnx(const char *fmt, ...) __printflike(1, 2);
209 static enum filetype file_gettype(u_char *);
210 #ifdef SMALL
211 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
212 #endif
213 static off_t gz_compress(int, int, off_t *, const char *, uint32_t);
214 static off_t gz_uncompress(int, int, char *, size_t, off_t *, const char *);
215 static off_t file_compress(char *, char *, size_t);
216 static off_t file_uncompress(char *, char *, size_t);
217 static void handle_pathname(char *);
218 static void handle_file(char *, struct stat *);
219 static void handle_stdin(void);
220 static void handle_stdout(void);
221 static void print_ratio(off_t, off_t, FILE *);
222 static void print_list(int fd, off_t, const char *, time_t);
223 __dead static void usage(void);
224 __dead static void display_version(void);
225 static const suffixes_t *check_suffix(char *, int);
226 static ssize_t read_retry(int, void *, size_t);
227 static ssize_t write_retry(int, const void *, size_t);
228 static void print_list_out(off_t, off_t, const char*);
229
230 #ifdef SMALL
231 #define infile_set(f,t) infile_set(f)
232 #endif
233 static void infile_set(const char *newinfile, off_t total);
234
235 #ifdef SMALL
236 #define unlink_input(f, sb) unlink(f)
237 #define check_siginfo() /* nothing */
238 #define setup_signals() /* nothing */
239 #define infile_newdata(t) /* nothing */
240 #else
241 static off_t infile_total; /* total expected to read/write */
242 static off_t infile_current; /* current read/write */
243
244 static void check_siginfo(void);
245 static off_t cat_fd(unsigned char *, size_t, off_t *, int fd);
246 static void prepend_gzip(char *, int *, char ***);
247 static void handle_dir(char *);
248 static void print_verbage(const char *, const char *, off_t, off_t);
249 static void print_test(const char *, int);
250 static void copymodes(int fd, const struct stat *, const char *file);
251 static int check_outfile(const char *outfile);
252 static void setup_signals(void);
253 static void infile_newdata(size_t newdata);
254 static void infile_clear(void);
255 #endif
256
257 #ifndef NO_BZIP2_SUPPORT
258 static off_t unbzip2(int, int, char *, size_t, off_t *);
259 #endif
260
261 #ifndef NO_COMPRESS_SUPPORT
262 static FILE *zdopen(int);
263 static off_t zuncompress(FILE *, FILE *, char *, size_t, off_t *);
264 #endif
265
266 #ifndef NO_PACK_SUPPORT
267 static off_t unpack(int, int, char *, size_t, off_t *);
268 #endif
269
270 #ifndef NO_XZ_SUPPORT
271 static off_t unxz(int, int, char *, size_t, off_t *);
272 static off_t unxz_len(int);
273 #endif
274
275 #ifndef NO_LZ_SUPPORT
276 static off_t unlz(int, int, char *, size_t, off_t *);
277 #endif
278
279 #ifdef SMALL
280 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
281 #else
282 static const struct option longopts[] = {
283 { "stdout", no_argument, 0, 'c' },
284 { "to-stdout", no_argument, 0, 'c' },
285 { "decompress", no_argument, 0, 'd' },
286 { "uncompress", no_argument, 0, 'd' },
287 { "force", no_argument, 0, 'f' },
288 { "help", no_argument, 0, 'h' },
289 { "keep", no_argument, 0, 'k' },
290 { "list", no_argument, 0, 'l' },
291 { "no-name", no_argument, 0, 'n' },
292 { "name", no_argument, 0, 'N' },
293 { "quiet", no_argument, 0, 'q' },
294 { "recursive", no_argument, 0, 'r' },
295 { "suffix", required_argument, 0, 'S' },
296 { "test", no_argument, 0, 't' },
297 { "verbose", no_argument, 0, 'v' },
298 { "version", no_argument, 0, 'V' },
299 { "fast", no_argument, 0, '1' },
300 { "best", no_argument, 0, '9' },
301 #if 0
302 /*
303 * This is what else GNU gzip implements. --ascii isn't useful
304 * on NetBSD, and I don't care to have a --license.
305 */
306 { "ascii", no_argument, 0, 'a' },
307 { "license", no_argument, 0, 'L' },
308 #endif
309 { NULL, no_argument, 0, 0 },
310 };
311 #endif
312
313 int
main(int argc,char ** argv)314 main(int argc, char **argv)
315 {
316 const char *progname = getprogname();
317 #ifndef SMALL
318 char *gzip;
319 int len;
320 #endif
321 int ch;
322
323 setup_signals();
324
325 #ifndef SMALL
326 if ((gzip = getenv("GZIP")) != NULL)
327 prepend_gzip(gzip, &argc, &argv);
328 #endif
329
330 /*
331 * XXX
332 * handle being called `gunzip', `zcat' and `gzcat'
333 */
334 if (strcmp(progname, "gunzip") == 0)
335 dflag = 1;
336 else if (strcmp(progname, "zcat") == 0 ||
337 strcmp(progname, "gzcat") == 0)
338 dflag = cflag = 1;
339
340 #ifdef SMALL
341 #define OPT_LIST "123456789cdhlV"
342 #else
343 #define OPT_LIST "123456789cdfhklNnqrS:tVv"
344 #endif
345
346 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
347 switch (ch) {
348 case '1': case '2': case '3':
349 case '4': case '5': case '6':
350 case '7': case '8': case '9':
351 numflag = ch - '0';
352 break;
353 case 'c':
354 cflag = 1;
355 break;
356 case 'd':
357 dflag = 1;
358 break;
359 case 'l':
360 lflag = 1;
361 dflag = 1;
362 break;
363 case 'V':
364 display_version();
365 /* NOTREACHED */
366 #ifndef SMALL
367 case 'f':
368 fflag = 1;
369 break;
370 case 'k':
371 kflag = 1;
372 break;
373 case 'N':
374 nflag = 0;
375 Nflag = 1;
376 break;
377 case 'n':
378 nflag = 1;
379 Nflag = 0;
380 break;
381 case 'q':
382 qflag = 1;
383 break;
384 case 'r':
385 rflag = 1;
386 break;
387 case 'S':
388 len = strlen(optarg);
389 if (len != 0) {
390 if (len > SUFFIX_MAXLEN)
391 errx(1, "incorrect suffix: '%s'", optarg);
392 suffixes[0].zipped = optarg;
393 suffixes[0].ziplen = len;
394 } else {
395 suffixes[NUM_SUFFIXES - 1].zipped = "";
396 suffixes[NUM_SUFFIXES - 1].ziplen = 0;
397 }
398 break;
399 case 't':
400 cflag = 1;
401 tflag = 1;
402 dflag = 1;
403 break;
404 case 'v':
405 vflag = 1;
406 break;
407 #endif
408 default:
409 usage();
410 /* NOTREACHED */
411 }
412 }
413 argv += optind;
414 argc -= optind;
415
416 if (argc == 0) {
417 if (dflag) /* stdin mode */
418 handle_stdin();
419 else /* stdout mode */
420 handle_stdout();
421 } else {
422 do {
423 handle_pathname(argv[0]);
424 } while (*++argv);
425 }
426 #ifndef SMALL
427 if (qflag == 0 && lflag && argc > 1)
428 print_list(-1, 0, "(totals)", 0);
429 #endif
430 exit(exit_value);
431 }
432
433 /* maybe print a warning */
434 void
maybe_warn(const char * fmt,...)435 maybe_warn(const char *fmt, ...)
436 {
437 va_list ap;
438
439 if (qflag == 0) {
440 va_start(ap, fmt);
441 vwarn(fmt, ap);
442 va_end(ap);
443 }
444 if (exit_value == 0)
445 exit_value = 1;
446 }
447
448 /* ... without an errno. */
449 void
maybe_warnx(const char * fmt,...)450 maybe_warnx(const char *fmt, ...)
451 {
452 va_list ap;
453
454 if (qflag == 0) {
455 va_start(ap, fmt);
456 vwarnx(fmt, ap);
457 va_end(ap);
458 }
459 if (exit_value == 0)
460 exit_value = 1;
461 }
462
463 /* maybe print an error */
464 void
maybe_err(const char * fmt,...)465 maybe_err(const char *fmt, ...)
466 {
467 va_list ap;
468
469 if (qflag == 0) {
470 va_start(ap, fmt);
471 vwarn(fmt, ap);
472 va_end(ap);
473 }
474 exit(2);
475 }
476
477 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
478 !defined(NO_XZ_SUPPORT)
479 /* ... without an errno. */
480 void
maybe_errx(const char * fmt,...)481 maybe_errx(const char *fmt, ...)
482 {
483 va_list ap;
484
485 if (qflag == 0) {
486 va_start(ap, fmt);
487 vwarnx(fmt, ap);
488 va_end(ap);
489 }
490 exit(2);
491 }
492 #endif
493
494 #ifndef SMALL
495 /* split up $GZIP and prepend it to the argument list */
496 static void
prepend_gzip(char * gzip,int * argc,char *** argv)497 prepend_gzip(char *gzip, int *argc, char ***argv)
498 {
499 char *s, **nargv, **ac;
500 int nenvarg = 0, i;
501
502 /* scan how many arguments there are */
503 for (s = gzip;;) {
504 while (*s == ' ' || *s == '\t')
505 s++;
506 if (*s == 0)
507 goto count_done;
508 nenvarg++;
509 while (*s != ' ' && *s != '\t')
510 if (*s++ == 0)
511 goto count_done;
512 }
513 count_done:
514 /* punt early */
515 if (nenvarg == 0)
516 return;
517
518 *argc += nenvarg;
519 ac = *argv;
520
521 nargv = (char **)malloc((*argc + 1) * sizeof(char *));
522 if (nargv == NULL)
523 maybe_err("malloc");
524
525 /* stash this away */
526 *argv = nargv;
527
528 /* copy the program name first */
529 i = 0;
530 nargv[i++] = *(ac++);
531
532 /* take a copy of $GZIP and add it to the array */
533 s = strdup(gzip);
534 if (s == NULL)
535 maybe_err("strdup");
536 for (;;) {
537 /* Skip whitespaces. */
538 while (*s == ' ' || *s == '\t')
539 s++;
540 if (*s == 0)
541 goto copy_done;
542 nargv[i++] = s;
543 /* Find the end of this argument. */
544 while (*s != ' ' && *s != '\t')
545 if (*s++ == 0)
546 /* Argument followed by NUL. */
547 goto copy_done;
548 /* Terminate by overwriting ' ' or '\t' with NUL. */
549 *s++ = 0;
550 }
551 copy_done:
552
553 /* copy the original arguments and a NULL */
554 while (*ac)
555 nargv[i++] = *(ac++);
556 nargv[i] = NULL;
557 }
558 #endif
559
560 /* compress input to output. Return bytes read, -1 on error */
561 static off_t
gz_compress(int in,int out,off_t * gsizep,const char * origname,uint32_t mtime)562 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
563 {
564 z_stream z;
565 char *outbufp, *inbufp;
566 off_t in_tot = 0, out_tot = 0;
567 ssize_t in_size;
568 int i, error;
569 uLong crc;
570 #ifdef SMALL
571 static char header[] = { GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 0,
572 0, 0, 0, 0,
573 0, OS_CODE };
574 #endif
575
576 outbufp = malloc(BUFLEN);
577 inbufp = malloc(BUFLEN);
578 if (outbufp == NULL || inbufp == NULL) {
579 maybe_err("malloc failed");
580 goto out;
581 }
582
583 memset(&z, 0, sizeof z);
584 z.zalloc = Z_NULL;
585 z.zfree = Z_NULL;
586 z.opaque = 0;
587
588 #ifdef SMALL
589 memcpy(outbufp, header, sizeof header);
590 i = sizeof header;
591 #else
592 if (nflag != 0) {
593 mtime = 0;
594 origname = "";
595 }
596
597 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
598 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
599 *origname ? ORIG_NAME : 0,
600 mtime & 0xff,
601 (mtime >> 8) & 0xff,
602 (mtime >> 16) & 0xff,
603 (mtime >> 24) & 0xff,
604 numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
605 OS_CODE, origname);
606 if (i >= BUFLEN)
607 /* this need PATH_MAX > BUFLEN ... */
608 maybe_err("snprintf");
609 if (*origname)
610 i++;
611 #endif
612
613 z.next_out = (unsigned char *)outbufp + i;
614 z.avail_out = BUFLEN - i;
615
616 error = deflateInit2(&z, numflag, Z_DEFLATED,
617 (-MAX_WBITS), 8, Z_DEFAULT_STRATEGY);
618 if (error != Z_OK) {
619 maybe_warnx("deflateInit2 failed");
620 in_tot = -1;
621 goto out;
622 }
623
624 crc = crc32(0L, Z_NULL, 0);
625 for (;;) {
626 check_siginfo();
627 if (z.avail_out == 0) {
628 if (write_retry(out, outbufp, BUFLEN) != BUFLEN) {
629 maybe_warn("write");
630 out_tot = -1;
631 goto out;
632 }
633
634 out_tot += BUFLEN;
635 z.next_out = (unsigned char *)outbufp;
636 z.avail_out = BUFLEN;
637 }
638
639 if (z.avail_in == 0) {
640 in_size = read(in, inbufp, BUFLEN);
641 if (in_size < 0) {
642 maybe_warn("read");
643 in_tot = -1;
644 goto out;
645 }
646 if (in_size == 0)
647 break;
648 infile_newdata(in_size);
649
650 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
651 in_tot += in_size;
652 z.next_in = (unsigned char *)inbufp;
653 z.avail_in = in_size;
654 }
655
656 error = deflate(&z, Z_NO_FLUSH);
657 if (error != Z_OK && error != Z_STREAM_END) {
658 maybe_warnx("deflate failed");
659 in_tot = -1;
660 goto out;
661 }
662 }
663
664 /* clean up */
665 for (;;) {
666 size_t len;
667 ssize_t w;
668
669 error = deflate(&z, Z_FINISH);
670 if (error != Z_OK && error != Z_STREAM_END) {
671 maybe_warnx("deflate failed");
672 in_tot = -1;
673 goto out;
674 }
675
676 len = (char *)z.next_out - outbufp;
677
678 w = write_retry(out, outbufp, len);
679 if (w == -1 || (size_t)w != len) {
680 maybe_warn("write");
681 out_tot = -1;
682 goto out;
683 }
684 out_tot += len;
685 z.next_out = (unsigned char *)outbufp;
686 z.avail_out = BUFLEN;
687
688 if (error == Z_STREAM_END)
689 break;
690 }
691
692 if (deflateEnd(&z) != Z_OK) {
693 maybe_warnx("deflateEnd failed");
694 in_tot = -1;
695 goto out;
696 }
697
698 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
699 (int)crc & 0xff,
700 (int)(crc >> 8) & 0xff,
701 (int)(crc >> 16) & 0xff,
702 (int)(crc >> 24) & 0xff,
703 (int)in_tot & 0xff,
704 (int)(in_tot >> 8) & 0xff,
705 (int)(in_tot >> 16) & 0xff,
706 (int)(in_tot >> 24) & 0xff);
707 if (i != 8)
708 maybe_err("snprintf");
709 #if 0
710 if (in_tot > 0xffffffff)
711 maybe_warn("input file size >= 4GB cannot be saved");
712 #endif
713 if (write_retry(out, outbufp, i) != i) {
714 maybe_warn("write");
715 in_tot = -1;
716 } else
717 out_tot += i;
718
719 out:
720 if (inbufp != NULL)
721 free(inbufp);
722 if (outbufp != NULL)
723 free(outbufp);
724 if (gsizep)
725 *gsizep = out_tot;
726 return in_tot;
727 }
728
729 /*
730 * uncompress input to output then close the input. return the
731 * uncompressed size written, and put the compressed sized read
732 * into `*gsizep'.
733 */
734 static off_t
gz_uncompress(int in,int out,char * pre,size_t prelen,off_t * gsizep,const char * filename)735 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
736 const char *filename)
737 {
738 z_stream z;
739 char *outbufp, *inbufp;
740 off_t out_tot = -1, in_tot = 0;
741 uint32_t out_sub_tot = 0;
742 enum {
743 GZSTATE_MAGIC0,
744 GZSTATE_MAGIC1,
745 GZSTATE_METHOD,
746 GZSTATE_FLAGS,
747 GZSTATE_SKIPPING,
748 GZSTATE_EXTRA,
749 GZSTATE_EXTRA2,
750 GZSTATE_EXTRA3,
751 GZSTATE_ORIGNAME,
752 GZSTATE_COMMENT,
753 GZSTATE_HEAD_CRC1,
754 GZSTATE_HEAD_CRC2,
755 GZSTATE_INIT,
756 GZSTATE_READ,
757 GZSTATE_CRC,
758 GZSTATE_LEN,
759 } state = GZSTATE_MAGIC0;
760 int flags = 0, skip_count = 0;
761 int error = Z_STREAM_ERROR, done_reading = 0;
762 uLong crc = 0;
763 ssize_t wr;
764 int needmore = 0;
765
766 #define ADVANCE() { z.next_in++; z.avail_in--; }
767
768 if ((outbufp = malloc(BUFLEN)) == NULL) {
769 maybe_err("malloc failed");
770 goto out2;
771 }
772 if ((inbufp = malloc(BUFLEN)) == NULL) {
773 maybe_err("malloc failed");
774 goto out1;
775 }
776
777 memset(&z, 0, sizeof z);
778 z.avail_in = prelen;
779 z.next_in = (unsigned char *)pre;
780 z.avail_out = BUFLEN;
781 z.next_out = (unsigned char *)outbufp;
782 z.zalloc = NULL;
783 z.zfree = NULL;
784 z.opaque = 0;
785
786 in_tot = prelen;
787 out_tot = 0;
788
789 for (;;) {
790 check_siginfo();
791 if ((z.avail_in == 0 || needmore) && done_reading == 0) {
792 ssize_t in_size;
793
794 if (z.avail_in > 0) {
795 memmove(inbufp, z.next_in, z.avail_in);
796 }
797 z.next_in = (unsigned char *)inbufp;
798 in_size = read(in, z.next_in + z.avail_in,
799 BUFLEN - z.avail_in);
800
801 if (in_size == -1) {
802 maybe_warn("failed to read stdin");
803 goto stop_and_fail;
804 } else if (in_size == 0) {
805 done_reading = 1;
806 }
807 infile_newdata(in_size);
808
809 z.avail_in += in_size;
810 needmore = 0;
811
812 in_tot += in_size;
813 }
814 if (z.avail_in == 0) {
815 if (done_reading && state != GZSTATE_MAGIC0) {
816 maybe_warnx("%s: unexpected end of file",
817 filename);
818 goto stop_and_fail;
819 }
820 goto stop;
821 }
822 switch (state) {
823 case GZSTATE_MAGIC0:
824 if (*z.next_in != GZIP_MAGIC0) {
825 if (in_tot > 0) {
826 maybe_warnx("%s: trailing garbage "
827 "ignored", filename);
828 goto stop;
829 }
830 maybe_warnx("input not gziped (MAGIC0)");
831 exit_value = 2;
832 goto stop_and_fail;
833 }
834 ADVANCE();
835 state++;
836 out_sub_tot = 0;
837 crc = crc32(0L, Z_NULL, 0);
838 break;
839
840 case GZSTATE_MAGIC1:
841 if (*z.next_in != GZIP_MAGIC1 &&
842 *z.next_in != GZIP_OMAGIC1) {
843 maybe_warnx("input not gziped (MAGIC1)");
844 goto stop_and_fail;
845 }
846 ADVANCE();
847 state++;
848 break;
849
850 case GZSTATE_METHOD:
851 if (*z.next_in != Z_DEFLATED) {
852 maybe_warnx("unknown compression method");
853 goto stop_and_fail;
854 }
855 ADVANCE();
856 state++;
857 break;
858
859 case GZSTATE_FLAGS:
860 flags = *z.next_in;
861 ADVANCE();
862 skip_count = 6;
863 state++;
864 break;
865
866 case GZSTATE_SKIPPING:
867 if (skip_count > 0) {
868 skip_count--;
869 ADVANCE();
870 } else
871 state++;
872 break;
873
874 case GZSTATE_EXTRA:
875 if ((flags & EXTRA_FIELD) == 0) {
876 state = GZSTATE_ORIGNAME;
877 break;
878 }
879 skip_count = *z.next_in;
880 ADVANCE();
881 state++;
882 break;
883
884 case GZSTATE_EXTRA2:
885 skip_count |= ((*z.next_in) << 8);
886 ADVANCE();
887 state++;
888 break;
889
890 case GZSTATE_EXTRA3:
891 if (skip_count > 0) {
892 skip_count--;
893 ADVANCE();
894 } else
895 state++;
896 break;
897
898 case GZSTATE_ORIGNAME:
899 if ((flags & ORIG_NAME) == 0) {
900 state++;
901 break;
902 }
903 if (*z.next_in == 0)
904 state++;
905 ADVANCE();
906 break;
907
908 case GZSTATE_COMMENT:
909 if ((flags & COMMENT) == 0) {
910 state++;
911 break;
912 }
913 if (*z.next_in == 0)
914 state++;
915 ADVANCE();
916 break;
917
918 case GZSTATE_HEAD_CRC1:
919 if (flags & HEAD_CRC)
920 skip_count = 2;
921 else
922 skip_count = 0;
923 state++;
924 break;
925
926 case GZSTATE_HEAD_CRC2:
927 if (skip_count > 0) {
928 skip_count--;
929 ADVANCE();
930 } else
931 state++;
932 break;
933
934 case GZSTATE_INIT:
935 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
936 maybe_warnx("failed to inflateInit");
937 goto stop_and_fail;
938 }
939 state++;
940 break;
941
942 case GZSTATE_READ:
943 error = inflate(&z, Z_FINISH);
944 switch (error) {
945 /* Z_BUF_ERROR goes with Z_FINISH... */
946 case Z_BUF_ERROR:
947 if (z.avail_out > 0 && !done_reading)
948 continue;
949
950 case Z_STREAM_END:
951 case Z_OK:
952 break;
953
954 case Z_NEED_DICT:
955 maybe_warnx("Z_NEED_DICT error");
956 goto stop_and_fail;
957 case Z_DATA_ERROR:
958 maybe_warnx("data stream error");
959 goto stop_and_fail;
960 case Z_STREAM_ERROR:
961 maybe_warnx("internal stream error");
962 goto stop_and_fail;
963 case Z_MEM_ERROR:
964 maybe_warnx("memory allocation error");
965 goto stop_and_fail;
966
967 default:
968 maybe_warn("unknown error from inflate(): %d",
969 error);
970 }
971 wr = BUFLEN - z.avail_out;
972
973 if (wr != 0) {
974 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
975 if (
976 #ifndef SMALL
977 /* don't write anything with -t */
978 tflag == 0 &&
979 #endif
980 write_retry(out, outbufp, wr) != wr) {
981 maybe_warn("error writing to output");
982 goto stop_and_fail;
983 }
984
985 out_tot += wr;
986 out_sub_tot += wr;
987 }
988
989 if (error == Z_STREAM_END) {
990 inflateEnd(&z);
991 state++;
992 }
993
994 z.next_out = (unsigned char *)outbufp;
995 z.avail_out = BUFLEN;
996
997 break;
998 case GZSTATE_CRC:
999 {
1000 uLong origcrc;
1001
1002 if (z.avail_in < 4) {
1003 if (!done_reading) {
1004 needmore = 1;
1005 continue;
1006 }
1007 maybe_warnx("truncated input");
1008 goto stop_and_fail;
1009 }
1010 origcrc = ((unsigned)z.next_in[0] & 0xff) |
1011 ((unsigned)z.next_in[1] & 0xff) << 8 |
1012 ((unsigned)z.next_in[2] & 0xff) << 16 |
1013 ((unsigned)z.next_in[3] & 0xff) << 24;
1014 if (origcrc != crc) {
1015 maybe_warnx("invalid compressed"
1016 " data--crc error");
1017 goto stop_and_fail;
1018 }
1019 }
1020
1021 z.avail_in -= 4;
1022 z.next_in += 4;
1023
1024 if (!z.avail_in && done_reading) {
1025 goto stop;
1026 }
1027 state++;
1028 break;
1029 case GZSTATE_LEN:
1030 {
1031 uLong origlen;
1032
1033 if (z.avail_in < 4) {
1034 if (!done_reading) {
1035 needmore = 1;
1036 continue;
1037 }
1038 maybe_warnx("truncated input");
1039 goto stop_and_fail;
1040 }
1041 origlen = ((unsigned)z.next_in[0] & 0xff) |
1042 ((unsigned)z.next_in[1] & 0xff) << 8 |
1043 ((unsigned)z.next_in[2] & 0xff) << 16 |
1044 ((unsigned)z.next_in[3] & 0xff) << 24;
1045
1046 if (origlen != out_sub_tot) {
1047 maybe_warnx("invalid compressed"
1048 " data--length error");
1049 goto stop_and_fail;
1050 }
1051 }
1052
1053 z.avail_in -= 4;
1054 z.next_in += 4;
1055
1056 if (error < 0) {
1057 maybe_warnx("decompression error");
1058 goto stop_and_fail;
1059 }
1060 state = GZSTATE_MAGIC0;
1061 break;
1062 }
1063 continue;
1064 stop_and_fail:
1065 out_tot = -1;
1066 stop:
1067 break;
1068 }
1069 if (state > GZSTATE_INIT)
1070 inflateEnd(&z);
1071
1072 free(inbufp);
1073 out1:
1074 free(outbufp);
1075 out2:
1076 if (gsizep)
1077 *gsizep = in_tot;
1078 return (out_tot);
1079 }
1080
1081 #ifndef SMALL
1082 /*
1083 * set the owner, mode, flags & utimes using the given file descriptor.
1084 * file is only used in possible warning messages.
1085 */
1086 static void
copymodes(int fd,const struct stat * sbp,const char * file)1087 copymodes(int fd, const struct stat *sbp, const char *file)
1088 {
1089 struct timeval times[2];
1090 struct stat sb;
1091
1092 /*
1093 * If we have no info on the input, give this file some
1094 * default values and return..
1095 */
1096 if (sbp == NULL) {
1097 mode_t mask = umask(022);
1098
1099 (void)fchmod(fd, DEFFILEMODE & ~mask);
1100 (void)umask(mask);
1101 return;
1102 }
1103 sb = *sbp;
1104
1105 /* if the chown fails, remove set-id bits as-per compress(1) */
1106 if (fchown(fd, sb.st_uid, sb.st_gid) < 0) {
1107 if (errno != EPERM)
1108 maybe_warn("couldn't fchown: %s", file);
1109 sb.st_mode &= ~(S_ISUID|S_ISGID);
1110 }
1111
1112 /* we only allow set-id and the 9 normal permission bits */
1113 sb.st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1114 if (fchmod(fd, sb.st_mode) < 0)
1115 maybe_warn("couldn't fchmod: %s", file);
1116
1117 /* only try flags if they exist already */
1118 if (sb.st_flags != 0 && fchflags(fd, sb.st_flags) < 0)
1119 maybe_warn("couldn't fchflags: %s", file);
1120
1121 TIMESPEC_TO_TIMEVAL(×[0], &sb.st_atimespec);
1122 TIMESPEC_TO_TIMEVAL(×[1], &sb.st_mtimespec);
1123 if (futimes(fd, times) < 0)
1124 maybe_warn("couldn't utimes: %s", file);
1125 }
1126 #endif
1127
1128 /* what sort of file is this? */
1129 static enum filetype
file_gettype(u_char * buf)1130 file_gettype(u_char *buf)
1131 {
1132
1133 if (buf[0] == GZIP_MAGIC0 &&
1134 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1135 return FT_GZIP;
1136 else
1137 #ifndef NO_BZIP2_SUPPORT
1138 if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1139 buf[3] >= '0' && buf[3] <= '9')
1140 return FT_BZIP2;
1141 else
1142 #endif
1143 #ifndef NO_COMPRESS_SUPPORT
1144 if (memcmp(buf, Z_MAGIC, 2) == 0)
1145 return FT_Z;
1146 else
1147 #endif
1148 #ifndef NO_PACK_SUPPORT
1149 if (memcmp(buf, PACK_MAGIC, 2) == 0)
1150 return FT_PACK;
1151 else
1152 #endif
1153 #ifndef NO_XZ_SUPPORT
1154 if (memcmp(buf, XZ_MAGIC, 4) == 0) /* XXX: We only have 4 bytes */
1155 return FT_XZ;
1156 else
1157 #endif
1158 #ifndef NO_LZ_SUPPORT
1159 if (memcmp(buf, LZ_MAGIC, 4) == 0)
1160 return FT_LZ;
1161 else
1162 #endif
1163 return FT_UNKNOWN;
1164 }
1165
1166 #ifndef SMALL
1167 /* check the outfile is OK. */
1168 static int
check_outfile(const char * outfile)1169 check_outfile(const char *outfile)
1170 {
1171 struct stat sb;
1172 int ok = 1;
1173
1174 if (lflag == 0 && stat(outfile, &sb) == 0) {
1175 if (fflag)
1176 unlink(outfile);
1177 else if (isatty(STDIN_FILENO)) {
1178 char ans[10] = { 'n', '\0' }; /* default */
1179
1180 fprintf(stderr, "%s already exists -- do you wish to "
1181 "overwrite (y or n)? " , outfile);
1182 (void)fgets(ans, sizeof(ans) - 1, stdin);
1183 if (ans[0] != 'y' && ans[0] != 'Y') {
1184 fprintf(stderr, "\tnot overwriting\n");
1185 ok = 0;
1186 } else
1187 unlink(outfile);
1188 } else {
1189 maybe_warnx("%s already exists -- skipping", outfile);
1190 ok = 0;
1191 }
1192 }
1193 return ok;
1194 }
1195
1196 static void
unlink_input(const char * file,const struct stat * sb)1197 unlink_input(const char *file, const struct stat *sb)
1198 {
1199 struct stat nsb;
1200
1201 if (kflag)
1202 return;
1203 if (stat(file, &nsb) != 0)
1204 /* Must be gone already */
1205 return;
1206 if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1207 /* Definitely a different file */
1208 return;
1209 unlink(file);
1210 }
1211
1212 static void
got_siginfo(int signo)1213 got_siginfo(int signo)
1214 {
1215
1216 print_info = 1;
1217 }
1218
1219 static void
setup_signals(void)1220 setup_signals(void)
1221 {
1222
1223 signal(SIGINFO, got_siginfo);
1224 }
1225
1226 static void
infile_newdata(size_t newdata)1227 infile_newdata(size_t newdata)
1228 {
1229
1230 infile_current += newdata;
1231 }
1232 #endif
1233
1234 static void
infile_set(const char * newinfile,off_t total)1235 infile_set(const char *newinfile, off_t total)
1236 {
1237
1238 if (newinfile)
1239 infile = newinfile;
1240 #ifndef SMALL
1241 infile_total = total;
1242 #endif
1243 }
1244
1245 static void
infile_clear(void)1246 infile_clear(void)
1247 {
1248
1249 infile = NULL;
1250 #ifndef SMALL
1251 infile_total = infile_current = 0;
1252 #endif
1253 }
1254
1255 static const suffixes_t *
check_suffix(char * file,int xlate)1256 check_suffix(char *file, int xlate)
1257 {
1258 const suffixes_t *s;
1259 int len = strlen(file);
1260 char *sp;
1261
1262 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1263 /* if it doesn't fit in "a.suf", don't bother */
1264 if (s->ziplen >= len)
1265 continue;
1266 sp = file + len - s->ziplen;
1267 if (strcmp(s->zipped, sp) != 0)
1268 continue;
1269 if (xlate)
1270 strcpy(sp, s->normal);
1271 return s;
1272 }
1273 return NULL;
1274 }
1275
1276 /*
1277 * compress the given file: create a corresponding .gz file and remove the
1278 * original.
1279 */
1280 static off_t
file_compress(char * file,char * outfile,size_t outsize)1281 file_compress(char *file, char *outfile, size_t outsize)
1282 {
1283 int in;
1284 int out;
1285 off_t size, in_size;
1286 #ifndef SMALL
1287 struct stat isb, osb;
1288 const suffixes_t *suff;
1289 #endif
1290
1291 in = open(file, O_RDONLY);
1292 if (in == -1) {
1293 maybe_warn("can't open %s", file);
1294 return -1;
1295 }
1296
1297 #ifndef SMALL
1298 if (fstat(in, &isb) != 0) {
1299 close(in);
1300 maybe_warn("can't stat %s", file);
1301 return -1;
1302 }
1303 infile_set(file, isb.st_size);
1304 #endif
1305
1306 if (cflag == 0) {
1307 #ifndef SMALL
1308 if (isb.st_nlink > 1 && fflag == 0) {
1309 maybe_warnx("%s has %d other link%s -- "
1310 "skipping", file, isb.st_nlink - 1,
1311 isb.st_nlink == 1 ? "" : "s");
1312 close(in);
1313 return -1;
1314 }
1315
1316 if (fflag == 0 && (suff = check_suffix(file, 0))
1317 && suff->zipped[0] != 0) {
1318 maybe_warnx("%s already has %s suffix -- unchanged",
1319 file, suff->zipped);
1320 close(in);
1321 return -1;
1322 }
1323 #endif
1324
1325 /* Add (usually) .gz to filename */
1326 if ((size_t)snprintf(outfile, outsize, "%s%s",
1327 file, suffixes[0].zipped) >= outsize)
1328 memcpy(outfile + outsize - suffixes[0].ziplen - 1,
1329 suffixes[0].zipped, suffixes[0].ziplen + 1);
1330
1331 #ifndef SMALL
1332 if (check_outfile(outfile) == 0) {
1333 close(in);
1334 return -1;
1335 }
1336 #endif
1337 }
1338
1339 if (cflag == 0) {
1340 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1341 if (out == -1) {
1342 maybe_warn("could not create output: %s", outfile);
1343 fclose(stdin);
1344 return -1;
1345 }
1346 } else
1347 out = STDOUT_FILENO;
1348
1349 in_size = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1350
1351 (void)close(in);
1352
1353 /*
1354 * If there was an error, in_size will be -1.
1355 * If we compressed to stdout, just return the size.
1356 * Otherwise stat the file and check it is the correct size.
1357 * We only blow away the file if we can stat the output and it
1358 * has the expected size.
1359 */
1360 if (cflag != 0)
1361 return in_size == -1 ? -1 : size;
1362
1363 #ifndef SMALL
1364 if (fstat(out, &osb) != 0) {
1365 maybe_warn("couldn't stat: %s", outfile);
1366 goto bad_outfile;
1367 }
1368
1369 if (osb.st_size != size) {
1370 maybe_warnx("output file: %s wrong size (%" PRIdOFF
1371 " != %" PRIdOFF "), deleting",
1372 outfile, osb.st_size, size);
1373 goto bad_outfile;
1374 }
1375
1376 copymodes(out, &isb, outfile);
1377 #endif
1378 if (close(out) == -1)
1379 maybe_warn("couldn't close output");
1380
1381 /* output is good, ok to delete input */
1382 unlink_input(file, &isb);
1383 return size;
1384
1385 #ifndef SMALL
1386 bad_outfile:
1387 if (close(out) == -1)
1388 maybe_warn("couldn't close output");
1389
1390 maybe_warnx("leaving original %s", file);
1391 unlink(outfile);
1392 return size;
1393 #endif
1394 }
1395
1396 /* uncompress the given file and remove the original */
1397 static off_t
file_uncompress(char * file,char * outfile,size_t outsize)1398 file_uncompress(char *file, char *outfile, size_t outsize)
1399 {
1400 struct stat isb, osb;
1401 off_t size;
1402 ssize_t rbytes;
1403 unsigned char fourbytes[4];
1404 enum filetype method;
1405 int fd, ofd, zfd = -1;
1406 size_t in_size;
1407 #ifndef SMALL
1408 ssize_t rv;
1409 time_t timestamp = 0;
1410 char name[PATH_MAX + 1];
1411 #endif
1412
1413 /* gather the old name info */
1414
1415 fd = open(file, O_RDONLY);
1416 if (fd < 0) {
1417 maybe_warn("can't open %s", file);
1418 goto lose;
1419 }
1420 if (fstat(fd, &isb) != 0) {
1421 close(fd);
1422 maybe_warn("can't stat %s", file);
1423 goto lose;
1424 }
1425 if (S_ISREG(isb.st_mode))
1426 in_size = isb.st_size;
1427 else
1428 in_size = 0;
1429 infile_set(file, in_size);
1430
1431 strlcpy(outfile, file, outsize);
1432 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1433 maybe_warnx("%s: unknown suffix -- ignored", file);
1434 goto lose;
1435 }
1436
1437 rbytes = read(fd, fourbytes, sizeof fourbytes);
1438 if (rbytes != sizeof fourbytes) {
1439 /* we don't want to fail here. */
1440 #ifndef SMALL
1441 if (fflag)
1442 goto lose;
1443 #endif
1444 if (rbytes == -1)
1445 maybe_warn("can't read %s", file);
1446 else
1447 goto unexpected_EOF;
1448 goto lose;
1449 }
1450 infile_newdata(rbytes);
1451
1452 method = file_gettype(fourbytes);
1453 #ifndef SMALL
1454 if (fflag == 0 && method == FT_UNKNOWN) {
1455 maybe_warnx("%s: not in gzip format", file);
1456 goto lose;
1457 }
1458
1459 #endif
1460
1461 #ifndef SMALL
1462 if (method == FT_GZIP && Nflag) {
1463 unsigned char ts[4]; /* timestamp */
1464
1465 rv = pread(fd, ts, sizeof ts, GZIP_TIMESTAMP);
1466 if (rv >= 0 && rv < (ssize_t)(sizeof ts))
1467 goto unexpected_EOF;
1468 if (rv == -1) {
1469 if (!fflag)
1470 maybe_warn("can't read %s", file);
1471 goto lose;
1472 }
1473 infile_newdata(rv);
1474 timestamp = ts[3] << 24 | ts[2] << 16 | ts[1] << 8 | ts[0];
1475
1476 if (fourbytes[3] & ORIG_NAME) {
1477 rbytes = pread(fd, name, sizeof(name) - 1, GZIP_ORIGNAME);
1478 if (rbytes < 0) {
1479 maybe_warn("can't read %s", file);
1480 goto lose;
1481 }
1482 if (name[0] != '\0') {
1483 char *dp, *nf;
1484
1485 /* Make sure that name is NUL-terminated */
1486 name[rbytes] = '\0';
1487
1488 /* strip saved directory name */
1489 nf = strrchr(name, '/');
1490 if (nf == NULL)
1491 nf = name;
1492 else
1493 nf++;
1494
1495 /* preserve original directory name */
1496 dp = strrchr(file, '/');
1497 if (dp == NULL)
1498 dp = file;
1499 else
1500 dp++;
1501 snprintf(outfile, outsize, "%.*s%.*s",
1502 (int) (dp - file),
1503 file, (int) rbytes, nf);
1504 }
1505 }
1506 }
1507 #endif
1508 lseek(fd, 0, SEEK_SET);
1509
1510 if (cflag == 0 || lflag) {
1511 #ifndef SMALL
1512 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1513 maybe_warnx("%s has %d other links -- skipping",
1514 file, isb.st_nlink - 1);
1515 goto lose;
1516 }
1517 if (nflag == 0 && timestamp)
1518 isb.st_mtime = timestamp;
1519 if (check_outfile(outfile) == 0)
1520 goto lose;
1521 #endif
1522 }
1523
1524 if (cflag)
1525 zfd = STDOUT_FILENO;
1526 else if (lflag)
1527 zfd = -1;
1528 else {
1529 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1530 if (zfd == STDOUT_FILENO) {
1531 /* We won't close STDOUT_FILENO later... */
1532 zfd = dup(zfd);
1533 close(STDOUT_FILENO);
1534 }
1535 if (zfd == -1) {
1536 maybe_warn("can't open %s", outfile);
1537 goto lose;
1538 }
1539 }
1540
1541 switch (method) {
1542 #ifndef NO_BZIP2_SUPPORT
1543 case FT_BZIP2:
1544 /* XXX */
1545 if (lflag) {
1546 maybe_warnx("no -l with bzip2 files");
1547 goto lose;
1548 }
1549
1550 size = unbzip2(fd, zfd, NULL, 0, NULL);
1551 break;
1552 #endif
1553
1554 #ifndef NO_COMPRESS_SUPPORT
1555 case FT_Z: {
1556 FILE *in, *out;
1557
1558 /* XXX */
1559 if (lflag) {
1560 maybe_warnx("no -l with Lempel-Ziv files");
1561 goto lose;
1562 }
1563
1564 if ((in = zdopen(fd)) == NULL) {
1565 maybe_warn("zdopen for read: %s", file);
1566 goto lose;
1567 }
1568
1569 out = fdopen(dup(zfd), "w");
1570 if (out == NULL) {
1571 maybe_warn("fdopen for write: %s", outfile);
1572 fclose(in);
1573 goto lose;
1574 }
1575
1576 size = zuncompress(in, out, NULL, 0, NULL);
1577 /* need to fclose() if ferror() is true... */
1578 if (ferror(in) | fclose(in)) {
1579 maybe_warn("failed infile fclose");
1580 unlink(outfile);
1581 (void)fclose(out);
1582 }
1583 if (fclose(out) != 0) {
1584 maybe_warn("failed outfile fclose");
1585 unlink(outfile);
1586 goto lose;
1587 }
1588 break;
1589 }
1590 #endif
1591
1592 #ifndef NO_PACK_SUPPORT
1593 case FT_PACK:
1594 if (lflag) {
1595 maybe_warnx("no -l with packed files");
1596 goto lose;
1597 }
1598
1599 size = unpack(fd, zfd, NULL, 0, NULL);
1600 break;
1601 #endif
1602
1603 #ifndef NO_XZ_SUPPORT
1604 case FT_XZ:
1605 if (lflag) {
1606 size = unxz_len(fd);
1607 print_list_out(in_size, size, file);
1608 return -1;
1609 }
1610 size = unxz(fd, zfd, NULL, 0, NULL);
1611 break;
1612 #endif
1613
1614 #ifndef NO_LZ_SUPPORT
1615 case FT_LZ:
1616 if (lflag) {
1617 maybe_warnx("no -l with lzip files");
1618 goto lose;
1619 }
1620 size = unlz(fd, zfd, NULL, 0, NULL);
1621 break;
1622 #endif
1623 #ifndef SMALL
1624 case FT_UNKNOWN:
1625 if (lflag) {
1626 maybe_warnx("no -l for unknown filetypes");
1627 goto lose;
1628 }
1629 size = cat_fd(NULL, 0, NULL, fd);
1630 break;
1631 #endif
1632 default:
1633 if (lflag) {
1634 print_list(fd, in_size, outfile, isb.st_mtime);
1635 close(fd);
1636 return -1; /* XXX */
1637 }
1638
1639 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1640 break;
1641 }
1642
1643 if (close(fd) != 0)
1644 maybe_warn("couldn't close input");
1645 if (zfd != STDOUT_FILENO && close(zfd) != 0)
1646 maybe_warn("couldn't close output");
1647
1648 if (size == -1) {
1649 if (cflag == 0)
1650 unlink(outfile);
1651 maybe_warnx("%s: uncompress failed", file);
1652 return -1;
1653 }
1654
1655 /* if testing, or we uncompressed to stdout, this is all we need */
1656 #ifndef SMALL
1657 if (tflag)
1658 return size;
1659 #endif
1660 /* if we are uncompressing to stdin, don't remove the file. */
1661 if (cflag)
1662 return size;
1663
1664 /*
1665 * if we create a file...
1666 */
1667 /*
1668 * if we can't stat the file don't remove the file.
1669 */
1670
1671 ofd = open(outfile, O_RDWR, 0);
1672 if (ofd == -1) {
1673 maybe_warn("couldn't open (leaving original): %s",
1674 outfile);
1675 return -1;
1676 }
1677 if (fstat(ofd, &osb) != 0) {
1678 maybe_warn("couldn't stat (leaving original): %s",
1679 outfile);
1680 close(ofd);
1681 return -1;
1682 }
1683 if (osb.st_size != size) {
1684 maybe_warnx("stat gave different size: %" PRIdOFF
1685 " != %" PRIdOFF " (leaving original)",
1686 size, osb.st_size);
1687 close(ofd);
1688 unlink(outfile);
1689 return -1;
1690 }
1691 unlink_input(file, &isb);
1692 #ifndef SMALL
1693 copymodes(ofd, &isb, outfile);
1694 #endif
1695 close(ofd);
1696 return size;
1697
1698 unexpected_EOF:
1699 maybe_warnx("%s: unexpected end of file", file);
1700 lose:
1701 if (fd != -1)
1702 close(fd);
1703 if (zfd != -1 && zfd != STDOUT_FILENO)
1704 close(fd);
1705 return -1;
1706 }
1707
1708 #ifndef SMALL
1709 static void
check_siginfo(void)1710 check_siginfo(void)
1711 {
1712 static int ttyfd = -2;
1713 char buf[2048];
1714 int n;
1715
1716 if (print_info == 0)
1717 return;
1718
1719 if (!infile)
1720 goto out;
1721
1722 if (ttyfd == -2)
1723 ttyfd = open(_PATH_TTY, O_RDWR | O_CLOEXEC);
1724
1725 if (ttyfd == -1)
1726 goto out;
1727
1728 if (infile_total) {
1729 const double pcent = (100.0 * infile_current) / infile_total;
1730
1731 n = snprintf(buf, sizeof(buf),
1732 "%s: %s: done %ju/%ju bytes (%3.2f%%)\n",
1733 getprogname(), infile, (uintmax_t)infile_current,
1734 (uintmax_t)infile_total, pcent);
1735 } else {
1736 n = snprintf(buf, sizeof(buf), "%s: %s: done %ju bytes\n",
1737 getprogname(), infile, (uintmax_t)infile_current);
1738 }
1739
1740 if (n <= 0)
1741 goto out;
1742
1743 write(ttyfd, buf, (size_t)n);
1744 out:
1745 print_info = 0;
1746 }
1747
1748 static off_t
cat_fd(unsigned char * prepend,size_t count,off_t * gsizep,int fd)1749 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd)
1750 {
1751 char buf[BUFLEN];
1752 off_t in_tot;
1753 ssize_t w;
1754
1755 in_tot = count;
1756 w = write_retry(STDOUT_FILENO, prepend, count);
1757 if (w == -1 || (size_t)w != count) {
1758 maybe_warn("write to stdout");
1759 return -1;
1760 }
1761 for (;;) {
1762 ssize_t rv;
1763
1764 rv = read(fd, buf, sizeof buf);
1765 if (rv == 0)
1766 break;
1767 if (rv < 0) {
1768 maybe_warn("read from fd %d", fd);
1769 break;
1770 }
1771 infile_newdata(rv);
1772
1773 if (write_retry(STDOUT_FILENO, buf, rv) != rv) {
1774 maybe_warn("write to stdout");
1775 break;
1776 }
1777 in_tot += rv;
1778 }
1779
1780 if (gsizep)
1781 *gsizep = in_tot;
1782 return (in_tot);
1783 }
1784 #endif
1785
1786 static void
handle_stdin(void)1787 handle_stdin(void)
1788 {
1789 struct stat isb;
1790 unsigned char fourbytes[4];
1791 size_t in_size;
1792 off_t usize, gsize;
1793 enum filetype method;
1794 ssize_t bytes_read;
1795 #ifndef NO_COMPRESS_SUPPORT
1796 FILE *in;
1797 #endif
1798
1799 #ifndef SMALL
1800 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1801 maybe_warnx("standard input is a terminal -- ignoring");
1802 goto out;
1803 }
1804 #endif
1805
1806 if (fstat(STDIN_FILENO, &isb) < 0) {
1807 maybe_warn("fstat");
1808 goto out;
1809 }
1810 if (S_ISREG(isb.st_mode))
1811 in_size = isb.st_size;
1812 else
1813 in_size = 0;
1814 infile_set("(stdin)", in_size);
1815
1816 if (lflag) {
1817 print_list(STDIN_FILENO, in_size, infile, isb.st_mtime);
1818 goto out;
1819 }
1820
1821 bytes_read = read_retry(STDIN_FILENO, fourbytes, sizeof fourbytes);
1822 if (bytes_read == -1) {
1823 maybe_warn("can't read stdin");
1824 goto out;
1825 } else if (bytes_read != sizeof(fourbytes)) {
1826 maybe_warnx("(stdin): unexpected end of file");
1827 goto out;
1828 }
1829
1830 method = file_gettype(fourbytes);
1831 switch (method) {
1832 default:
1833 #ifndef SMALL
1834 if (fflag == 0) {
1835 maybe_warnx("unknown compression format");
1836 goto out;
1837 }
1838 usize = cat_fd(fourbytes, sizeof fourbytes, &gsize, STDIN_FILENO);
1839 break;
1840 #endif
1841 case FT_GZIP:
1842 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1843 (char *)fourbytes, sizeof fourbytes, &gsize, "(stdin)");
1844 break;
1845 #ifndef NO_BZIP2_SUPPORT
1846 case FT_BZIP2:
1847 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1848 (char *)fourbytes, sizeof fourbytes, &gsize);
1849 break;
1850 #endif
1851 #ifndef NO_COMPRESS_SUPPORT
1852 case FT_Z:
1853 if ((in = zdopen(STDIN_FILENO)) == NULL) {
1854 maybe_warnx("zopen of stdin");
1855 goto out;
1856 }
1857
1858 usize = zuncompress(in, stdout, (char *)fourbytes,
1859 sizeof fourbytes, &gsize);
1860 fclose(in);
1861 break;
1862 #endif
1863 #ifndef NO_PACK_SUPPORT
1864 case FT_PACK:
1865 usize = unpack(STDIN_FILENO, STDOUT_FILENO,
1866 (char *)fourbytes, sizeof fourbytes, &gsize);
1867 break;
1868 #endif
1869 #ifndef NO_XZ_SUPPORT
1870 case FT_XZ:
1871 usize = unxz(STDIN_FILENO, STDOUT_FILENO,
1872 (char *)fourbytes, sizeof fourbytes, &gsize);
1873 break;
1874 #endif
1875 #ifndef NO_LZ_SUPPORT
1876 case FT_LZ:
1877 usize = unlz(STDIN_FILENO, STDOUT_FILENO,
1878 (char *)fourbytes, sizeof fourbytes, &gsize);
1879 break;
1880 #endif
1881 }
1882
1883 #ifndef SMALL
1884 if (vflag && !tflag && usize != -1 && gsize != -1)
1885 print_verbage(NULL, NULL, usize, gsize);
1886 if (vflag && tflag)
1887 print_test("(stdin)", usize != -1);
1888 #else
1889 (void)&usize;
1890 #endif
1891
1892 out:
1893 infile_clear();
1894 }
1895
1896 static void
handle_stdout(void)1897 handle_stdout(void)
1898 {
1899 off_t gsize;
1900 #ifndef SMALL
1901 off_t usize;
1902 struct stat sb;
1903 time_t systime;
1904 uint32_t mtime;
1905 int ret;
1906
1907 infile_set("<stdout>", 0);
1908
1909 if (fflag == 0 && isatty(STDOUT_FILENO)) {
1910 maybe_warnx("standard output is a terminal -- ignoring");
1911 return;
1912 }
1913
1914 /* If stdin is a file use its mtime, otherwise use current time */
1915 ret = fstat(STDIN_FILENO, &sb);
1916 if (ret < 0) {
1917 maybe_warn("Can't stat stdin");
1918 return;
1919 }
1920
1921 if (S_ISREG(sb.st_mode)) {
1922 infile_set("<stdout>", sb.st_size);
1923 mtime = (uint32_t)sb.st_mtime;
1924 } else {
1925 systime = time(NULL);
1926 if (systime == -1) {
1927 maybe_warn("time");
1928 return;
1929 }
1930 mtime = (uint32_t)systime;
1931 }
1932
1933 usize =
1934 #endif
1935 gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime);
1936 #ifndef SMALL
1937 if (vflag && !tflag && usize != -1 && gsize != -1)
1938 print_verbage(NULL, NULL, usize, gsize);
1939 #endif
1940 }
1941
1942 /* do what is asked for, for the path name */
1943 static void
handle_pathname(char * path)1944 handle_pathname(char *path)
1945 {
1946 char *opath = path, *s = NULL;
1947 ssize_t len;
1948 int slen;
1949 struct stat sb;
1950
1951 /* check for stdout/stdin */
1952 if (path[0] == '-' && path[1] == '\0') {
1953 if (dflag)
1954 handle_stdin();
1955 else
1956 handle_stdout();
1957 return;
1958 }
1959
1960 retry:
1961 if (stat(path, &sb) != 0) {
1962 /* lets try <path>.gz if we're decompressing */
1963 if (dflag && s == NULL && errno == ENOENT) {
1964 len = strlen(path);
1965 slen = suffixes[0].ziplen;
1966 s = malloc(len + slen + 1);
1967 if (s == NULL)
1968 maybe_err("malloc");
1969 memcpy(s, path, len);
1970 memcpy(s + len, suffixes[0].zipped, slen + 1);
1971 path = s;
1972 goto retry;
1973 }
1974 maybe_warn("can't stat: %s", opath);
1975 goto out;
1976 }
1977
1978 if (S_ISDIR(sb.st_mode)) {
1979 #ifndef SMALL
1980 if (rflag)
1981 handle_dir(path);
1982 else
1983 #endif
1984 maybe_warnx("%s is a directory", path);
1985 goto out;
1986 }
1987
1988 if (S_ISREG(sb.st_mode))
1989 handle_file(path, &sb);
1990 else
1991 maybe_warnx("%s is not a regular file", path);
1992
1993 out:
1994 if (s)
1995 free(s);
1996 }
1997
1998 /* compress/decompress a file */
1999 static void
handle_file(char * file,struct stat * sbp)2000 handle_file(char *file, struct stat *sbp)
2001 {
2002 off_t usize, gsize;
2003 char outfile[PATH_MAX];
2004
2005 infile_set(file, sbp->st_size);
2006 if (dflag) {
2007 usize = file_uncompress(file, outfile, sizeof(outfile));
2008 #ifndef SMALL
2009 if (vflag && tflag)
2010 print_test(file, usize != -1);
2011 #endif
2012 if (usize == -1)
2013 return;
2014 gsize = sbp->st_size;
2015 } else {
2016 gsize = file_compress(file, outfile, sizeof(outfile));
2017 if (gsize == -1)
2018 return;
2019 usize = sbp->st_size;
2020 }
2021 infile_clear();
2022
2023 #ifndef SMALL
2024 if (vflag && !tflag)
2025 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
2026 #endif
2027 }
2028
2029 #ifndef SMALL
2030 /* this is used with -r to recursively descend directories */
2031 static void
handle_dir(char * dir)2032 handle_dir(char *dir)
2033 {
2034 char *path_argv[2];
2035 FTS *fts;
2036 FTSENT *entry;
2037
2038 path_argv[0] = dir;
2039 path_argv[1] = 0;
2040 fts = fts_open(path_argv, FTS_PHYSICAL, NULL);
2041 if (fts == NULL) {
2042 warn("couldn't fts_open %s", dir);
2043 return;
2044 }
2045
2046 while ((entry = fts_read(fts))) {
2047 switch(entry->fts_info) {
2048 case FTS_D:
2049 case FTS_DP:
2050 continue;
2051
2052 case FTS_DNR:
2053 case FTS_ERR:
2054 case FTS_NS:
2055 maybe_warn("%s", entry->fts_path);
2056 continue;
2057 case FTS_F:
2058 handle_file(entry->fts_name, entry->fts_statp);
2059 }
2060 }
2061 (void)fts_close(fts);
2062 }
2063 #endif
2064
2065 /* print a ratio - size reduction as a fraction of uncompressed size */
2066 static void
print_ratio(off_t in,off_t out,FILE * where)2067 print_ratio(off_t in, off_t out, FILE *where)
2068 {
2069 int percent10; /* 10 * percent */
2070 off_t diff;
2071 char buff[8];
2072 int len;
2073
2074 diff = in - out/2;
2075 if (in == 0 && out == 0)
2076 percent10 = 0;
2077 else if (diff < 0)
2078 /*
2079 * Output is more than double size of input! print -99.9%
2080 * Quite possibly we've failed to get the original size.
2081 */
2082 percent10 = -999;
2083 else {
2084 /*
2085 * We only need 12 bits of result from the final division,
2086 * so reduce the values until a 32bit division will suffice.
2087 */
2088 while (in > 0x100000) {
2089 diff >>= 1;
2090 in >>= 1;
2091 }
2092 if (in != 0)
2093 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
2094 else
2095 percent10 = 0;
2096 }
2097
2098 len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
2099 /* Move the '.' to before the last digit */
2100 buff[len - 1] = buff[len - 2];
2101 buff[len - 2] = '.';
2102 fprintf(where, "%5s%%", buff);
2103 }
2104
2105 #ifndef SMALL
2106 /* print compression statistics, and the new name (if there is one!) */
2107 static void
print_verbage(const char * file,const char * nfile,off_t usize,off_t gsize)2108 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
2109 {
2110 if (file)
2111 fprintf(stderr, "%s:%s ", file,
2112 strlen(file) < 7 ? "\t\t" : "\t");
2113 print_ratio(usize, gsize, stderr);
2114 if (nfile)
2115 fprintf(stderr, " -- replaced with %s", nfile);
2116 fprintf(stderr, "\n");
2117 fflush(stderr);
2118 }
2119
2120 /* print test results */
2121 static void
print_test(const char * file,int ok)2122 print_test(const char *file, int ok)
2123 {
2124
2125 if (exit_value == 0 && ok == 0)
2126 exit_value = 1;
2127 fprintf(stderr, "%s:%s %s\n", file,
2128 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
2129 fflush(stderr);
2130 }
2131 #endif
2132
2133 /* print a file's info ala --list */
2134 /* eg:
2135 compressed uncompressed ratio uncompressed_name
2136 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
2137 */
2138 static void
print_list(int fd,off_t out,const char * outfile,time_t ts)2139 print_list(int fd, off_t out, const char *outfile, time_t ts)
2140 {
2141 static int first = 1;
2142 #ifndef SMALL
2143 static off_t in_tot, out_tot;
2144 uint32_t crc = 0;
2145 #endif
2146 off_t in = 0, rv;
2147
2148 if (first) {
2149 #ifndef SMALL
2150 if (vflag)
2151 printf("method crc date time ");
2152 #endif
2153 if (qflag == 0)
2154 printf(" compressed uncompressed "
2155 "ratio uncompressed_name\n");
2156 }
2157 first = 0;
2158
2159 /* print totals? */
2160 #ifndef SMALL
2161 if (fd == -1) {
2162 in = in_tot;
2163 out = out_tot;
2164 } else
2165 #endif
2166 {
2167 /* read the last 4 bytes - this is the uncompressed size */
2168 rv = lseek(fd, (off_t)(-8), SEEK_END);
2169 if (rv != -1) {
2170 unsigned char buf[8];
2171 uint32_t usize;
2172
2173 rv = read(fd, (char *)buf, sizeof(buf));
2174 if (rv == -1)
2175 maybe_warn("read of uncompressed size");
2176 else if (rv != sizeof(buf))
2177 maybe_warnx("read of uncompressed size");
2178
2179 else {
2180 usize = buf[4];
2181 usize |= (unsigned int)buf[5] << 8;
2182 usize |= (unsigned int)buf[6] << 16;
2183 usize |= (unsigned int)buf[7] << 24;
2184 in = (off_t)usize;
2185 #ifndef SMALL
2186 crc = buf[0];
2187 crc |= (unsigned int)buf[1] << 8;
2188 crc |= (unsigned int)buf[2] << 16;
2189 crc |= (unsigned int)buf[3] << 24;
2190 #endif
2191 }
2192 }
2193 }
2194
2195 #ifndef SMALL
2196 if (vflag && fd == -1)
2197 printf(" ");
2198 else if (vflag) {
2199 char *date = ctime(&ts);
2200
2201 /* skip the day, 1/100th second, and year */
2202 date += 4;
2203 date[12] = 0;
2204 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
2205 }
2206 in_tot += in;
2207 out_tot += out;
2208 #endif
2209 print_list_out(out, in, outfile);
2210 }
2211
2212 static void
print_list_out(off_t out,off_t in,const char * outfile)2213 print_list_out(off_t out, off_t in, const char *outfile)
2214 {
2215 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
2216 print_ratio(in, out, stdout);
2217 printf(" %s\n", outfile);
2218 }
2219
2220 /* display the usage of NetBSD gzip */
2221 static void
usage(void)2222 usage(void)
2223 {
2224
2225 fprintf(stderr, "%s\n", gzip_version);
2226 fprintf(stderr,
2227 "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n"
2228 #ifndef SMALL
2229 " -1 --fast fastest (worst) compression\n"
2230 " -2 .. -8 set compression level\n"
2231 " -9 --best best (slowest) compression\n"
2232 " -c --stdout write to stdout, keep original files\n"
2233 " --to-stdout\n"
2234 " -d --decompress uncompress files\n"
2235 " --uncompress\n"
2236 " -f --force force overwriting & compress links\n"
2237 " -h --help display this help\n"
2238 " -k --keep don't delete input files during operation\n"
2239 " -l --list list compressed file contents\n"
2240 " -N --name save or restore original file name and time stamp\n"
2241 " -n --no-name don't save original file name or time stamp\n"
2242 " -q --quiet output no warnings\n"
2243 " -r --recursive recursively compress files in directories\n"
2244 " -S .suf use suffix .suf instead of .gz\n"
2245 " --suffix .suf\n"
2246 " -t --test test compressed file\n"
2247 " -V --version display program version\n"
2248 " -v --verbose print extra statistics\n",
2249 #else
2250 ,
2251 #endif
2252 getprogname());
2253 exit(0);
2254 }
2255
2256 /* display the version of NetBSD gzip */
2257 static void
display_version(void)2258 display_version(void)
2259 {
2260
2261 fprintf(stderr, "%s\n", gzip_version);
2262 exit(0);
2263 }
2264
2265 #ifndef NO_BZIP2_SUPPORT
2266 #include "unbzip2.c"
2267 #endif
2268 #ifndef NO_COMPRESS_SUPPORT
2269 #include "zuncompress.c"
2270 #endif
2271 #ifndef NO_PACK_SUPPORT
2272 #include "unpack.c"
2273 #endif
2274 #ifndef NO_XZ_SUPPORT
2275 #include "unxz.c"
2276 #endif
2277 #ifndef NO_LZ_SUPPORT
2278 #include "unlz.c"
2279 #endif
2280
2281 static ssize_t
read_retry(int fd,void * buf,size_t sz)2282 read_retry(int fd, void *buf, size_t sz)
2283 {
2284 char *cp = buf;
2285 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2286
2287 while (left > 0) {
2288 ssize_t ret;
2289
2290 ret = read(fd, cp, left);
2291 if (ret == -1) {
2292 return ret;
2293 } else if (ret == 0) {
2294 break; /* EOF */
2295 }
2296 cp += ret;
2297 left -= ret;
2298 }
2299
2300 return sz - left;
2301 }
2302
2303 static ssize_t
write_retry(int fd,const void * buf,size_t sz)2304 write_retry(int fd, const void *buf, size_t sz)
2305 {
2306 const char *cp = buf;
2307 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2308
2309 while (left > 0) {
2310 ssize_t ret;
2311
2312 ret = write(fd, cp, left);
2313 if (ret == -1) {
2314 return ret;
2315 } else if (ret == 0) {
2316 abort(); /* Can't happen */
2317 }
2318 cp += ret;
2319 left -= ret;
2320 }
2321
2322 return sz - left;
2323 }
2324