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