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