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