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