pax.c revision 81601
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 81601 2001-08-13 21:54:47Z peter $";
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;			/* 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	listf = stderr;
246	/*
247	 * Keep a reference to cwd, so we can always come back home.
248	 */
249	cwdfd = open(".", O_RDONLY);
250	if (cwdfd < 0) {
251		syswarn(0, errno, "Can't open current working directory.");
252		return(exit_val);
253	}
254
255	/*
256	 * Where should we put temporary files?
257	 */
258	if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
259		tmpdir = _PATH_TMP;
260	tdlen = strlen(tmpdir);
261	while(tdlen > 0 && tmpdir[tdlen - 1] == '/')
262		tdlen--;
263	tempfile = malloc(tdlen + 1 + sizeof(_TFILE_BASE));
264	if (tempfile == NULL) {
265		paxwarn(1, "Cannot allocate memory for temp file name.");
266		return(exit_val);
267	}
268	if (tdlen)
269		memcpy(tempfile, tmpdir, tdlen);
270	tempbase = tempfile + tdlen;
271	*tempbase++ = '/';
272
273	/*
274	 * parse options, determine operational mode, general init
275	 */
276	options(argc, argv);
277	if ((gen_init() < 0) || (tty_init() < 0))
278		return(exit_val);
279
280	/*
281	 * select a primary operation mode
282	 */
283	switch(act) {
284	case EXTRACT:
285		extract();
286		break;
287	case ARCHIVE:
288		archive();
289		break;
290	case APPND:
291		if (gzip_program != NULL)
292			err(1, "can not gzip while appending");
293		append();
294		break;
295	case COPY:
296		copy();
297		break;
298	default:
299	case LIST:
300		list();
301		break;
302	}
303	return(exit_val);
304}
305
306/*
307 * sig_cleanup()
308 *	when interrupted we try to do whatever delayed processing we can.
309 *	This is not critical, but we really ought to limit our damage when we
310 *	are aborted by the user.
311 * Return:
312 *	never....
313 */
314
315#ifdef __STDC__
316void
317sig_cleanup(int which_sig)
318#else
319void
320sig_cleanup(which_sig)
321	int which_sig;
322#endif
323{
324	/*
325	 * restore modes and times for any dirs we may have created
326	 * or any dirs we may have read. Set vflag and vfpart so the user
327	 * will clearly see the message on a line by itself.
328	 */
329	vflag = vfpart = 1;
330	if (which_sig == SIGXCPU)
331		paxwarn(0, "Cpu time limit reached, cleaning up.");
332	else
333		paxwarn(0, "Signal caught, cleaning up.");
334
335	ar_close();
336	proc_dir();
337	if (tflag)
338		atdir_end();
339	exit(1);
340}
341
342/*
343 * gen_init()
344 *	general setup routines. Not all are required, but they really help
345 *	when dealing with a medium to large sized archives.
346 */
347
348#ifdef __STDC__
349static int
350gen_init(void)
351#else
352static int
353gen_init()
354#endif
355{
356	struct rlimit reslimit;
357	struct sigaction n_hand;
358	struct sigaction o_hand;
359
360	/*
361	 * Really needed to handle large archives. We can run out of memory for
362	 * internal tables really fast when we have a whole lot of files...
363	 */
364	if (getrlimit(RLIMIT_DATA , &reslimit) == 0){
365		reslimit.rlim_cur = reslimit.rlim_max;
366		(void)setrlimit(RLIMIT_DATA , &reslimit);
367	}
368
369	/*
370	 * should file size limits be waived? if the os limits us, this is
371	 * needed if we want to write a large archive
372	 */
373	if (getrlimit(RLIMIT_FSIZE , &reslimit) == 0){
374		reslimit.rlim_cur = reslimit.rlim_max;
375		(void)setrlimit(RLIMIT_FSIZE , &reslimit);
376	}
377
378	/*
379	 * increase the size the stack can grow to
380	 */
381	if (getrlimit(RLIMIT_STACK , &reslimit) == 0){
382		reslimit.rlim_cur = reslimit.rlim_max;
383		(void)setrlimit(RLIMIT_STACK , &reslimit);
384	}
385
386	/*
387	 * not really needed, but doesn't hurt
388	 */
389	if (getrlimit(RLIMIT_RSS , &reslimit) == 0){
390		reslimit.rlim_cur = reslimit.rlim_max;
391		(void)setrlimit(RLIMIT_RSS , &reslimit);
392	}
393
394	/*
395	 * signal handling to reset stored directory times and modes. Since
396	 * we deal with broken pipes via failed writes we ignore it. We also
397	 * deal with any file size limit thorugh failed writes. Cpu time
398	 * limits are caught and a cleanup is forced.
399	 */
400	if ((sigemptyset(&s_mask) < 0) || (sigaddset(&s_mask, SIGTERM) < 0) ||
401	    (sigaddset(&s_mask,SIGINT) < 0)||(sigaddset(&s_mask,SIGHUP) < 0) ||
402	    (sigaddset(&s_mask,SIGPIPE) < 0)||(sigaddset(&s_mask,SIGQUIT)<0) ||
403	    (sigaddset(&s_mask,SIGXCPU) < 0)||(sigaddset(&s_mask,SIGXFSZ)<0)) {
404		paxwarn(1, "Unable to set up signal mask");
405		return(-1);
406	}
407	memset(&n_hand, 0, sizeof n_hand);
408	n_hand.sa_mask = s_mask;
409	n_hand.sa_flags = 0;
410	n_hand.sa_handler = sig_cleanup;
411
412	if ((sigaction(SIGHUP, &n_hand, &o_hand) < 0) &&
413	    (o_hand.sa_handler == SIG_IGN) &&
414	    (sigaction(SIGHUP, &o_hand, &o_hand) < 0))
415		goto out;
416
417	if ((sigaction(SIGTERM, &n_hand, &o_hand) < 0) &&
418	    (o_hand.sa_handler == SIG_IGN) &&
419	    (sigaction(SIGTERM, &o_hand, &o_hand) < 0))
420		goto out;
421
422	if ((sigaction(SIGINT, &n_hand, &o_hand) < 0) &&
423	    (o_hand.sa_handler == SIG_IGN) &&
424	    (sigaction(SIGINT, &o_hand, &o_hand) < 0))
425		goto out;
426
427	if ((sigaction(SIGQUIT, &n_hand, &o_hand) < 0) &&
428	    (o_hand.sa_handler == SIG_IGN) &&
429	    (sigaction(SIGQUIT, &o_hand, &o_hand) < 0))
430		goto out;
431
432	if ((sigaction(SIGXCPU, &n_hand, &o_hand) < 0) &&
433	    (o_hand.sa_handler == SIG_IGN) &&
434	    (sigaction(SIGXCPU, &o_hand, &o_hand) < 0))
435		goto out;
436
437	n_hand.sa_handler = SIG_IGN;
438	if ((sigaction(SIGPIPE, &n_hand, &o_hand) < 0) ||
439	    (sigaction(SIGXFSZ, &n_hand, &o_hand) < 0))
440		goto out;
441	return(0);
442
443    out:
444	syswarn(1, errno, "Unable to set up signal handler");
445	return(-1);
446}
447