pax.c revision 102230
1326943Sdim/*-
2326943Sdim * Copyright (c) 1992 Keith Muller.
3353358Sdim * Copyright (c) 1992, 1993
4353358Sdim *	The Regents of the University of California.  All rights reserved.
5353358Sdim *
6326943Sdim * This code is derived from software contributed to Berkeley by
7326943Sdim * Keith Muller of the University of California, San Diego.
8326943Sdim *
9326943Sdim * Redistribution and use in source and binary forms, with or without
10326943Sdim * modification, are permitted provided that the following conditions
11326943Sdim * are met:
12326943Sdim * 1. Redistributions of source code must retain the above copyright
13326943Sdim *    notice, this list of conditions and the following disclaimer.
14326943Sdim * 2. Redistributions in binary form must reproduce the above copyright
15326943Sdim *    notice, this list of conditions and the following disclaimer in the
16326943Sdim *    documentation and/or other materials provided with the distribution.
17326943Sdim * 3. All advertising materials mentioning features or use of this software
18326943Sdim *    must display the following acknowledgement:
19326943Sdim *	This product includes software developed by the University of
20326943Sdim *	California, Berkeley and its contributors.
21326943Sdim * 4. Neither the name of the University nor the names of its contributors
22326943Sdim *    may be used to endorse or promote products derived from this software
23326943Sdim *    without specific prior written permission.
24326943Sdim *
25326943Sdim * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26326943Sdim * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27326943Sdim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28326943Sdim * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29326943Sdim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30326943Sdim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31326943Sdim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32326943Sdim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33326943Sdim * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34326943Sdim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35326943Sdim * SUCH DAMAGE.
36326943Sdim */
37326943Sdim
38326943Sdim#ifndef lint
39326943Sdimstatic char const copyright[] =
40326943Sdim"@(#) Copyright (c) 1992, 1993\n\
41326943Sdim	The Regents of the University of California.  All rights reserved.\n";
42326943Sdim#endif /* not lint */
43326943Sdim
44326943Sdim#ifndef lint
45326943Sdim#if 0
46326943Sdimstatic char sccsid[] = "@(#)pax.c	8.2 (Berkeley) 4/18/94";
47326943Sdim#endif
48326943Sdim#endif /* not lint */
49326943Sdim#include <sys/cdefs.h>
50326943Sdim__FBSDID("$FreeBSD: head/bin/pax/pax.c 102230 2002-08-21 17:32:44Z trhodes $");
51326943Sdim
52326943Sdim#include <sys/types.h>
53326943Sdim#include <sys/stat.h>
54353358Sdim#include <sys/time.h>
55326943Sdim#include <sys/resource.h>
56326943Sdim#include <err.h>
57326943Sdim#include <errno.h>
58326943Sdim#include <fcntl.h>
59326943Sdim#include <locale.h>
60326943Sdim#include <paths.h>
61326943Sdim#include <signal.h>
62326943Sdim#include <stdio.h>
63326943Sdim#include <stdlib.h>
64326943Sdim#include <string.h>
65326943Sdim#include <unistd.h>
66353358Sdim#include "pax.h"
67353358Sdim#include "extern.h"
68326943Sdimstatic int gen_init(void);
69326943Sdim
70326943Sdim/*
71326943Sdim * PAX main routines, general globals and some simple start up routines
72326943Sdim */
73353358Sdim
74353358Sdim/*
75353358Sdim * Variables that can be accessed by any routine within pax
76353358Sdim */
77353358Sdimint	act = DEFOP;		/* read/write/append/copy */
78353358SdimFSUB	*frmt = NULL;		/* archive format type */
79353358Sdimint	cflag;			/* match all EXCEPT pattern/file */
80353358Sdimint	cwdfd;			/* starting cwd */
81353358Sdimint	dflag;			/* directory member match only  */
82353358Sdimint	iflag;			/* interactive file/archive rename */
83353358Sdimint	kflag;			/* do not overwrite existing files */
84326943Sdimint	lflag;			/* use hard links when possible */
85326943Sdimint	nflag;			/* select first archive member match */
86326943Sdimint	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;			/* 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 *	file system
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 file system
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
231int
232main(int argc, char *argv[])
233{
234	char *tmpdir;
235	size_t tdlen;
236
237	(void) setlocale(LC_ALL, "");
238	listf = stderr;
239	/*
240	 * Keep a reference to cwd, so we can always come back home.
241	 */
242	cwdfd = open(".", O_RDONLY);
243	if (cwdfd < 0) {
244		syswarn(0, errno, "Can't open current working directory.");
245		return(exit_val);
246	}
247
248	/*
249	 * Where should we put temporary files?
250	 */
251	if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
252		tmpdir = _PATH_TMP;
253	tdlen = strlen(tmpdir);
254	while(tdlen > 0 && tmpdir[tdlen - 1] == '/')
255		tdlen--;
256	tempfile = malloc(tdlen + 1 + sizeof(_TFILE_BASE));
257	if (tempfile == NULL) {
258		paxwarn(1, "Cannot allocate memory for temp file name.");
259		return(exit_val);
260	}
261	if (tdlen)
262		memcpy(tempfile, tmpdir, tdlen);
263	tempbase = tempfile + tdlen;
264	*tempbase++ = '/';
265
266	/*
267	 * parse options, determine operational mode, general init
268	 */
269	options(argc, argv);
270	if ((gen_init() < 0) || (tty_init() < 0))
271		return(exit_val);
272
273	/*
274	 * select a primary operation mode
275	 */
276	switch(act) {
277	case EXTRACT:
278		extract();
279		break;
280	case ARCHIVE:
281		archive();
282		break;
283	case APPND:
284		if (gzip_program != NULL)
285			err(1, "can not gzip while appending");
286		append();
287		break;
288	case COPY:
289		copy();
290		break;
291	default:
292	case LIST:
293		list();
294		break;
295	}
296	return(exit_val);
297}
298
299/*
300 * sig_cleanup()
301 *	when interrupted we try to do whatever delayed processing we can.
302 *	This is not critical, but we really ought to limit our damage when we
303 *	are aborted by the user.
304 * Return:
305 *	never....
306 */
307
308void
309sig_cleanup(int which_sig)
310{
311	/*
312	 * restore modes and times for any dirs we may have created
313	 * or any dirs we may have read. Set vflag and vfpart so the user
314	 * will clearly see the message on a line by itself.
315	 */
316	vflag = vfpart = 1;
317	if (which_sig == SIGXCPU)
318		paxwarn(0, "Cpu time limit reached, cleaning up.");
319	else
320		paxwarn(0, "Signal caught, cleaning up.");
321
322	ar_close();
323	proc_dir();
324	if (tflag)
325		atdir_end();
326	exit(1);
327}
328
329/*
330 * gen_init()
331 *	general setup routines. Not all are required, but they really help
332 *	when dealing with a medium to large sized archives.
333 */
334
335static int
336gen_init(void)
337{
338	struct rlimit reslimit;
339	struct sigaction n_hand;
340	struct sigaction o_hand;
341
342	/*
343	 * Really needed to handle large archives. We can run out of memory for
344	 * internal tables really fast when we have a whole lot of files...
345	 */
346	if (getrlimit(RLIMIT_DATA , &reslimit) == 0){
347		reslimit.rlim_cur = reslimit.rlim_max;
348		(void)setrlimit(RLIMIT_DATA , &reslimit);
349	}
350
351	/*
352	 * should file size limits be waived? if the os limits us, this is
353	 * needed if we want to write a large archive
354	 */
355	if (getrlimit(RLIMIT_FSIZE , &reslimit) == 0){
356		reslimit.rlim_cur = reslimit.rlim_max;
357		(void)setrlimit(RLIMIT_FSIZE , &reslimit);
358	}
359
360	/*
361	 * increase the size the stack can grow to
362	 */
363	if (getrlimit(RLIMIT_STACK , &reslimit) == 0){
364		reslimit.rlim_cur = reslimit.rlim_max;
365		(void)setrlimit(RLIMIT_STACK , &reslimit);
366	}
367
368	/*
369	 * not really needed, but doesn't hurt
370	 */
371	if (getrlimit(RLIMIT_RSS , &reslimit) == 0){
372		reslimit.rlim_cur = reslimit.rlim_max;
373		(void)setrlimit(RLIMIT_RSS , &reslimit);
374	}
375
376	/*
377	 * signal handling to reset stored directory times and modes. Since
378	 * we deal with broken pipes via failed writes we ignore it. We also
379	 * deal with any file size limit thorugh failed writes. Cpu time
380	 * limits are caught and a cleanup is forced.
381	 */
382	if ((sigemptyset(&s_mask) < 0) || (sigaddset(&s_mask, SIGTERM) < 0) ||
383	    (sigaddset(&s_mask,SIGINT) < 0)||(sigaddset(&s_mask,SIGHUP) < 0) ||
384	    (sigaddset(&s_mask,SIGPIPE) < 0)||(sigaddset(&s_mask,SIGQUIT)<0) ||
385	    (sigaddset(&s_mask,SIGXCPU) < 0)||(sigaddset(&s_mask,SIGXFSZ)<0)) {
386		paxwarn(1, "Unable to set up signal mask");
387		return(-1);
388	}
389	memset(&n_hand, 0, sizeof n_hand);
390	n_hand.sa_mask = s_mask;
391	n_hand.sa_flags = 0;
392	n_hand.sa_handler = sig_cleanup;
393
394	if ((sigaction(SIGHUP, &n_hand, &o_hand) < 0) &&
395	    (o_hand.sa_handler == SIG_IGN) &&
396	    (sigaction(SIGHUP, &o_hand, &o_hand) < 0))
397		goto out;
398
399	if ((sigaction(SIGTERM, &n_hand, &o_hand) < 0) &&
400	    (o_hand.sa_handler == SIG_IGN) &&
401	    (sigaction(SIGTERM, &o_hand, &o_hand) < 0))
402		goto out;
403
404	if ((sigaction(SIGINT, &n_hand, &o_hand) < 0) &&
405	    (o_hand.sa_handler == SIG_IGN) &&
406	    (sigaction(SIGINT, &o_hand, &o_hand) < 0))
407		goto out;
408
409	if ((sigaction(SIGQUIT, &n_hand, &o_hand) < 0) &&
410	    (o_hand.sa_handler == SIG_IGN) &&
411	    (sigaction(SIGQUIT, &o_hand, &o_hand) < 0))
412		goto out;
413
414	if ((sigaction(SIGXCPU, &n_hand, &o_hand) < 0) &&
415	    (o_hand.sa_handler == SIG_IGN) &&
416	    (sigaction(SIGXCPU, &o_hand, &o_hand) < 0))
417		goto out;
418
419	n_hand.sa_handler = SIG_IGN;
420	if ((sigaction(SIGPIPE, &n_hand, &o_hand) < 0) ||
421	    (sigaction(SIGXFSZ, &n_hand, &o_hand) < 0))
422		goto out;
423	return(0);
424
425    out:
426	syswarn(1, errno, "Unable to set up signal handler");
427	return(-1);
428}
429