1 /* truncate -- truncate or extend the length of files.
2    Copyright (C) 2008-2023 Free Software Foundation, Inc.
3 
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8 
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
16 
17 /* Written by Pádraig Brady
18 
19    This is backwards compatible with the FreeBSD utility, but is more
20    flexible wrt the size specifications and the use of long options,
21    to better fit the "GNU" environment.  */
22 
23 #include <config.h>             /* sets _FILE_OFFSET_BITS=64 etc. */
24 #include <stdckdint.h>
25 #include <stdio.h>
26 #include <getopt.h>
27 #include <sys/types.h>
28 
29 #include "system.h"
30 #include "quote.h"
31 #include "stat-size.h"
32 #include "xdectoint.h"
33 
34 /* The official name of this program (e.g., no 'g' prefix).  */
35 #define PROGRAM_NAME "truncate"
36 
37 #define AUTHORS proper_name_lite ("Padraig Brady", "P\303\241draig Brady")
38 
39 /* (-c) If true, don't create if not already there */
40 static bool no_create;
41 
42 /* (-o) If true, --size refers to blocks not bytes */
43 static bool block_mode;
44 
45 /* (-r) Reference file to use size from */
46 static char const *ref_file;
47 
48 static struct option const longopts[] =
49 {
50   {"no-create", no_argument, nullptr, 'c'},
51   {"io-blocks", no_argument, nullptr, 'o'},
52   {"reference", required_argument, nullptr, 'r'},
53   {"size", required_argument, nullptr, 's'},
54   {GETOPT_HELP_OPTION_DECL},
55   {GETOPT_VERSION_OPTION_DECL},
56   {nullptr, 0, nullptr, 0}
57 };
58 
59 typedef enum
60 { rm_abs = 0, rm_rel, rm_min, rm_max, rm_rdn, rm_rup } rel_mode_t;
61 
62 void
usage(int status)63 usage (int status)
64 {
65   if (status != EXIT_SUCCESS)
66     emit_try_help ();
67   else
68     {
69       printf (_("Usage: %s OPTION... FILE...\n"), program_name);
70       fputs (_("\
71 Shrink or extend the size of each FILE to the specified size\n\
72 \n\
73 A FILE argument that does not exist is created.\n\
74 \n\
75 If a FILE is larger than the specified size, the extra data is lost.\n\
76 If a FILE is shorter, it is extended and the sparse extended part (hole)\n\
77 reads as zero bytes.\n\
78 "), stdout);
79 
80       emit_mandatory_arg_note ();
81 
82       fputs (_("\
83   -c, --no-create        do not create any files\n\
84 "), stdout);
85       fputs (_("\
86   -o, --io-blocks        treat SIZE as number of IO blocks instead of bytes\n\
87 "), stdout);
88       fputs (_("\
89   -r, --reference=RFILE  base size on RFILE\n\
90   -s, --size=SIZE        set or adjust the file size by SIZE bytes\n"), stdout);
91       fputs (HELP_OPTION_DESCRIPTION, stdout);
92       fputs (VERSION_OPTION_DESCRIPTION, stdout);
93       emit_size_note ();
94       fputs (_("\n\
95 SIZE may also be prefixed by one of the following modifying characters:\n\
96 '+' extend by, '-' reduce by, '<' at most, '>' at least,\n\
97 '/' round down to multiple of, '%' round up to multiple of.\n"), stdout);
98       emit_ancillary_info (PROGRAM_NAME);
99     }
100   exit (status);
101 }
102 
103 /* return true on success, false on error.  */
104 static bool
do_ftruncate(int fd,char const * fname,off_t ssize,off_t rsize,rel_mode_t rel_mode)105 do_ftruncate (int fd, char const *fname, off_t ssize, off_t rsize,
106               rel_mode_t rel_mode)
107 {
108   struct stat sb;
109   off_t nsize;
110 
111   if ((block_mode || (rel_mode && rsize < 0)) && fstat (fd, &sb) != 0)
112     {
113       error (0, errno, _("cannot fstat %s"), quoteaf (fname));
114       return false;
115     }
116   if (block_mode)
117     {
118       ptrdiff_t blksize = STP_BLKSIZE (&sb);
119       intmax_t ssize0 = ssize;
120       if (ckd_mul (&ssize, ssize, blksize))
121         {
122           error (0, 0,
123                  _("overflow in %jd * %td byte blocks for file %s"),
124                  ssize0, blksize, quoteaf (fname));
125           return false;
126         }
127     }
128   if (rel_mode)
129     {
130       off_t fsize;
131 
132       if (0 <= rsize)
133         fsize = rsize;
134       else
135         {
136           if (usable_st_size (&sb))
137             {
138               fsize = sb.st_size;
139               if (fsize < 0)
140                 {
141                   /* Sanity check.  Overflow is the only reason I can think
142                      this would ever go negative. */
143                   error (0, 0, _("%s has unusable, apparently negative size"),
144                          quoteaf (fname));
145                   return false;
146                 }
147             }
148           else
149             {
150               fsize = lseek (fd, 0, SEEK_END);
151               if (fsize < 0)
152                 {
153                   error (0, errno, _("cannot get the size of %s"),
154                          quoteaf (fname));
155                   return false;
156                 }
157             }
158         }
159 
160       if (rel_mode == rm_min)
161         nsize = MAX (fsize, ssize);
162       else if (rel_mode == rm_max)
163         nsize = MIN (fsize, ssize);
164       else if (rel_mode == rm_rdn)
165         /* 0..ssize-1 -> 0 */
166         nsize = fsize - fsize % ssize;
167       else
168         {
169           if (rel_mode == rm_rup)
170             {
171               /* 1..ssize -> ssize */
172               off_t r = fsize % ssize;
173               ssize = r == 0 ? 0 : ssize - r;
174             }
175           if (ckd_add (&nsize, fsize, ssize))
176             {
177               error (0, 0, _("overflow extending size of file %s"),
178                      quoteaf (fname));
179               return false;
180             }
181         }
182     }
183   else
184     nsize = ssize;
185   if (nsize < 0)
186     nsize = 0;
187 
188   if (ftruncate (fd, nsize) != 0)
189     {
190       error (0, errno, _("failed to truncate %s at %jd bytes"),
191              quoteaf (fname), (intmax_t) nsize);
192       return false;
193     }
194 
195   return true;
196 }
197 
198 int
main(int argc,char ** argv)199 main (int argc, char **argv)
200 {
201   bool got_size = false;
202   off_t size IF_LINT ( = 0);
203   off_t rsize = -1;
204   rel_mode_t rel_mode = rm_abs;
205   int c;
206 
207   initialize_main (&argc, &argv);
208   set_program_name (argv[0]);
209   setlocale (LC_ALL, "");
210   bindtextdomain (PACKAGE, LOCALEDIR);
211   textdomain (PACKAGE);
212 
213   atexit (close_stdout);
214 
215   while ((c = getopt_long (argc, argv, "cor:s:", longopts, nullptr)) != -1)
216     {
217       switch (c)
218         {
219         case 'c':
220           no_create = true;
221           break;
222 
223         case 'o':
224           block_mode = true;
225           break;
226 
227         case 'r':
228           ref_file = optarg;
229           break;
230 
231         case 's':
232           /* skip any whitespace */
233           while (isspace (to_uchar (*optarg)))
234             optarg++;
235           switch (*optarg)
236             {
237             case '<':
238               rel_mode = rm_max;
239               optarg++;
240               break;
241             case '>':
242               rel_mode = rm_min;
243               optarg++;
244               break;
245             case '/':
246               rel_mode = rm_rdn;
247               optarg++;
248               break;
249             case '%':
250               rel_mode = rm_rup;
251               optarg++;
252               break;
253             }
254           /* skip any whitespace */
255           while (isspace (to_uchar (*optarg)))
256             optarg++;
257           if (*optarg == '+' || *optarg == '-')
258             {
259               if (rel_mode)
260                 {
261                   error (0, 0, _("multiple relative modifiers specified"));
262                   /* Note other combinations are flagged as invalid numbers */
263                   usage (EXIT_FAILURE);
264                 }
265               rel_mode = rm_rel;
266             }
267           /* Support dd BLOCK size suffixes + lowercase g,t,m for bsd compat.
268              Note we don't support dd's b=512, c=1, w=2 or 21x512MiB formats. */
269           size = xdectoimax (optarg, OFF_T_MIN, OFF_T_MAX, "EgGkKmMPQRtTYZ0",
270                              _("Invalid number"), 0);
271           /* Rounding to multiple of 0 is nonsensical */
272           if ((rel_mode == rm_rup || rel_mode == rm_rdn) && size == 0)
273             error (EXIT_FAILURE, 0, _("division by zero"));
274           got_size = true;
275           break;
276 
277         case_GETOPT_HELP_CHAR;
278 
279         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
280 
281         default:
282           usage (EXIT_FAILURE);
283         }
284     }
285 
286   argv += optind;
287   argc -= optind;
288 
289   /* must specify either size or reference file */
290   if (!ref_file && !got_size)
291     {
292       error (0, 0, _("you must specify either %s or %s"),
293              quote_n (0, "--size"), quote_n (1, "--reference"));
294       usage (EXIT_FAILURE);
295     }
296   /* must specify a relative size with a reference file */
297   if (ref_file && got_size && !rel_mode)
298     {
299       error (0, 0, _("you must specify a relative %s with %s"),
300              quote_n (0, "--size"), quote_n (1, "--reference"));
301       usage (EXIT_FAILURE);
302     }
303   /* block_mode without size is not valid */
304   if (block_mode && !got_size)
305     {
306       error (0, 0, _("%s was specified but %s was not"),
307              quote_n (0, "--io-blocks"), quote_n (1, "--size"));
308       usage (EXIT_FAILURE);
309     }
310   /* must specify at least 1 file */
311   if (argc < 1)
312     {
313       error (0, 0, _("missing file operand"));
314       usage (EXIT_FAILURE);
315     }
316 
317   if (ref_file)
318     {
319       struct stat sb;
320       off_t file_size = -1;
321       if (stat (ref_file, &sb) != 0)
322         error (EXIT_FAILURE, errno, _("cannot stat %s"), quoteaf (ref_file));
323       if (usable_st_size (&sb))
324         file_size = sb.st_size;
325       else
326         {
327           int ref_fd = open (ref_file, O_RDONLY);
328           if (0 <= ref_fd)
329             {
330               off_t file_end = lseek (ref_fd, 0, SEEK_END);
331               int saved_errno = errno;
332               close (ref_fd); /* ignore failure */
333               if (0 <= file_end)
334                 file_size = file_end;
335               else
336                 {
337                   /* restore, in case close clobbered it. */
338                   errno = saved_errno;
339                 }
340             }
341         }
342       if (file_size < 0)
343         error (EXIT_FAILURE, errno, _("cannot get the size of %s"),
344                quoteaf (ref_file));
345       if (!got_size)
346         size = file_size;
347       else
348         rsize = file_size;
349     }
350 
351   int oflags = O_WRONLY | (no_create ? 0 : O_CREAT) | O_NONBLOCK;
352   bool errors = false;
353 
354   for (char const *fname; (fname = *argv); argv++)
355     {
356       int fd = open (fname, oflags, MODE_RW_UGO);
357       if (fd < 0)
358         {
359           /* 'truncate -s0 -c no-such-file'  shouldn't gen error
360              'truncate -s0 no-such-dir/file' should gen ENOENT error
361              'truncate -s0 no-such-dir/' should gen EISDIR error
362              'truncate -s0 .' should gen EISDIR error */
363           if (!(no_create && errno == ENOENT))
364             {
365               error (0, errno, _("cannot open %s for writing"),
366                      quoteaf (fname));
367               errors = true;
368             }
369         }
370       else
371         {
372           errors |= !do_ftruncate (fd, fname, size, rsize, rel_mode);
373           if (close (fd) != 0)
374             {
375               error (0, errno, _("failed to close %s"), quoteaf (fname));
376               errors = true;
377             }
378         }
379     }
380 
381   return errors ? EXIT_FAILURE : EXIT_SUCCESS;
382 }
383