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