xref: /netbsd-src/bin/pax/pax.c (revision 2b9c0f9f43ba74451b873b59bedeb267f2fc4a30)
1 /*	$NetBSD: pax.c,v 1.52 2024/08/05 13:37:27 riastradh Exp $	*/
2 
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 HAVE_NBTOOL_CONFIG_H
37 #include "nbtool_config.h"
38 #endif
39 
40 #include <sys/cdefs.h>
41 #if !defined(lint)
42 __COPYRIGHT("@(#) Copyright (c) 1992, 1993\
43  The Regents of the University of California.  All rights reserved.");
44 #if 0
45 static char sccsid[] = "@(#)pax.c	8.2 (Berkeley) 4/18/94";
46 #else
47 __RCSID("$NetBSD: pax.c,v 1.52 2024/08/05 13:37:27 riastradh Exp $");
48 #endif
49 #endif /* not lint */
50 
51 #include <sys/param.h>
52 #include <sys/resource.h>
53 #include <sys/stat.h>
54 #include <sys/time.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <paths.h>
58 #include <signal.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <time.h>
63 #include <unistd.h>
64 #include <util.h>
65 #include "pax.h"
66 #include "extern.h"
67 static int gen_init(void);
68 
69 /*
70  * PAX main routines, general globals and some simple start up routines
71  */
72 
73 /*
74  * Variables that can be accessed by any routine within pax
75  */
76 int	act = ERROR;		/* read/write/append/copy */
77 FSUB	*frmt = NULL;		/* archive format type */
78 int	cflag;			/* match all EXCEPT pattern/file */
79 int	cwdfd = -1;		/* starting cwd */
80 int	dflag;			/* directory member match only  */
81 int	iflag;			/* interactive file/archive rename */
82 int	kflag;			/* do not overwrite existing files */
83 int	lflag;			/* use hard links when possible */
84 int	nflag;			/* select first archive member match */
85 int	tflag;			/* restore access time after read */
86 int	uflag;			/* ignore older modification time files */
87 int	vflag;			/* produce verbose output */
88 int	Aflag;			/* honor absolute path */
89 int	Dflag;			/* same as uflag except inode change time */
90 int	Hflag;			/* follow command line symlinks (write only) */
91 int	Lflag;			/* follow symlinks when writing */
92 int	Mflag;			/* treat stdin as an mtree(8) specfile */
93 int	Vflag;			/* produce somewhat verbose output (no listing) */
94 int	Xflag;			/* archive files with same device id only */
95 int	Yflag;			/* same as Dflg except after name mode */
96 int	Zflag;			/* same as uflg except after name mode */
97 int	vfpart;			/* is partial verbose output in progress */
98 int	patime = 1;		/* preserve file access time */
99 int	pmtime = 1;		/* preserve file modification times */
100 int	nodirs;			/* do not create directories as needed */
101 int	pfflags = 1;		/* preserve file flags */
102 int	pmode;			/* preserve file mode bits */
103 int	pids;			/* preserve file uid/gid */
104 int	rmleadslash = 0;	/* remove leading '/' from pathnames */
105 int	exit_val;		/* exit value */
106 int	docrc;			/* check/create file crc */
107 int	to_stdout;		/* extract to stdout */
108 char	*dirptr;		/* destination dir in a copy */
109 char	*ltmfrmt;		/* -v locale time format (if any) */
110 const char *argv0;		/* root of argv[0] */
111 sigset_t s_mask;		/* signal mask for cleanup critical sect */
112 FILE	*listf;			/* file pointer to print file list to */
113 char	*tempfile;		/* tempfile to use for mkstemp(3) */
114 char	*tempbase;		/* basename of tempfile to use for mkstemp(3) */
115 int	forcelocal;		/* force local operation even if the name
116 				 * contains a :
117 				 */
118 int	secure = 1;		/* don't extract names that contain .. */
119 
120 /*
121  *	PAX - Portable Archive Interchange
122  *
123  *	A utility to read, write, and write lists of the members of archive
124  *	files and copy directory hierarchies. A variety of archive formats
125  *	are supported (some are described in POSIX 1003.1 10.1):
126  *
127  *		ustar - 10.1.1 extended tar interchange format
128  *		cpio  - 10.1.2 extended cpio interchange format
129  *		tar - old BSD 4.3 tar format
130  *		binary cpio - old cpio with binary header format
131  *		sysVR4 cpio -  with and without CRC
132  *
133  * This version is a superset of IEEE Std 1003.2b-d3
134  *
135  * Summary of Extensions to the IEEE Standard:
136  *
137  * 1	READ ENHANCEMENTS
138  * 1.1	Operations which read archives will continue to operate even when
139  *	processing archives which may be damaged, truncated, or fail to meet
140  *	format specs in several different ways. Damaged sections of archives
141  *	are detected and avoided if possible. Attempts will be made to resync
142  *	archive read operations even with badly damaged media.
143  * 1.2	Blocksize requirements are not strictly enforced on archive read.
144  *	Tapes which have variable sized records can be read without errors.
145  * 1.3	The user can specify via the non-standard option flag -E if error
146  *	resync operation should stop on a media error, try a specified number
147  *	of times to correct, or try to correct forever.
148  * 1.4	Sparse files (lseek holes) stored on the archive (but stored with blocks
149  *	of all zeros will be restored with holes appropriate for the target
150  *	filesystem
151  * 1.5	The user is notified whenever something is found during archive
152  *	read operations which violates spec (but the read will continue).
153  * 1.6	Multiple archive volumes can be read and may span over different
154  *	archive devices
155  * 1.7	Rigidly restores all file attributes exactly as they are stored on the
156  *	archive.
157  * 1.8	Modification change time ranges can be specified via multiple -T
158  *	options. These allow a user to select files whose modification time
159  *	lies within a specific time range.
160  * 1.9	Files can be selected based on owner (user name or uid) via one or more
161  *	-U options.
162  * 1.10	Files can be selected based on group (group name or gid) via one o
163  *	more -G options.
164  * 1.11	File modification time can be checked against existing file after
165  *	name modification (-Z)
166  *
167  * 2	WRITE ENHANCEMENTS
168  * 2.1	Write operation will stop instead of allowing a user to create a flawed
169  *	flawed archive (due to any problem).
170  * 2.2	Archives written by pax are forced to strictly conform to both the
171  *	archive and pax the specific format specifications.
172  * 2.3	Blocking size and format is rigidly enforced on writes.
173  * 2.4	Formats which may exhibit header overflow problems (they have fields
174  *	too small for large file systems, such as inode number storage), use
175  *	routines designed to repair this problem. These techniques still
176  *	conform to both pax and format specifications, but no longer truncate
177  *	these fields. This removes any restrictions on using these archive
178  *	formats on large file systems.
179  * 2.5	Multiple archive volumes can be written and may span over different
180  *	archive devices
181  * 2.6	A archive volume record limit allows the user to specify the number
182  *	of bytes stored on an archive volume. When reached the user is
183  *	prompted for the next archive volume. This is specified with the
184  *	non-standard -B flag. The limit is rounded up to the next blocksize.
185  * 2.7	All archive padding during write use zero filled sections. This makes
186  *	it much easier to pull data out of flawed archive during read
187  *	operations.
188  * 2.8	Access time reset with the -t applies to all file nodes (including
189  *	directories).
190  * 2.9	Symbolic links can be followed with -L (optional in the spec).
191  * 2.10	Modification or inode change time ranges can be specified via
192  *	multiple -T options. These allow a user to select files whose
193  *	modification or inode change time lies within a specific time range.
194  * 2.11	Files can be selected based on owner (user name or uid) via one or more
195  *	-U options.
196  * 2.12	Files can be selected based on group (group name or gid) via one o
197  *	more -G options.
198  * 2.13	Symlinks which appear on the command line can be followed (without
199  *	following other symlinks; -H flag)
200  *
201  * 3	COPY ENHANCEMENTS
202  * 3.1	Sparse files (lseek holes) can be copied without expanding the holes
203  *	into zero filled blocks. The file copy is created with holes which are
204  *	appropriate for the target filesystem
205  * 3.2	Access time as well as modification time on copied file trees can be
206  *	preserved with the appropriate -p options.
207  * 3.3	Access time reset with the -t applies to all file nodes (including
208  *	directories).
209  * 3.4	Symbolic links can be followed with -L (optional in the spec).
210  * 3.5	Modification or inode change time ranges can be specified via
211  *	multiple -T options. These allow a user to select files whose
212  *	modification or inode change time lies within a specific time range.
213  * 3.6	Files can be selected based on owner (user name or uid) via one or more
214  *	-U options.
215  * 3.7	Files can be selected based on group (group name or gid) via one o
216  *	more -G options.
217  * 3.8	Symlinks which appear on the command line can be followed (without
218  *	following other symlinks; -H flag)
219  * 3.9	File inode change time can be checked against existing file before
220  *	name modification (-D)
221  * 3.10	File inode change time can be checked against existing file after
222  *	name modification (-Y)
223  * 3.11	File modification time can be checked against existing file after
224  *	name modification (-Z)
225  *
226  * 4	GENERAL ENHANCEMENTS
227  * 4.1	Internal structure is designed to isolate format dependent and
228  *	independent functions. Formats are selected via a format driver table.
229  *	This encourages the addition of new archive formats by only having to
230  *	write those routines which id, read and write the archive header.
231  */
232 
233 /*
234  * main()
235  *	parse options, set up and operate as specified by the user.
236  *	any operational flaw will set exit_val to non-zero
237  * Return: 0 if ok, 1 otherwise
238  */
239 
240 int
241 main(int argc, char **argv)
242 {
243 	const char *tmpdir;
244 	size_t tdlen;
245 	int rval;
246 
247 	setprogname(argv[0]);
248 
249 	listf = stderr;
250 
251 	/*
252 	 * parse options, determine operational mode
253 	 */
254 	options(argc, argv);
255 
256 	/*
257 	 * general init
258 	 */
259 	if ((gen_init() < 0) || (tty_init() < 0))
260 		return exit_val;
261 
262 	/*
263 	 * For any actions other than LIST, keep a reference to cwd, so
264 	 * we can always come back home.
265 	 *
266 	 * For EXTRACT (pax -r) without --insecure, also save the path
267 	 * to cwd to check for escape attempts.
268 	 */
269 	if (act != LIST) {
270 		cwdfd = open(".", O_RDONLY);
271 		if (cwdfd < 0) {
272 			syswarn(1, errno,
273 			    "Can't open current working directory.");
274 			return exit_val;
275 		}
276 		if (act == EXTRACT && secure) {
277 			if (updatepath() == -1)
278 				return exit_val;
279 		}
280 	}
281 
282 	/*
283 	 * Where should we put temporary files?
284 	 */
285 	if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
286 		tmpdir = _PATH_TMP;
287 	tdlen = strlen(tmpdir);
288 	while(tdlen > 0 && tmpdir[tdlen - 1] == '/')
289 		tdlen--;
290 	tempfile = malloc(tdlen + 1 + sizeof(_TFILE_BASE));
291 	if (tempfile == NULL) {
292 		tty_warn(1, "Cannot allocate memory for temp file name.");
293 		return exit_val;
294 	}
295 	if (tdlen)
296 		memcpy(tempfile, tmpdir, tdlen);
297 	tempbase = tempfile + tdlen;
298 	*tempbase++ = '/';
299 
300 	(void)time(&starttime);
301 #ifdef SIGINFO
302 	(void)signal(SIGINFO, ar_summary);
303 #endif
304 	/*
305 	 * select a primary operation mode
306 	 */
307 	switch (act) {
308 	case EXTRACT:
309 		rval = extract();
310 		break;
311 	case ARCHIVE:
312 		rval = archive();
313 		break;
314 	case APPND:
315 		if (gzip_program != NULL)
316 			err(1, "cannot gzip while appending");
317 		rval = append();
318 		/*
319 		 * Check if we tried to append on an empty file and
320 		 * turned into ARCHIVE mode.
321 		 */
322 		if (act == -ARCHIVE) {
323 			act = ARCHIVE;
324 			rval = archive();
325 		}
326 		break;
327 	case COPY:
328 		rval = copy();
329 		break;
330 	default:
331 	case LIST:
332 		rval = list();
333 		break;
334 	}
335 	if (rval != 0)
336 		exit_val = 1;
337 	return exit_val;
338 }
339 
340 /*
341  * sig_cleanup()
342  *	when interrupted we try to do whatever delayed processing we can.
343  *	This is not critical, but we really ought to limit our damage when we
344  *	are aborted by the user.
345  * Return:
346  *	never....
347  */
348 
349 __dead static void
350 sig_cleanup(int which_sig)
351 {
352 	/*
353 	 * restore modes and times for any dirs we may have created
354 	 * or any dirs we may have read. Set vflag and vfpart so the user
355 	 * will clearly see the message on a line by itself.
356 	 */
357 	vflag = vfpart = 1;
358 #ifdef SIGXCPU
359 	if (which_sig == SIGXCPU)
360 		tty_warn(1, "CPU time limit reached, cleaning up.");
361 	else
362 #endif
363 		tty_warn(1, "Signal caught, cleaning up.");
364 
365 	/* delete any open temporary file */
366 	if (xtmp_name)
367 		(void)unlink(xtmp_name);
368 	ar_close();
369 	proc_dir();
370 	if (tflag)
371 		atdir_end();
372 
373 	(void)raise_default_signal(which_sig);
374 	exit(1);
375 }
376 
377 /*
378  * gen_init()
379  *	general setup routines. Not all are required, but they really help
380  *	when dealing with a medium to large sized archives.
381  */
382 
383 static int
384 gen_init(void)
385 {
386 	struct rlimit reslimit;
387 	struct sigaction n_hand;
388 	struct sigaction o_hand;
389 
390 	/*
391 	 * Really needed to handle large archives. We can run out of memory for
392 	 * internal tables really fast when we have a whole lot of files...
393 	 */
394 	if (getrlimit(RLIMIT_DATA , &reslimit) == 0){
395 		reslimit.rlim_cur = reslimit.rlim_max;
396 		(void)setrlimit(RLIMIT_DATA , &reslimit);
397 	}
398 
399 	/*
400 	 * should file size limits be waived? if the os limits us, this is
401 	 * needed if we want to write a large archive
402 	 */
403 	if (getrlimit(RLIMIT_FSIZE , &reslimit) == 0){
404 		reslimit.rlim_cur = reslimit.rlim_max;
405 		(void)setrlimit(RLIMIT_FSIZE , &reslimit);
406 	}
407 
408 	/*
409 	 * increase the size the stack can grow to
410 	 */
411 	if (getrlimit(RLIMIT_STACK , &reslimit) == 0){
412 		reslimit.rlim_cur = reslimit.rlim_max;
413 		(void)setrlimit(RLIMIT_STACK , &reslimit);
414 	}
415 
416 #ifdef RLIMIT_RSS
417 	/*
418 	 * not really needed, but doesn't hurt
419 	 */
420 	if (getrlimit(RLIMIT_RSS , &reslimit) == 0){
421 		reslimit.rlim_cur = reslimit.rlim_max;
422 		(void)setrlimit(RLIMIT_RSS , &reslimit);
423 	}
424 #endif
425 
426 	/*
427 	 * Handle posix locale
428 	 *
429 	 * set user defines time printing format for -v option
430 	 */
431 	ltmfrmt = getenv("LC_TIME");
432 
433 	/*
434 	 * signal handling to reset stored directory times and modes. Since
435 	 * we deal with broken pipes via failed writes we ignore it. We also
436 	 * deal with any file size limit through failed writes. CPU time
437 	 * limits are caught and a cleanup is forced.
438 	 */
439 	if ((sigemptyset(&s_mask) < 0) || (sigaddset(&s_mask, SIGTERM) < 0) ||
440 	    (sigaddset(&s_mask,SIGINT) < 0)||(sigaddset(&s_mask,SIGHUP) < 0) ||
441 	    (sigaddset(&s_mask,SIGPIPE) < 0)||(sigaddset(&s_mask,SIGQUIT)<0)){
442 		tty_warn(1, "Unable to set up signal mask");
443 		return -1;
444 	}
445 #ifdef SIGXCPU
446 	if (sigaddset(&s_mask,SIGXCPU) < 0) {
447 		tty_warn(1, "Unable to set up signal mask");
448 		return -1;
449 	}
450 #endif
451 #ifdef SIGXFSZ
452 	if (sigaddset(&s_mask,SIGXFSZ) < 0) {
453 		tty_warn(1, "Unable to set up signal mask");
454 		return -1;
455 	}
456 #endif
457 
458 	memset(&n_hand, 0, sizeof n_hand);
459 	n_hand.sa_mask = s_mask;
460 	n_hand.sa_flags = 0;
461 	n_hand.sa_handler = sig_cleanup;
462 
463 	if ((sigaction(SIGHUP, &n_hand, &o_hand) < 0) &&
464 	    (o_hand.sa_handler == SIG_IGN) &&
465 	    (sigaction(SIGHUP, &o_hand, NULL) < 0))
466 		goto out;
467 
468 	if ((sigaction(SIGTERM, &n_hand, &o_hand) < 0) &&
469 	    (o_hand.sa_handler == SIG_IGN) &&
470 	    (sigaction(SIGTERM, &o_hand, NULL) < 0))
471 		goto out;
472 
473 	if ((sigaction(SIGINT, &n_hand, &o_hand) < 0) &&
474 	    (o_hand.sa_handler == SIG_IGN) &&
475 	    (sigaction(SIGINT, &o_hand, NULL) < 0))
476 		goto out;
477 
478 	if ((sigaction(SIGQUIT, &n_hand, &o_hand) < 0) &&
479 	    (o_hand.sa_handler == SIG_IGN) &&
480 	    (sigaction(SIGQUIT, &o_hand, NULL) < 0))
481 		goto out;
482 
483 #ifdef SIGXCPU
484 	if ((sigaction(SIGXCPU, &n_hand, &o_hand) < 0) &&
485 	    (o_hand.sa_handler == SIG_IGN) &&
486 	    (sigaction(SIGXCPU, &o_hand, NULL) < 0))
487 		goto out;
488 #endif
489 	n_hand.sa_handler = SIG_IGN;
490 	if (sigaction(SIGPIPE, &n_hand, &o_hand) < 0)
491 		goto out;
492 #ifdef SIGXFSZ
493 	if (sigaction(SIGXFSZ, &n_hand, &o_hand) < 0)
494 		goto out;
495 #endif
496 	return 0;
497 
498     out:
499 	syswarn(1, errno, "Unable to set up signal handler");
500 	return -1;
501 }
502