xref: /freebsd/bin/pax/pax.c (revision 5b31cc94b10d4bb7109c6b27940a0fc76a44a331)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1992 Keith Muller.
5  * Copyright (c) 1992, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Keith Muller of the University of California, San Diego.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #if 0
37 #ifndef lint
38 static char const copyright[] =
39 "@(#) Copyright (c) 1992, 1993\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #endif
44 #include <sys/cdefs.h>
45 #include <sys/types.h>
46 #include <sys/stat.h>
47 #include <sys/time.h>
48 #include <sys/resource.h>
49 #include <err.h>
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <locale.h>
53 #include <paths.h>
54 #include <signal.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include "pax.h"
59 #include "extern.h"
60 static int gen_init(void);
61 
62 /*
63  * PAX main routines, general globals and some simple start up routines
64  */
65 
66 /*
67  * Variables that can be accessed by any routine within pax
68  */
69 int	act = DEFOP;		/* read/write/append/copy */
70 FSUB	*frmt = NULL;		/* archive format type */
71 int	cflag;			/* match all EXCEPT pattern/file */
72 int	cwdfd;			/* starting cwd */
73 int	dflag;			/* directory member match only  */
74 int	iflag;			/* interactive file/archive rename */
75 int	kflag;			/* do not overwrite existing files */
76 int	lflag;			/* use hard links when possible */
77 int	nflag;			/* select first archive member match */
78 int	tflag;			/* restore access time after read */
79 int	uflag;			/* ignore older modification time files */
80 int	vflag;			/* produce verbose output */
81 int	Dflag;			/* same as uflag except inode change time */
82 int	Hflag;			/* follow command line symlinks (write only) */
83 int	Lflag;			/* follow symlinks when writing */
84 int	Oflag;			/* limit to single volume */
85 int	Xflag;			/* archive files with same device id only */
86 int	Yflag;			/* same as Dflg except after name mode */
87 int	Zflag;			/* same as uflg except after name mode */
88 int	vfpart;			/* is partial verbose output in progress */
89 int	patime = 1;		/* preserve file access time */
90 int	pmtime = 1;		/* preserve file modification times */
91 int	nodirs;			/* do not create directories as needed */
92 int	pmode;			/* preserve file mode bits */
93 int	pids;			/* preserve file uid/gid */
94 int	rmleadslash = 0;	/* remove leading '/' from pathnames */
95 int	exit_val;		/* exit value */
96 int	docrc;			/* check/create file crc */
97 char	*dirptr;		/* destination dir in a copy */
98 const	char *argv0;		/* root of argv[0] */
99 sigset_t s_mask;		/* signal mask for cleanup critical sect */
100 FILE	*listf;			/* file pointer to print file list to */
101 char	*tempfile;		/* tempfile to use for mkstemp(3) */
102 char	*tempbase;		/* basename of tempfile to use for mkstemp(3) */
103 
104 /*
105  *	PAX - Portable Archive Interchange
106  *
107  *	A utility to read, write, and write lists of the members of archive
108  *	files and copy directory hierarchies. A variety of archive formats
109  *	are supported (some are described in POSIX 1003.1 10.1):
110  *
111  *		ustar - 10.1.1 extended tar interchange format
112  *		cpio  - 10.1.2 extended cpio interchange format
113  *		tar - old BSD 4.3 tar format
114  *		binary cpio - old cpio with binary header format
115  *		sysVR4 cpio -  with and without CRC
116  *
117  * This version is a superset of IEEE Std 1003.2b-d3
118  *
119  * Summary of Extensions to the IEEE Standard:
120  *
121  * 1	READ ENHANCEMENTS
122  * 1.1	Operations which read archives will continue to operate even when
123  *	processing archives which may be damaged, truncated, or fail to meet
124  *	format specs in several different ways. Damaged sections of archives
125  *	are detected and avoided if possible. Attempts will be made to resync
126  *	archive read operations even with badly damaged media.
127  * 1.2	Blocksize requirements are not strictly enforced on archive read.
128  *	Tapes which have variable sized records can be read without errors.
129  * 1.3	The user can specify via the non-standard option flag -E if error
130  *	resync operation should stop on a media error, try a specified number
131  *	of times to correct, or try to correct forever.
132  * 1.4	Sparse files (lseek holes) stored on the archive (but stored with blocks
133  *	of all zeros will be restored with holes appropriate for the target
134  *	file system
135  * 1.5	The user is notified whenever something is found during archive
136  *	read operations which violates spec (but the read will continue).
137  * 1.6	Multiple archive volumes can be read and may span over different
138  *	archive devices
139  * 1.7	Rigidly restores all file attributes exactly as they are stored on the
140  *	archive.
141  * 1.8	Modification change time ranges can be specified via multiple -T
142  *	options. These allow a user to select files whose modification time
143  *	lies within a specific time range.
144  * 1.9	Files can be selected based on owner (user name or uid) via one or more
145  *	-U options.
146  * 1.10	Files can be selected based on group (group name or gid) via one o
147  *	more -G options.
148  * 1.11	File modification time can be checked against existing file after
149  *	name modification (-Z)
150  *
151  * 2	WRITE ENHANCEMENTS
152  * 2.1	Write operation will stop instead of allowing a user to create a flawed
153  *	flawed archive (due to any problem).
154  * 2.2	Archives written by pax are forced to strictly conform to both the
155  *	archive and pax the specific format specifications.
156  * 2.3	Blocking size and format is rigidly enforced on writes.
157  * 2.4	Formats which may exhibit header overflow problems (they have fields
158  *	too small for large file systems, such as inode number storage), use
159  *	routines designed to repair this problem. These techniques still
160  *	conform to both pax and format specifications, but no longer truncate
161  *	these fields. This removes any restrictions on using these archive
162  *	formats on large file systems.
163  * 2.5	Multiple archive volumes can be written and may span over different
164  *	archive devices
165  * 2.6	A archive volume record limit allows the user to specify the number
166  *	of bytes stored on an archive volume. When reached the user is
167  *	prompted for the next archive volume. This is specified with the
168  *	non-standard -B flag. The limit is rounded up to the next blocksize.
169  * 2.7	All archive padding during write use zero filled sections. This makes
170  *	it much easier to pull data out of flawed archive during read
171  *	operations.
172  * 2.8	Access time reset with the -t applies to all file nodes (including
173  *	directories).
174  * 2.9	Symbolic links can be followed with -L (optional in the spec).
175  * 2.10	Modification or inode change time ranges can be specified via
176  *	multiple -T options. These allow a user to select files whose
177  *	modification or inode change time lies within a specific time range.
178  * 2.11	Files can be selected based on owner (user name or uid) via one or more
179  *	-U options.
180  * 2.12	Files can be selected based on group (group name or gid) via one o
181  *	more -G options.
182  * 2.13	Symlinks which appear on the command line can be followed (without
183  *	following other symlinks; -H flag)
184  *
185  * 3	COPY ENHANCEMENTS
186  * 3.1	Sparse files (lseek holes) can be copied without expanding the holes
187  *	into zero filled blocks. The file copy is created with holes which are
188  *	appropriate for the target file system
189  * 3.2	Access time as well as modification time on copied file trees can be
190  *	preserved with the appropriate -p options.
191  * 3.3	Access time reset with the -t applies to all file nodes (including
192  *	directories).
193  * 3.4	Symbolic links can be followed with -L (optional in the spec).
194  * 3.5	Modification or inode change time ranges can be specified via
195  *	multiple -T options. These allow a user to select files whose
196  *	modification or inode change time lies within a specific time range.
197  * 3.6	Files can be selected based on owner (user name or uid) via one or more
198  *	-U options.
199  * 3.7	Files can be selected based on group (group name or gid) via one o
200  *	more -G options.
201  * 3.8	Symlinks which appear on the command line can be followed (without
202  *	following other symlinks; -H flag)
203  * 3.9  File inode change time can be checked against existing file before
204  *	name modification (-D)
205  * 3.10 File inode change time can be checked against existing file after
206  *	name modification (-Y)
207  * 3.11	File modification time can be checked against existing file after
208  *	name modification (-Z)
209  *
210  * 4	GENERAL ENHANCEMENTS
211  * 4.1	Internal structure is designed to isolate format dependent and
212  *	independent functions. Formats are selected via a format driver table.
213  *	This encourages the addition of new archive formats by only having to
214  *	write those routines which id, read and write the archive header.
215  */
216 
217 /*
218  * main()
219  *	parse options, set up and operate as specified by the user.
220  *	any operational flaw will set exit_val to non-zero
221  * Return: 0 if ok, 1 otherwise
222  */
223 
224 int
225 main(int argc, char *argv[])
226 {
227 	const char *tmpdir;
228 	size_t tdlen;
229 
230 	(void) setlocale(LC_ALL, "");
231 	listf = stderr;
232 	/*
233 	 * Keep a reference to cwd, so we can always come back home.
234 	 */
235 	cwdfd = open(".", O_RDONLY | O_CLOEXEC);
236 	if (cwdfd < 0) {
237 		syswarn(0, errno, "Can't open current working directory.");
238 		return(exit_val);
239 	}
240 
241 	/*
242 	 * Where should we put temporary files?
243 	 */
244 	if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
245 		tmpdir = _PATH_TMP;
246 	tdlen = strlen(tmpdir);
247 	while (tdlen > 0 && tmpdir[tdlen - 1] == '/')
248 		tdlen--;
249 	tempfile = malloc(tdlen + 1 + sizeof(_TFILE_BASE));
250 	if (tempfile == NULL) {
251 		paxwarn(1, "Cannot allocate memory for temp file name.");
252 		return(exit_val);
253 	}
254 	if (tdlen)
255 		memcpy(tempfile, tmpdir, tdlen);
256 	tempbase = tempfile + tdlen;
257 	*tempbase++ = '/';
258 
259 	/*
260 	 * parse options, determine operational mode, general init
261 	 */
262 	options(argc, argv);
263 	if ((gen_init() < 0) || (tty_init() < 0))
264 		return(exit_val);
265 
266 	/*
267 	 * select a primary operation mode
268 	 */
269 	switch (act) {
270 	case EXTRACT:
271 		extract();
272 		break;
273 	case ARCHIVE:
274 		archive();
275 		break;
276 	case APPND:
277 		if (gzip_program != NULL)
278 			err(1, "can not gzip while appending");
279 		append();
280 		break;
281 	case COPY:
282 		copy();
283 		break;
284 	default:
285 	case LIST:
286 		list();
287 		break;
288 	}
289 	return(exit_val);
290 }
291 
292 /*
293  * sig_cleanup()
294  *	when interrupted we try to do whatever delayed processing we can.
295  *	This is not critical, but we really ought to limit our damage when we
296  *	are aborted by the user.
297  * Return:
298  *	never....
299  */
300 
301 void
302 sig_cleanup(int which_sig)
303 {
304 	/*
305 	 * restore modes and times for any dirs we may have created
306 	 * or any dirs we may have read. Set vflag and vfpart so the user
307 	 * will clearly see the message on a line by itself.
308 	 */
309 	vflag = vfpart = 1;
310 	if (which_sig == SIGXCPU)
311 		paxwarn(0, "Cpu time limit reached, cleaning up.");
312 	else
313 		paxwarn(0, "Signal caught, cleaning up.");
314 
315 	ar_close();
316 	proc_dir();
317 	if (tflag)
318 		atdir_end();
319 	exit(1);
320 }
321 
322 /*
323  * setup_sig()
324  *	set a signal to be caught, but only if it isn't being ignored already
325  */
326 
327 static int
328 setup_sig(int sig, const struct sigaction *n_hand)
329 {
330 	struct sigaction o_hand;
331 
332 	if (sigaction(sig, NULL, &o_hand) < 0)
333 		return (-1);
334 
335 	if (o_hand.sa_handler == SIG_IGN)
336 		return (0);
337 
338 	return (sigaction(sig, n_hand, NULL));
339 }
340 
341 /*
342  * gen_init()
343  *	general setup routines. Not all are required, but they really help
344  *	when dealing with a medium to large sized archives.
345  */
346 
347 static int
348 gen_init(void)
349 {
350 	struct rlimit reslimit;
351 	struct sigaction n_hand;
352 
353 	/*
354 	 * Really needed to handle large archives. We can run out of memory for
355 	 * internal tables really fast when we have a whole lot of files...
356 	 */
357 	if (getrlimit(RLIMIT_DATA , &reslimit) == 0){
358 		reslimit.rlim_cur = reslimit.rlim_max;
359 		(void)setrlimit(RLIMIT_DATA , &reslimit);
360 	}
361 
362 	/*
363 	 * should file size limits be waived? if the os limits us, this is
364 	 * needed if we want to write a large archive
365 	 */
366 	if (getrlimit(RLIMIT_FSIZE , &reslimit) == 0){
367 		reslimit.rlim_cur = reslimit.rlim_max;
368 		(void)setrlimit(RLIMIT_FSIZE , &reslimit);
369 	}
370 
371 	/*
372 	 * increase the size the stack can grow to
373 	 */
374 	if (getrlimit(RLIMIT_STACK , &reslimit) == 0){
375 		reslimit.rlim_cur = reslimit.rlim_max;
376 		(void)setrlimit(RLIMIT_STACK , &reslimit);
377 	}
378 
379 	/*
380 	 * not really needed, but doesn't hurt
381 	 */
382 	if (getrlimit(RLIMIT_RSS , &reslimit) == 0){
383 		reslimit.rlim_cur = reslimit.rlim_max;
384 		(void)setrlimit(RLIMIT_RSS , &reslimit);
385 	}
386 
387 	/*
388 	 * signal handling to reset stored directory times and modes. Since
389 	 * we deal with broken pipes via failed writes we ignore it. We also
390 	 * deal with any file size limit through failed writes. Cpu time
391 	 * limits are caught and a cleanup is forced.
392 	 */
393 	if ((sigemptyset(&s_mask) < 0) || (sigaddset(&s_mask, SIGTERM) < 0) ||
394 	    (sigaddset(&s_mask,SIGINT) < 0)||(sigaddset(&s_mask,SIGHUP) < 0) ||
395 	    (sigaddset(&s_mask,SIGPIPE) < 0)||(sigaddset(&s_mask,SIGQUIT)<0) ||
396 	    (sigaddset(&s_mask,SIGXCPU) < 0)||(sigaddset(&s_mask,SIGXFSZ)<0)) {
397 		paxwarn(1, "Unable to set up signal mask");
398 		return(-1);
399 	}
400 	memset(&n_hand, 0, sizeof n_hand);
401 	n_hand.sa_mask = s_mask;
402 	n_hand.sa_flags = 0;
403 	n_hand.sa_handler = sig_cleanup;
404 
405 	if (setup_sig(SIGHUP,  &n_hand) ||
406 	   setup_sig(SIGTERM, &n_hand) ||
407 	   setup_sig(SIGINT,  &n_hand) ||
408 	   setup_sig(SIGQUIT, &n_hand) ||
409 	   setup_sig(SIGXCPU, &n_hand))
410 		goto out;
411 
412 	n_hand.sa_handler = SIG_IGN;
413 	if ((sigaction(SIGPIPE, &n_hand, NULL) < 0) ||
414 	    (sigaction(SIGXFSZ, &n_hand, NULL) < 0))
415 		goto out;
416 	return(0);
417 
418     out:
419 	syswarn(1, errno, "Unable to set up signal handler");
420 	return(-1);
421 }
422