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