Home | History | Annotate | Line # | Download | only in pax
ar_subs.c revision 1.34
      1 /*	$NetBSD: ar_subs.c,v 1.34 2004/10/22 21:00:18 jmc Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1992 Keith Muller.
      5  * Copyright (c) 1992, 1993
      6  *	The Regents of the University of California.  All rights reserved.
      7  *
      8  * This code is derived from software contributed to Berkeley by
      9  * Keith Muller of the University of California, San Diego.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #if HAVE_NBTOOL_CONFIG_H
     37 #include "nbtool_config.h"
     38 #endif
     39 
     40 #include <sys/cdefs.h>
     41 #if !defined(lint)
     42 #if 0
     43 static char sccsid[] = "@(#)ar_subs.c	8.2 (Berkeley) 4/18/94";
     44 #else
     45 __RCSID("$NetBSD: ar_subs.c,v 1.34 2004/10/22 21:00:18 jmc Exp $");
     46 #endif
     47 #endif /* not lint */
     48 
     49 #include <sys/types.h>
     50 #include <sys/time.h>
     51 #include <sys/stat.h>
     52 #include <sys/param.h>
     53 #include <signal.h>
     54 #include <string.h>
     55 #include <stdio.h>
     56 #include <ctype.h>
     57 #include <fcntl.h>
     58 #include <errno.h>
     59 #include <time.h>
     60 #include <unistd.h>
     61 #include <stdlib.h>
     62 #include "pax.h"
     63 #include "extern.h"
     64 
     65 static void wr_archive(ARCHD *, int is_app);
     66 static int get_arc(void);
     67 static int next_head(ARCHD *);
     68 extern sigset_t s_mask;
     69 
     70 /*
     71  * Routines which control the overall operation modes of pax as specified by
     72  * the user: list, append, read ...
     73  */
     74 
     75 static char hdbuf[BLKMULT];		/* space for archive header on read */
     76 u_long flcnt;				/* number of files processed */
     77 ARCHD archd;
     78 
     79 /*
     80  * list()
     81  *	list the contents of an archive which match user supplied pattern(s)
     82  *	(if no pattern is supplied, list entire contents).
     83  */
     84 
     85 void
     86 list(void)
     87 {
     88 	ARCHD *arcn;
     89 	int res;
     90 	time_t now;
     91 
     92 	arcn = &archd;
     93 	/*
     94 	 * figure out archive type; pass any format specific options to the
     95 	 * archive option processing routine; call the format init routine. We
     96 	 * also save current time for ls_list() so we do not make a system
     97 	 * call for each file we need to print. If verbose (vflag) start up
     98 	 * the name and group caches.
     99 	 */
    100 	if ((get_arc() < 0) || ((*frmt->options)() < 0) ||
    101 	    ((*frmt->st_rd)() < 0))
    102 		return;
    103 
    104 	now = time((time_t *)NULL);
    105 
    106 	/*
    107 	 * step through the archive until the format says it is done
    108 	 */
    109 	while (next_head(arcn) == 0) {
    110 		if (arcn->type == PAX_GLL || arcn->type == PAX_GLF) {
    111 			/*
    112 			 * we need to read, to get the real filename
    113 			 */
    114 			off_t cnt;
    115 			if (!(*frmt->rd_data)(arcn, arcn->type == PAX_GLF
    116 			    ? -1 : -2, &cnt))
    117 				(void)rd_skip(cnt + arcn->pad);
    118 			continue;
    119 		}
    120 
    121 		if (arcn->name[0] == '/' && !check_Aflag()) {
    122 			memmove(arcn->name, arcn->name + 1, strlen(arcn->name));
    123 		}
    124 		/*
    125 		 * check for pattern, and user specified options match.
    126 		 * When all patterns are matched we are done.
    127 		 */
    128 		if ((res = pat_match(arcn)) < 0)
    129 			break;
    130 
    131 		if ((res == 0) && (sel_chk(arcn) == 0)) {
    132 			/*
    133 			 * pattern resulted in a selected file
    134 			 */
    135 			if (pat_sel(arcn) < 0)
    136 				break;
    137 
    138 			/*
    139 			 * modify the name as requested by the user if name
    140 			 * survives modification, do a listing of the file
    141 			 */
    142 			if ((res = mod_name(arcn)) < 0)
    143 				break;
    144 			if (res == 0)
    145 				ls_list(arcn, now, stdout);
    146 			/*
    147 			 * if there's an error writing to stdout then we must
    148 			 * stop now -- we're probably writing to a pipe that
    149 			 * has been closed by the reader.
    150 			 */
    151 			if (ferror(stdout)) {
    152 				syswarn(1, errno, "Listing incomplete.");
    153 				break;
    154 			}
    155 		}
    156 		/*
    157 		 * skip to next archive format header using values calculated
    158 		 * by the format header read routine
    159 		 */
    160 		if (rd_skip(arcn->skip + arcn->pad) == 1)
    161 			break;
    162 	}
    163 
    164 	/*
    165 	 * all done, let format have a chance to cleanup, and make sure that
    166 	 * the patterns supplied by the user were all matched
    167 	 */
    168 	(void)(*frmt->end_rd)();
    169 	(void)sigprocmask(SIG_BLOCK, &s_mask, (sigset_t *)NULL);
    170 	ar_close();
    171 	pat_chk();
    172 }
    173 
    174 /*
    175  * extract()
    176  *	extract the member(s) of an archive as specified by user supplied
    177  *	pattern(s) (no patterns extracts all members)
    178  */
    179 
    180 void
    181 extract(void)
    182 {
    183 	ARCHD *arcn;
    184 	int res;
    185 	off_t cnt;
    186 	struct stat sb;
    187 	int fd;
    188 	time_t now;
    189 
    190 	arcn = &archd;
    191 	/*
    192 	 * figure out archive type; pass any format specific options to the
    193 	 * archive option processing routine; call the format init routine;
    194 	 * start up the directory modification time and access mode database
    195 	 */
    196 	if ((get_arc() < 0) || ((*frmt->options)() < 0) ||
    197 	    ((*frmt->st_rd)() < 0) || (dir_start() < 0))
    198 		return;
    199 
    200 	now = time((time_t *)NULL);
    201 #if !HAVE_NBTOOL_CONFIG_H
    202 	if (do_chroot && fchroot(cwdfd) != 0) {
    203 		syswarn(1, errno, "Can't fchroot to \".\"");
    204 		return;
    205 	}
    206 #endif
    207 
    208 	/*
    209 	 * When we are doing interactive rename, we store the mapping of names
    210 	 * so we can fix up hard links files later in the archive.
    211 	 */
    212 	if (iflag && (name_start() < 0))
    213 		return;
    214 
    215 	/*
    216 	 * step through each entry on the archive until the format read routine
    217 	 * says it is done
    218 	 */
    219 	while (next_head(arcn) == 0) {
    220 		int write_to_hard_link = 0;
    221 
    222 		if (arcn->type == PAX_GLL || arcn->type == PAX_GLF) {
    223 			/*
    224 			 * we need to read, to get the real filename
    225 			 */
    226 			if (!(*frmt->rd_data)(arcn, arcn->type == PAX_GLF
    227 			    ? -1 : -2, &cnt))
    228 				(void)rd_skip(cnt + arcn->pad);
    229 			continue;
    230 		}
    231 
    232 		if (arcn->name[0] == '/' && !check_Aflag()) {
    233 			memmove(arcn->name, arcn->name + 1, strlen(arcn->name));
    234 		}
    235 		/*
    236 		 * check for pattern, and user specified options match. When
    237 		 * all the patterns are matched we are done
    238 		 */
    239 		if ((res = pat_match(arcn)) < 0)
    240 			break;
    241 
    242 		if ((res > 0) || (sel_chk(arcn) != 0)) {
    243 			/*
    244 			 * file is not selected. skip past any file
    245 			 * data and padding and go back for the next
    246 			 * archive member
    247 			 */
    248 			(void)rd_skip(arcn->skip + arcn->pad);
    249 			continue;
    250 		}
    251 
    252 		/*
    253 		 * with -u or -D only extract when the archive member is newer
    254 		 * than the file with the same name in the file system (no
    255 		 * test of being the same type is required).
    256 		 * NOTE: this test is done BEFORE name modifications as
    257 		 * specified by pax. this operation can be confusing to the
    258 		 * user who might expect the test to be done on an existing
    259 		 * file AFTER the name mod. In honesty the pax spec is probably
    260 		 * flawed in this respect.  ignore this for GNU long links.
    261 		 */
    262 		if ((uflag || Dflag) && ((lstat(arcn->name, &sb) == 0))) {
    263 			if (uflag && Dflag) {
    264 				if ((arcn->sb.st_mtime <= sb.st_mtime) &&
    265 				    (arcn->sb.st_ctime <= sb.st_ctime)) {
    266 					(void)rd_skip(arcn->skip + arcn->pad);
    267 					continue;
    268 				}
    269 			} else if (Dflag) {
    270 				if (arcn->sb.st_ctime <= sb.st_ctime) {
    271 					(void)rd_skip(arcn->skip + arcn->pad);
    272 					continue;
    273 				}
    274 			} else if (arcn->sb.st_mtime <= sb.st_mtime) {
    275 				(void)rd_skip(arcn->skip + arcn->pad);
    276 				continue;
    277 			}
    278 		}
    279 
    280 		/*
    281 		 * this archive member is now been selected. modify the name.
    282 		 */
    283 		if ((pat_sel(arcn) < 0) || ((res = mod_name(arcn)) < 0))
    284 			break;
    285 		if (res > 0) {
    286 			/*
    287 			 * a bad name mod, skip and purge name from link table
    288 			 */
    289 			purg_lnk(arcn);
    290 			(void)rd_skip(arcn->skip + arcn->pad);
    291 			continue;
    292 		}
    293 
    294 		/*
    295 		 * Non standard -Y and -Z flag. When the existing file is
    296 		 * same age or newer skip; ignore this for GNU long links.
    297 		 */
    298 		if ((Yflag || Zflag) && ((lstat(arcn->name, &sb) == 0))) {
    299 			if (Yflag && Zflag) {
    300 				if ((arcn->sb.st_mtime <= sb.st_mtime) &&
    301 				    (arcn->sb.st_ctime <= sb.st_ctime)) {
    302 					(void)rd_skip(arcn->skip + arcn->pad);
    303 					continue;
    304 				}
    305 			} else if (Yflag) {
    306 				if (arcn->sb.st_ctime <= sb.st_ctime) {
    307 					(void)rd_skip(arcn->skip + arcn->pad);
    308 					continue;
    309 				}
    310 			} else if (arcn->sb.st_mtime <= sb.st_mtime) {
    311 				(void)rd_skip(arcn->skip + arcn->pad);
    312 				continue;
    313 			}
    314 		}
    315 
    316 		if (vflag) {
    317 			if (vflag > 1)
    318 				ls_list(arcn, now, listf);
    319 			else {
    320 				(void)safe_print(arcn->name, listf);
    321 				vfpart = 1;
    322 			}
    323 		}
    324 
    325 		/*
    326 		 * if required, chdir around.
    327 		 */
    328 		if ((arcn->pat != NULL) && (arcn->pat->chdname != NULL) &&
    329 		    !to_stdout)
    330 			if (chdir(arcn->pat->chdname) != 0)
    331 				syswarn(1, errno, "Cannot chdir to %s",
    332 				    arcn->pat->chdname);
    333 		/*
    334 		 * all ok, extract this member based on type
    335 		 */
    336 		if ((arcn->type != PAX_REG) && (arcn->type != PAX_CTG)) {
    337 			/*
    338 			 * process archive members that are not regular files.
    339 			 * throw out padding and any data that might follow the
    340 			 * header (as determined by the format).
    341 			 */
    342 			if ((arcn->type == PAX_HLK) ||
    343 			    (arcn->type == PAX_HRG))
    344 				res = lnk_creat(arcn, &write_to_hard_link);
    345 			else
    346 				res = node_creat(arcn);
    347 
    348 			if (!write_to_hard_link) {
    349 				(void)rd_skip(arcn->skip + arcn->pad);
    350 				if (res < 0)
    351 					purg_lnk(arcn);
    352 
    353 				if (vflag && vfpart) {
    354 					(void)putc('\n', listf);
    355 					vfpart = 0;
    356 				}
    357 				continue;
    358 			}
    359 		}
    360 		if (to_stdout)
    361 			fd = STDOUT_FILENO;
    362 		else {
    363 			/*
    364 			 * We have a file with data here. If we cannot create
    365 			 * it, skip over the data and purge the name from hard
    366 			 * link table.
    367 			 */
    368 			if ((fd = file_creat(arcn, write_to_hard_link)) < 0) {
    369 				(void)fflush(listf);
    370 				(void)rd_skip(arcn->skip + arcn->pad);
    371 				purg_lnk(arcn);
    372 				continue;
    373 			}
    374 		}
    375 		/*
    376 		 * extract the file from the archive and skip over padding and
    377 		 * any unprocessed data
    378 		 */
    379 		res = (*frmt->rd_data)(arcn, fd, &cnt);
    380 		if (!to_stdout)
    381 			file_close(arcn, fd);
    382 		if (vflag && vfpart) {
    383 			(void)putc('\n', listf);
    384 			vfpart = 0;
    385 		}
    386 		if (!res)
    387 			(void)rd_skip(cnt + arcn->pad);
    388 
    389 		/*
    390 		 * if required, chdir around.
    391 		 */
    392 		if ((arcn->pat != NULL) && (arcn->pat->chdname != NULL))
    393 			if (fchdir(cwdfd) != 0)
    394 				syswarn(1, errno,
    395 				    "Can't fchdir to starting directory");
    396 	}
    397 
    398 	/*
    399 	 * all done, restore directory modes and times as required; make sure
    400 	 * all patterns supplied by the user were matched; block off signals
    401 	 * to avoid chance for multiple entry into the cleanup code.
    402 	 */
    403 	(void)(*frmt->end_rd)();
    404 	(void)sigprocmask(SIG_BLOCK, &s_mask, (sigset_t *)NULL);
    405 	ar_close();
    406 	proc_dir();
    407 	pat_chk();
    408 }
    409 
    410 /*
    411  * wr_archive()
    412  *	Write an archive. used in both creating a new archive and appends on
    413  *	previously written archive.
    414  */
    415 
    416 static void
    417 wr_archive(ARCHD *arcn, int is_app)
    418 {
    419 	int res;
    420 	int hlk;
    421 	int wr_one;
    422 	off_t cnt;
    423 	int (*wrf)(ARCHD *);
    424 	int fd = -1;
    425 	time_t now;
    426 
    427 	/*
    428 	 * if this format supports hard link storage, start up the database
    429 	 * that detects them.
    430 	 */
    431 	if (((hlk = frmt->hlk) == 1) && (lnk_start() < 0))
    432 		return;
    433 
    434 	/*
    435 	 * start up the file traversal code and format specific write
    436 	 */
    437 	if ((ftree_start() < 0) || ((*frmt->st_wr)() < 0))
    438 		return;
    439 	wrf = frmt->wr;
    440 
    441 	now = time((time_t *)NULL);
    442 
    443 	/*
    444 	 * When we are doing interactive rename, we store the mapping of names
    445 	 * so we can fix up hard links files later in the archive.
    446 	 */
    447 	if (iflag && (name_start() < 0))
    448 		return;
    449 
    450 	/*
    451 	 * if this is not append, and there are no files, we do no write a trailer
    452 	 */
    453 	wr_one = is_app;
    454 
    455 	/*
    456 	 * while there are files to archive, process them one at at time
    457 	 */
    458 	while (next_file(arcn) == 0) {
    459 		/*
    460 		 * check if this file meets user specified options match.
    461 		 */
    462 		if (sel_chk(arcn) != 0)
    463 			continue;
    464 		fd = -1;
    465 		if (uflag) {
    466 			/*
    467 			 * only archive if this file is newer than a file with
    468 			 * the same name that is already stored on the archive
    469 			 */
    470 			if ((res = chk_ftime(arcn)) < 0)
    471 				break;
    472 			if (res > 0)
    473 				continue;
    474 		}
    475 
    476 		/*
    477 		 * this file is considered selected now. see if this is a hard
    478 		 * link to a file already stored
    479 		 */
    480 		ftree_sel(arcn);
    481 		if (hlk && (chk_lnk(arcn) < 0))
    482 			break;
    483 
    484 		if ((arcn->type == PAX_REG) || (arcn->type == PAX_HRG) ||
    485 		    (arcn->type == PAX_CTG)) {
    486 			/*
    487 			 * we will have to read this file. by opening it now we
    488 			 * can avoid writing a header to the archive for a file
    489 			 * we were later unable to read (we also purge it from
    490 			 * the link table).
    491 			 */
    492 			if ((fd = open(arcn->org_name, O_RDONLY, 0)) < 0) {
    493 				syswarn(1, errno, "Unable to open %s to read",
    494 					arcn->org_name);
    495 				purg_lnk(arcn);
    496 				continue;
    497 			}
    498 		}
    499 
    500 		if (arcn->name[0] == '/' && !check_Aflag()) {
    501 			memmove(arcn->name, arcn->name + 1, strlen(arcn->name));
    502 		}
    503 		/*
    504 		 * Now modify the name as requested by the user
    505 		 */
    506 		if ((res = mod_name(arcn)) < 0) {
    507 			/*
    508 			 * name modification says to skip this file, close the
    509 			 * file and purge link table entry
    510 			 */
    511 			rdfile_close(arcn, &fd);
    512 			purg_lnk(arcn);
    513 			break;
    514 		}
    515 
    516 		if ((res > 0) || (docrc && (set_crc(arcn, fd) < 0))) {
    517 			/*
    518 			 * unable to obtain the crc we need, close the file,
    519 			 * purge link table entry
    520 			 */
    521 			rdfile_close(arcn, &fd);
    522 			purg_lnk(arcn);
    523 			continue;
    524 		}
    525 
    526 		if (vflag) {
    527 			if (vflag > 1)
    528 				ls_list(arcn, now, listf);
    529 			else {
    530 				(void)safe_print(arcn->name, listf);
    531 				vfpart = 1;
    532 			}
    533 		}
    534 		++flcnt;
    535 
    536 		/*
    537 		 * looks safe to store the file, have the format specific
    538 		 * routine write routine store the file header on the archive
    539 		 */
    540 		if ((res = (*wrf)(arcn)) < 0) {
    541 			rdfile_close(arcn, &fd);
    542 			break;
    543 		}
    544 		wr_one = 1;
    545 		if (res > 0) {
    546 			/*
    547 			 * format write says no file data needs to be stored
    548 			 * so we are done messing with this file
    549 			 */
    550 			if (vflag && vfpart) {
    551 				(void)putc('\n', listf);
    552 				vfpart = 0;
    553 			}
    554 			rdfile_close(arcn, &fd);
    555 			continue;
    556 		}
    557 
    558 		/*
    559 		 * Add file data to the archive, quit on write error. if we
    560 		 * cannot write the entire file contents to the archive we
    561 		 * must pad the archive to replace the missing file data
    562 		 * (otherwise during an extract the file header for the file
    563 		 * which FOLLOWS this one will not be where we expect it to
    564 		 * be).
    565 		 */
    566 		res = (*frmt->wr_data)(arcn, fd, &cnt);
    567 		rdfile_close(arcn, &fd);
    568 		if (vflag && vfpart) {
    569 			(void)putc('\n', listf);
    570 			vfpart = 0;
    571 		}
    572 		if (res < 0)
    573 			break;
    574 
    575 		/*
    576 		 * pad as required, cnt is number of bytes not written
    577 		 */
    578 		if (((cnt > 0) && (wr_skip(cnt) < 0)) ||
    579 		    ((arcn->pad > 0) && (wr_skip(arcn->pad) < 0)))
    580 			break;
    581 	}
    582 
    583 	/*
    584 	 * tell format to write trailer; pad to block boundary; reset directory
    585 	 * mode/access times, and check if all patterns supplied by the user
    586 	 * were matched. block off signals to avoid chance for multiple entry
    587 	 * into the cleanup code
    588 	 */
    589 	if (wr_one) {
    590 		(*frmt->end_wr)();
    591 		wr_fin();
    592 	}
    593 	(void)sigprocmask(SIG_BLOCK, &s_mask, (sigset_t *)NULL);
    594 	ar_close();
    595 	if (tflag)
    596 		proc_dir();
    597 	ftree_chk();
    598 }
    599 
    600 /*
    601  * append()
    602  *	Add file to previously written archive. Archive format specified by the
    603  *	user must agree with archive. The archive is read first to collect
    604  *	modification times (if -u) and locate the archive trailer. The archive
    605  *	is positioned in front of the record with the trailer and wr_archive()
    606  *	is called to add the new members.
    607  *	PAX IMPLEMENTATION DETAIL NOTE:
    608  *	-u is implemented by adding the new members to the end of the archive.
    609  *	Care is taken so that these do not end up as links to the older
    610  *	version of the same file already stored in the archive. It is expected
    611  *	when extraction occurs these newer versions will over-write the older
    612  *	ones stored "earlier" in the archive (this may be a bad assumption as
    613  *	it depends on the implementation of the program doing the extraction).
    614  *	It is really difficult to splice in members without either re-writing
    615  *	the entire archive (from the point were the old version was), or having
    616  *	assistance of the format specification in terms of a special update
    617  *	header that invalidates a previous archive record. The posix spec left
    618  *	the method used to implement -u unspecified. This pax is able to
    619  *	over write existing files that it creates.
    620  */
    621 
    622 void
    623 append(void)
    624 {
    625 	ARCHD *arcn;
    626 	int res;
    627 	FSUB *orgfrmt;
    628 	int udev;
    629 	off_t tlen;
    630 
    631 	arcn = &archd;
    632 	orgfrmt = frmt;
    633 
    634 	/*
    635 	 * Do not allow an append operation if the actual archive is of a
    636 	 * different format than the user specified format.
    637 	 */
    638 	if (get_arc() < 0)
    639 		return;
    640 	if ((orgfrmt != NULL) && (orgfrmt != frmt)) {
    641 		tty_warn(1, "Cannot mix current archive format %s with %s",
    642 		    frmt->name, orgfrmt->name);
    643 		return;
    644 	}
    645 
    646 	/*
    647 	 * pass the format any options and start up format
    648 	 */
    649 	if (((*frmt->options)() < 0) || ((*frmt->st_rd)() < 0))
    650 		return;
    651 
    652 	/*
    653 	 * if we only are adding members that are newer, we need to save the
    654 	 * mod times for all files we see.
    655 	 */
    656 	if (uflag && (ftime_start() < 0))
    657 		return;
    658 
    659 	/*
    660 	 * some archive formats encode hard links by recording the device and
    661 	 * file serial number (inode) but copy the file anyway (multiple times)
    662 	 * to the archive. When we append, we run the risk that newly added
    663 	 * files may have the same device and inode numbers as those recorded
    664 	 * on the archive but during a previous run. If this happens, when the
    665 	 * archive is extracted we get INCORRECT hard links. We avoid this by
    666 	 * remapping the device numbers so that newly added files will never
    667 	 * use the same device number as one found on the archive. remapping
    668 	 * allows new members to safely have links among themselves. remapping
    669 	 * also avoids problems with file inode (serial number) truncations
    670 	 * when the inode number is larger than storage space in the archive
    671 	 * header. See the remap routines for more details.
    672 	 */
    673 	if ((udev = frmt->udev) && (dev_start() < 0))
    674 		return;
    675 
    676 	/*
    677 	 * reading the archive may take a long time. If verbose tell the user
    678 	 */
    679 	if (vflag) {
    680 		(void)fprintf(listf,
    681 			"%s: Reading archive to position at the end...", argv0);
    682 		vfpart = 1;
    683 	}
    684 
    685 	/*
    686 	 * step through the archive until the format says it is done
    687 	 */
    688 	while (next_head(arcn) == 0) {
    689 		/*
    690 		 * check if this file meets user specified options.
    691 		 */
    692 		if (sel_chk(arcn) != 0) {
    693 			if (rd_skip(arcn->skip + arcn->pad) == 1)
    694 				break;
    695 			continue;
    696 		}
    697 
    698 		if (uflag) {
    699 			/*
    700 			 * see if this is the newest version of this file has
    701 			 * already been seen, if so skip.
    702 			 */
    703 			if ((res = chk_ftime(arcn)) < 0)
    704 				break;
    705 			if (res > 0) {
    706 				if (rd_skip(arcn->skip + arcn->pad) == 1)
    707 					break;
    708 				continue;
    709 			}
    710 		}
    711 
    712 		/*
    713 		 * Store this device number. Device numbers seen during the
    714 		 * read phase of append will cause newly appended files with a
    715 		 * device number seen in the old part of the archive to be
    716 		 * remapped to an unused device number.
    717 		 */
    718 		if ((udev && (add_dev(arcn) < 0)) ||
    719 		    (rd_skip(arcn->skip + arcn->pad) == 1))
    720 			break;
    721 	}
    722 
    723 	/*
    724 	 * done, finish up read and get the number of bytes to back up so we
    725 	 * can add new members. The format might have used the hard link table,
    726 	 * purge it.
    727 	 */
    728 	tlen = (*frmt->end_rd)();
    729 	lnk_end();
    730 
    731 	/*
    732 	 * try to position for write, if this fails quit. if any error occurs,
    733 	 * we will refuse to write
    734 	 */
    735 	if (appnd_start(tlen) < 0)
    736 		return;
    737 
    738 	/*
    739 	 * tell the user we are done reading.
    740 	 */
    741 	if (vflag && vfpart) {
    742 		(void)safe_print("done.\n", listf);
    743 		vfpart = 0;
    744 	}
    745 
    746 	/*
    747 	 * go to the writing phase to add the new members
    748 	 */
    749 	wr_archive(arcn, 1);
    750 }
    751 
    752 /*
    753  * archive()
    754  *	write a new archive
    755  */
    756 
    757 void
    758 archive(void)
    759 {
    760 
    761 	/*
    762 	 * if we only are adding members that are newer, we need to save the
    763 	 * mod times for all files; set up for writing; pass the format any
    764 	 * options write the archive
    765 	 */
    766 	if ((uflag && (ftime_start() < 0)) || (wr_start() < 0))
    767 		return;
    768 	if ((*frmt->options)() < 0)
    769 		return;
    770 
    771 	wr_archive(&archd, 0);
    772 }
    773 
    774 /*
    775  * copy()
    776  *	copy files from one part of the file system to another. this does not
    777  *	use any archive storage. The EFFECT OF THE COPY IS THE SAME as if an
    778  *	archive was written and then extracted in the destination directory
    779  *	(except the files are forced to be under the destination directory).
    780  */
    781 
    782 void
    783 copy(void)
    784 {
    785 	ARCHD *arcn;
    786 	int res;
    787 	int fddest;
    788 	char *dest_pt;
    789 	int dlen;
    790 	int drem;
    791 	int fdsrc = -1;
    792 	struct stat sb;
    793 	char dirbuf[PAXPATHLEN+1];
    794 
    795 	arcn = &archd;
    796 	/*
    797 	 * set up the destination dir path and make sure it is a directory. We
    798 	 * make sure we have a trailing / on the destination
    799 	 */
    800 	dlen = strlcpy(dirbuf, dirptr, sizeof(dirbuf));
    801 	if (dlen >= sizeof(dirbuf) ||
    802 	    (dlen == sizeof(dirbuf) - 1 && dirbuf[dlen - 1] != '/')) {
    803 		tty_warn(1, "directory name is too long %s", dirptr);
    804 		return;
    805 	}
    806 	dest_pt = dirbuf + dlen;
    807 	if (*(dest_pt-1) != '/') {
    808 		*dest_pt++ = '/';
    809 		++dlen;
    810 	}
    811 	*dest_pt = '\0';
    812 	drem = PAXPATHLEN - dlen;
    813 
    814 	if (stat(dirptr, &sb) < 0) {
    815 		syswarn(1, errno, "Cannot access destination directory %s",
    816 			dirptr);
    817 		return;
    818 	}
    819 	if (!S_ISDIR(sb.st_mode)) {
    820 		tty_warn(1, "Destination is not a directory %s", dirptr);
    821 		return;
    822 	}
    823 
    824 	/*
    825 	 * start up the hard link table; file traversal routines and the
    826 	 * modification time and access mode database
    827 	 */
    828 	if ((lnk_start() < 0) || (ftree_start() < 0) || (dir_start() < 0))
    829 		return;
    830 
    831 	/*
    832 	 * When we are doing interactive rename, we store the mapping of names
    833 	 * so we can fix up hard links files later in the archive.
    834 	 */
    835 	if (iflag && (name_start() < 0))
    836 		return;
    837 
    838 	/*
    839 	 * set up to cp file trees
    840 	 */
    841 	cp_start();
    842 
    843 	/*
    844 	 * while there are files to archive, process them
    845 	 */
    846 	while (next_file(arcn) == 0) {
    847 		fdsrc = -1;
    848 
    849 		/*
    850 		 * check if this file meets user specified options
    851 		 */
    852 		if (sel_chk(arcn) != 0)
    853 			continue;
    854 
    855 		/*
    856 		 * if there is already a file in the destination directory with
    857 		 * the same name and it is newer, skip the one stored on the
    858 		 * archive.
    859 		 * NOTE: this test is done BEFORE name modifications as
    860 		 * specified by pax. this can be confusing to the user who
    861 		 * might expect the test to be done on an existing file AFTER
    862 		 * the name mod. In honesty the pax spec is probably flawed in
    863 		 * this respect
    864 		 */
    865 		if (uflag || Dflag) {
    866 			/*
    867 			 * create the destination name
    868 			 */
    869 			if (strlcpy(dest_pt, arcn->name + (*arcn->name == '/'),
    870 			    drem + 1) > drem) {
    871 				tty_warn(1, "Destination pathname too long %s",
    872 					arcn->name);
    873 				continue;
    874 			}
    875 
    876 			/*
    877 			 * if existing file is same age or newer skip
    878 			 */
    879 			res = lstat(dirbuf, &sb);
    880 			*dest_pt = '\0';
    881 
    882 			if (res == 0) {
    883 				if (uflag && Dflag) {
    884 					if ((arcn->sb.st_mtime<=sb.st_mtime) &&
    885 					    (arcn->sb.st_ctime<=sb.st_ctime))
    886 						continue;
    887 				} else if (Dflag) {
    888 					if (arcn->sb.st_ctime <= sb.st_ctime)
    889 						continue;
    890 				} else if (arcn->sb.st_mtime <= sb.st_mtime)
    891 					continue;
    892 			}
    893 		}
    894 
    895 		/*
    896 		 * this file is considered selected. See if this is a hard link
    897 		 * to a previous file; modify the name as requested by the
    898 		 * user; set the final destination.
    899 		 */
    900 		ftree_sel(arcn);
    901 		if ((chk_lnk(arcn) < 0) || ((res = mod_name(arcn)) < 0))
    902 			break;
    903 		if ((res > 0) || (set_dest(arcn, dirbuf, dlen) < 0)) {
    904 			/*
    905 			 * skip file, purge from link table
    906 			 */
    907 			purg_lnk(arcn);
    908 			continue;
    909 		}
    910 
    911 		/*
    912 		 * Non standard -Y and -Z flag. When the exisiting file is
    913 		 * same age or newer skip
    914 		 */
    915 		if ((Yflag || Zflag) && ((lstat(arcn->name, &sb) == 0))) {
    916 			if (Yflag && Zflag) {
    917 				if ((arcn->sb.st_mtime <= sb.st_mtime) &&
    918 				    (arcn->sb.st_ctime <= sb.st_ctime))
    919 					continue;
    920 			} else if (Yflag) {
    921 				if (arcn->sb.st_ctime <= sb.st_ctime)
    922 					continue;
    923 			} else if (arcn->sb.st_mtime <= sb.st_mtime)
    924 				continue;
    925 		}
    926 
    927 		if (vflag) {
    928 			(void)safe_print(arcn->name, listf);
    929 			vfpart = 1;
    930 		}
    931 		++flcnt;
    932 
    933 		/*
    934 		 * try to create a hard link to the src file if requested
    935 		 * but make sure we are not trying to overwrite ourselves.
    936 		 */
    937 		if (lflag)
    938 			res = cross_lnk(arcn);
    939 		else
    940 			res = chk_same(arcn);
    941 		if (res <= 0) {
    942 			if (vflag && vfpart) {
    943 				(void)putc('\n', listf);
    944 				vfpart = 0;
    945 			}
    946 			continue;
    947 		}
    948 
    949 		/*
    950 		 * have to create a new file
    951 		 */
    952 		if ((arcn->type != PAX_REG) && (arcn->type != PAX_CTG)) {
    953 			/*
    954 			 * create a link or special file
    955 			 */
    956 			if ((arcn->type == PAX_HLK) ||
    957 			    (arcn->type == PAX_HRG)) {
    958 				int payload;
    959 
    960 				res = lnk_creat(arcn, &payload);
    961 			} else {
    962 				res = node_creat(arcn);
    963 			}
    964 			if (res < 0)
    965 				purg_lnk(arcn);
    966 			if (vflag && vfpart) {
    967 				(void)putc('\n', listf);
    968 				vfpart = 0;
    969 			}
    970 			continue;
    971 		}
    972 
    973 		/*
    974 		 * have to copy a regular file to the destination directory.
    975 		 * first open source file and then create the destination file
    976 		 */
    977 		if ((fdsrc = open(arcn->org_name, O_RDONLY, 0)) < 0) {
    978 			syswarn(1, errno, "Unable to open %s to read",
    979 			    arcn->org_name);
    980 			purg_lnk(arcn);
    981 			continue;
    982 		}
    983 		if ((fddest = file_creat(arcn, 0)) < 0) {
    984 			rdfile_close(arcn, &fdsrc);
    985 			purg_lnk(arcn);
    986 			continue;
    987 		}
    988 
    989 		/*
    990 		 * copy source file data to the destination file
    991 		 */
    992 		cp_file(arcn, fdsrc, fddest);
    993 		file_close(arcn, fddest);
    994 		rdfile_close(arcn, &fdsrc);
    995 
    996 		if (vflag && vfpart) {
    997 			(void)putc('\n', listf);
    998 			vfpart = 0;
    999 		}
   1000 	}
   1001 
   1002 	/*
   1003 	 * restore directory modes and times as required; make sure all
   1004 	 * patterns were selected block off signals to avoid chance for
   1005 	 * multiple entry into the cleanup code.
   1006 	 */
   1007 	(void)sigprocmask(SIG_BLOCK, &s_mask, (sigset_t *)NULL);
   1008 	ar_close();
   1009 	proc_dir();
   1010 	ftree_chk();
   1011 }
   1012 
   1013 /*
   1014  * next_head()
   1015  *	try to find a valid header in the archive. Uses format specific
   1016  *	routines to extract the header and id the trailer. Trailers may be
   1017  *	located within a valid header or in an invalid header (the location
   1018  *	is format specific. The inhead field from the option table tells us
   1019  *	where to look for the trailer).
   1020  *	We keep reading (and resyncing) until we get enough contiguous data
   1021  *	to check for a header. If we cannot find one, we shift by a byte
   1022  *	add a new byte from the archive to the end of the buffer and try again.
   1023  *	If we get a read error, we throw out what we have (as we must have
   1024  *	contiguous data) and start over again.
   1025  *	ASSUMED: headers fit within a BLKMULT header.
   1026  * Return:
   1027  *	0 if we got a header, -1 if we are unable to ever find another one
   1028  *	(we reached the end of input, or we reached the limit on retries. see
   1029  *	the specs for rd_wrbuf() for more details)
   1030  */
   1031 
   1032 static int
   1033 next_head(ARCHD *arcn)
   1034 {
   1035 	int ret;
   1036 	char *hdend;
   1037 	int res;
   1038 	int shftsz;
   1039 	int hsz;
   1040 	int in_resync = 0;		/* set when we are in resync mode */
   1041 	int cnt = 0;			/* counter for trailer function */
   1042 	int first = 1;			/* on 1st read, EOF isn't premature. */
   1043 
   1044 	/*
   1045 	 * set up initial conditions, we want a whole frmt->hsz block as we
   1046 	 * have no data yet.
   1047 	 */
   1048 	res = hsz = frmt->hsz;
   1049 	hdend = hdbuf;
   1050 	shftsz = hsz - 1;
   1051 	for(;;) {
   1052 		/*
   1053 		 * keep looping until we get a contiguous FULL buffer
   1054 		 * (frmt->hsz is the proper size)
   1055 		 */
   1056 		for (;;) {
   1057 			if ((ret = rd_wrbuf(hdend, res)) == res)
   1058 				break;
   1059 
   1060 			/*
   1061 			 * If we read 0 bytes (EOF) from an archive when we
   1062 			 * expect to find a header, we have stepped upon
   1063 			 * an archive without the customary block of zeroes
   1064 			 * end marker.  It's just stupid to error out on
   1065 			 * them, so exit gracefully.
   1066 			 */
   1067 			if (first && ret == 0)
   1068 				return(-1);
   1069 			first = 0;
   1070 
   1071 			/*
   1072 			 * some kind of archive read problem, try to resync the
   1073 			 * storage device, better give the user the bad news.
   1074 			 */
   1075 			if ((ret == 0) || (rd_sync() < 0)) {
   1076 				tty_warn(1,
   1077 				    "Premature end of file on archive read");
   1078 				return(-1);
   1079 			}
   1080 			if (!in_resync) {
   1081 				if (act == APPND) {
   1082 					tty_warn(1,
   1083 					  "Archive I/O error, cannot continue");
   1084 					return(-1);
   1085 				}
   1086 				tty_warn(1,
   1087 				    "Archive I/O error. Trying to recover.");
   1088 				++in_resync;
   1089 			}
   1090 
   1091 			/*
   1092 			 * oh well, throw it all out and start over
   1093 			 */
   1094 			res = hsz;
   1095 			hdend = hdbuf;
   1096 		}
   1097 
   1098 		/*
   1099 		 * ok we have a contiguous buffer of the right size. Call the
   1100 		 * format read routine. If this was not a valid header and this
   1101 		 * format stores trailers outside of the header, call the
   1102 		 * format specific trailer routine to check for a trailer. We
   1103 		 * have to watch out that we do not mis-identify file data or
   1104 		 * block padding as a header or trailer. Format specific
   1105 		 * trailer functions must NOT check for the trailer while we
   1106 		 * are running in resync mode. Some trailer functions may tell
   1107 		 * us that this block cannot contain a valid header either, so
   1108 		 * we then throw out the entire block and start over.
   1109 		 */
   1110 		if ((*frmt->rd)(arcn, hdbuf) == 0)
   1111 			break;
   1112 
   1113 		if (!frmt->inhead) {
   1114 			/*
   1115 			 * this format has trailers outside of valid headers
   1116 			 */
   1117 			if ((ret = (*frmt->trail)(hdbuf,in_resync,&cnt)) == 0){
   1118 				/*
   1119 				 * valid trailer found, drain input as required
   1120 				 */
   1121 				ar_drain();
   1122 				return(-1);
   1123 			}
   1124 
   1125 			if (ret == 1) {
   1126 				/*
   1127 				 * we are in resync and we were told to throw
   1128 				 * the whole block out because none of the
   1129 				 * bytes in this block can be used to form a
   1130 				 * valid header
   1131 				 */
   1132 				res = hsz;
   1133 				hdend = hdbuf;
   1134 				continue;
   1135 			}
   1136 		}
   1137 
   1138 		/*
   1139 		 * Brute force section.
   1140 		 * not a valid header. We may be able to find a header yet. So
   1141 		 * we shift over by one byte, and set up to read one byte at a
   1142 		 * time from the archive and place it at the end of the buffer.
   1143 		 * We will keep moving byte at a time until we find a header or
   1144 		 * get a read error and have to start over.
   1145 		 */
   1146 		if (!in_resync) {
   1147 			if (act == APPND) {
   1148 				tty_warn(1,
   1149 				    "Unable to append, archive header flaw");
   1150 				return(-1);
   1151 			}
   1152 			tty_warn(1,
   1153 			    "Invalid header, starting valid header search.");
   1154 			++in_resync;
   1155 		}
   1156 		memmove(hdbuf, hdbuf+1, shftsz);
   1157 		res = 1;
   1158 		hdend = hdbuf + shftsz;
   1159 	}
   1160 
   1161 	/*
   1162 	 * ok got a valid header, check for trailer if format encodes it in the
   1163 	 * the header. NOTE: the parameters are different than trailer routines
   1164 	 * which encode trailers outside of the header!
   1165 	 */
   1166 	if (frmt->inhead && ((*frmt->subtrail)(arcn) == 0)) {
   1167 		/*
   1168 		 * valid trailer found, drain input as required
   1169 		 */
   1170 		ar_drain();
   1171 		return(-1);
   1172 	}
   1173 
   1174 	++flcnt;
   1175 	return(0);
   1176 }
   1177 
   1178 /*
   1179  * get_arc()
   1180  *	Figure out what format an archive is. Handles archive with flaws by
   1181  *	brute force searches for a legal header in any supported format. The
   1182  *	format id routines have to be careful to NOT mis-identify a format.
   1183  *	ASSUMED: headers fit within a BLKMULT header.
   1184  * Return:
   1185  *	0 if archive found -1 otherwise
   1186  */
   1187 
   1188 static int
   1189 get_arc(void)
   1190 {
   1191 	int i;
   1192 	int hdsz = 0;
   1193 	int res;
   1194 	int minhd = BLKMULT;
   1195 	char *hdend;
   1196 	int notice = 0;
   1197 
   1198 	/*
   1199 	 * find the smallest header size in all archive formats and then set up
   1200 	 * to read the archive.
   1201 	 */
   1202 	for (i = 0; ford[i] >= 0; ++i) {
   1203 		if (fsub[ford[i]].hsz < minhd)
   1204 			minhd = fsub[ford[i]].hsz;
   1205 	}
   1206 	if (rd_start() < 0)
   1207 		return(-1);
   1208 	res = BLKMULT;
   1209 	hdsz = 0;
   1210 	hdend = hdbuf;
   1211 	for(;;) {
   1212 		for (;;) {
   1213 			/*
   1214 			 * fill the buffer with at least the smallest header
   1215 			 */
   1216 			i = rd_wrbuf(hdend, res);
   1217 			if (i > 0)
   1218 				hdsz += i;
   1219 			if (hdsz >= minhd)
   1220 				break;
   1221 
   1222 			/*
   1223 			 * if we cannot recover from a read error quit
   1224 			 */
   1225 			if ((i == 0) || (rd_sync() < 0))
   1226 				goto out;
   1227 
   1228 			/*
   1229 			 * when we get an error none of the data we already
   1230 			 * have can be used to create a legal header (we just
   1231 			 * got an error in the middle), so we throw it all out
   1232 			 * and refill the buffer with fresh data.
   1233 			 */
   1234 			res = BLKMULT;
   1235 			hdsz = 0;
   1236 			hdend = hdbuf;
   1237 			if (!notice) {
   1238 				if (act == APPND)
   1239 					return(-1);
   1240 				tty_warn(1,
   1241 				    "Cannot identify format. Searching...");
   1242 				++notice;
   1243 			}
   1244 		}
   1245 
   1246 		/*
   1247 		 * we have at least the size of the smallest header in any
   1248 		 * archive format. Look to see if we have a match. The array
   1249 		 * ford[] is used to specify the header id order to reduce the
   1250 		 * chance of incorrectly id'ing a valid header (some formats
   1251 		 * may be subsets of each other and the order would then be
   1252 		 * important).
   1253 		 */
   1254 		for (i = 0; ford[i] >= 0; ++i) {
   1255 			if ((*fsub[ford[i]].id)(hdbuf, hdsz) < 0)
   1256 				continue;
   1257 			frmt = &(fsub[ford[i]]);
   1258 			/*
   1259 			 * yuck, to avoid slow special case code in the extract
   1260 			 * routines, just push this header back as if it was
   1261 			 * not seen. We have left extra space at start of the
   1262 			 * buffer for this purpose. This is a bit ugly, but
   1263 			 * adding all the special case code is far worse.
   1264 			 */
   1265 			pback(hdbuf, hdsz);
   1266 			return(0);
   1267 		}
   1268 
   1269 		/*
   1270 		 * We have a flawed archive, no match. we start searching, but
   1271 		 * we never allow additions to flawed archives
   1272 		 */
   1273 		if (!notice) {
   1274 			if (act == APPND)
   1275 				return(-1);
   1276 			tty_warn(1, "Cannot identify format. Searching...");
   1277 			++notice;
   1278 		}
   1279 
   1280 		/*
   1281 		 * brute force search for a header that we can id.
   1282 		 * we shift through byte at a time. this is slow, but we cannot
   1283 		 * determine the nature of the flaw in the archive in a
   1284 		 * portable manner
   1285 		 */
   1286 		if (--hdsz > 0) {
   1287 			memmove(hdbuf, hdbuf+1, hdsz);
   1288 			res = BLKMULT - hdsz;
   1289 			hdend = hdbuf + hdsz;
   1290 		} else {
   1291 			res = BLKMULT;
   1292 			hdend = hdbuf;
   1293 			hdsz = 0;
   1294 		}
   1295 	}
   1296 
   1297     out:
   1298 	/*
   1299 	 * we cannot find a header, bow, apologize and quit
   1300 	 */
   1301 	tty_warn(1, "Sorry, unable to determine archive format.");
   1302 	return(-1);
   1303 }
   1304