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#define FORCE_FLAGS
57#define FOR_gzip
58#include "toys.h"
59
60GLOBALS(
61 int level;
62)
63
64
65#if CFG_TOYBOX_LIBZ
66#include <zlib.h>
67
68
69static int do_deflate(int in_fd, int out_fd, int dd, int level)
70{
71 int len, err = 0;
72 char *b = "r";
73 gzFile gz;
74
75 if (!dd) {
76 sprintf(b = toybuf, "w%d", level);
77 if (out_fd == 1) out_fd = xdup(out_fd);
78 }
79 if (!(gz = gzdopen(dd ? in_fd : out_fd, b))) perror_exit("gzdopen");
80 if (dd) {
81 if (gzdirect(gz)) error_exit("not gzip");
82 while ((len = gzread(gz, toybuf, sizeof(toybuf))) > 0)
83 if (len != writeall(out_fd, toybuf, len)) break;
84 } else {
85 while ((len = read(in_fd, toybuf, sizeof(toybuf))) > 0)
86 if (len != gzwrite(gz, toybuf, len)) break;
87 }
88
89 err = !!len;
90 if (len>0 || err == Z_ERRNO) perror_msg(dd ? "write" : "read");
91 if (len<0)
92 error_msg("%s%s: %s", "gz", dd ? "read" : "write", gzerror(gz, &len));
93
94 if (gzclose(gz) != Z_OK) perror_msg("gzclose"), err++;
95
96 return err;
97}
98
99
100#else
101
102
103static int do_deflate(int in_fd, int out_fd, int dd, int level)
104{
105 int x;
106
107 if (dd) WOULD_EXIT(x, gunzip_fd(in_fd, out_fd));
108 else WOULD_EXIT(x, gzip_fd(in_fd, out_fd));
109
110 return x;
111}
112
113#endif
114
115static void do_gzip(int ifd, char *in)
116{
117 struct stat sb;
118 char *out = 0;
119 int ofd = 0;
120
121
122 if (!ifd || FLAG(c)) ofd = 1;
123 if (isatty(ifd)) {
124 if (!FLAG(f)) return error_msg("%s:need -f to read TTY"+3*!!ifd, in);
125 else ofd = 1;
126 }
127
128
129 if (!ofd) {
130 if (fstat(ifd, &sb)) return perror_msg("%s", in);
131
132
133 if (!FLAG(d)) out = xmprintf("%s%s", in, ".gz");
134 else if ((out = strend(in, ".gz"))>in) out = xstrndup(in, out-in);
135 else return error_msg("no .gz: %s", in);
136
137 ofd = xcreate(out, O_CREAT|O_WRONLY|WARN_ONLY|(O_EXCL*!FLAG(f)),sb.st_mode);
138 if (ofd == -1) return;
139 }
140
141 if (do_deflate(ifd, ofd, FLAG(d), TT.level)) in = out;
142
143 if (out) {
144 struct timespec times[] = {sb.st_atim, sb.st_mtim};
145
146 if (utimensat(AT_FDCWD, out, times, 0)) perror_exit("utimensat");
147 if (chmod(out, sb.st_mode)) perror_exit("chmod");
148 close(ofd);
149 if (!FLAG(k) && in && unlink(in)) perror_msg("unlink %s", in);
150 free(out);
151 }
152}
153
154void gzip_main(void)
155{
156
157 for (TT.level = 0; TT.level<9; TT.level++)
158 if ((toys.optflags>>TT.level)&1) break;
159 if (!(TT.level = 9-TT.level)) TT.level = 6;
160
161 loopfiles(toys.optargs, do_gzip);
162}
163
164void gunzip_main(void)
165{
166 toys.optflags |= FLAG_d;
167 gzip_main();
168}
169
170void zcat_main(void)
171{
172 toys.optflags |= (FLAG_c|FLAG_d);
173 gzip_main();
174}
175