Home | History | Annotate | Line # | Download | only in pax
file_subs.c revision 1.41
      1 /*	$NetBSD: file_subs.c,v 1.41 2004/02/13 23:10:14 matt 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[] = "@(#)file_subs.c	8.1 (Berkeley) 5/31/93";
     44 #else
     45 __RCSID("$NetBSD: file_subs.c,v 1.41 2004/02/13 23:10:14 matt 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 <unistd.h>
     53 #include <sys/param.h>
     54 #include <fcntl.h>
     55 #include <string.h>
     56 #include <stdio.h>
     57 #include <ctype.h>
     58 #include <errno.h>
     59 #include <sys/uio.h>
     60 #include <stdlib.h>
     61 #include "pax.h"
     62 #include "extern.h"
     63 #include "options.h"
     64 
     65 char *xtmp_name;
     66 
     67 static int
     68 mk_link(char *,struct stat *,char *, int);
     69 
     70 /*
     71  * routines that deal with file operations such as: creating, removing;
     72  * and setting access modes, uid/gid and times of files
     73  */
     74 
     75 #define FILEBITS		(S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
     76 #define SETBITS			(S_ISUID | S_ISGID)
     77 #define ABITS			(FILEBITS | SETBITS)
     78 
     79 /*
     80  * file_creat()
     81  *	Create and open a file.
     82  * Return:
     83  *	file descriptor or -1 for failure
     84  */
     85 
     86 int
     87 file_creat(ARCHD *arcn)
     88 {
     89 	int fd = -1;
     90 	int oerrno;
     91 
     92 	/*
     93 	 * Create a temporary file name so that the file doesn't have partial
     94 	 * contents while restoring.
     95 	 */
     96 	arcn->tmp_name = malloc(arcn->nlen + 8);
     97 	if (arcn->tmp_name == NULL) {
     98 		syswarn(1, errno, "Cannot malloc %d bytes", arcn->nlen + 8);
     99 		return(-1);
    100 	}
    101 	if (xtmp_name)
    102 		abort();
    103 	xtmp_name = arcn->tmp_name;
    104 
    105 	for (;;) {
    106 		/*
    107 		 * try to create the temporary file we use to restore the
    108 		 * contents info.  if this fails, keep checking all the nodes
    109 		 * in the path until chk_path() finds that it cannot fix
    110 		 * anything further.  if that happens we just give up.
    111 		 */
    112 		(void)snprintf(arcn->tmp_name, arcn->nlen + 8, "%s.XXXXXX",
    113 		    arcn->name);
    114 		fd = mkstemp(arcn->tmp_name);
    115 		if (fd >= 0)
    116 			break;
    117 		oerrno = errno;
    118 		if (nodirs || chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
    119 			(void)fflush(listf);
    120 			syswarn(1, oerrno, "Cannot create %s", arcn->tmp_name);
    121 			free(arcn->tmp_name);
    122 			arcn->tmp_name = NULL;
    123 			return(-1);
    124 		}
    125 	}
    126 	return(fd);
    127 }
    128 
    129 /*
    130  * file_close()
    131  *	Close file descriptor to a file just created by pax. Sets modes,
    132  *	ownership and times as required.
    133  * Return:
    134  *	0 for success, -1 for failure
    135  */
    136 
    137 void
    138 file_close(ARCHD *arcn, int fd)
    139 {
    140 	int res = 0;
    141 
    142 	if (fd < 0)
    143 		return;
    144 	if (close(fd) < 0)
    145 		syswarn(0, errno, "Cannot close file descriptor on %s",
    146 		    arcn->tmp_name);
    147 
    148 	/*
    149 	 * set owner/groups first as this may strip off mode bits we want
    150 	 * then set file permission modes. Then set file access and
    151 	 * modification times.
    152 	 */
    153 	if (pids)
    154 		res = set_ids(arcn->tmp_name, arcn->sb.st_uid, arcn->sb.st_gid);
    155 
    156 	/*
    157 	 * IMPORTANT SECURITY NOTE:
    158 	 * if not preserving mode or we cannot set uid/gid, then PROHIBIT
    159 	 * set uid/gid bits but restore the file modes (since mkstemp doesn't).
    160 	 */
    161 	if (!pmode || res)
    162 		arcn->sb.st_mode &= ~(SETBITS);
    163 	if (pmode)
    164 		set_pmode(arcn->tmp_name, arcn->sb.st_mode);
    165 	else
    166 		set_pmode(arcn->tmp_name, arcn->sb.st_mode & FILEBITS);
    167 	if (patime || pmtime)
    168 		set_ftime(arcn->tmp_name, arcn->sb.st_mtime, arcn->sb.st_atime, 0);
    169 #if HAVE_STRUCT_STAT_ST_FLAGS
    170 	if (pfflags && arcn->type != PAX_SLK)
    171 		set_chflags(arcn->tmp_name, arcn->sb.st_flags);
    172 #endif
    173 
    174 	/*
    175 	 * Finally, now the temp file is fully instantiated rename it to
    176 	 * the desired file name.
    177 	 */
    178 	if (rename(arcn->tmp_name, arcn->name) < 0) {
    179 		syswarn(0, errno, "Cannot rename %s to %s",
    180 		    arcn->tmp_name, arcn->name);
    181 		(void)unlink(arcn->tmp_name);
    182 	}
    183 
    184 	free(arcn->tmp_name);
    185 	arcn->tmp_name = NULL;
    186 	xtmp_name = NULL;
    187 }
    188 
    189 /*
    190  * lnk_creat()
    191  *	Create a hard link to arcn->ln_name from arcn->name. arcn->ln_name
    192  *	must exist;
    193  * Return:
    194  *	0 if ok, -1 otherwise
    195  */
    196 
    197 int
    198 lnk_creat(ARCHD *arcn)
    199 {
    200 	struct stat sb;
    201 
    202 	/*
    203 	 * we may be running as root, so we have to be sure that link target
    204 	 * is not a directory, so we lstat and check
    205 	 */
    206 	if (lstat(arcn->ln_name, &sb) < 0) {
    207 		syswarn(1, errno, "Cannot link to %s from %s", arcn->ln_name,
    208 		    arcn->name);
    209 		return(-1);
    210 	}
    211 
    212 	if (S_ISDIR(sb.st_mode)) {
    213 		tty_warn(1, "A hard link to the directory %s is not allowed",
    214 		    arcn->ln_name);
    215 		return(-1);
    216 	}
    217 
    218 	return(mk_link(arcn->ln_name, &sb, arcn->name, 0));
    219 }
    220 
    221 /*
    222  * cross_lnk()
    223  *	Create a hard link to arcn->org_name from arcn->name. Only used in copy
    224  *	with the -l flag. No warning or error if this does not succeed (we will
    225  *	then just create the file)
    226  * Return:
    227  *	1 if copy() should try to create this file node
    228  *	0 if cross_lnk() ok, -1 for fatal flaw (like linking to self).
    229  */
    230 
    231 int
    232 cross_lnk(ARCHD *arcn)
    233 {
    234 	/*
    235 	 * try to make a link to original file (-l flag in copy mode). make
    236 	 * sure we do not try to link to directories in case we are running as
    237 	 * root (and it might succeed).
    238 	 */
    239 	if (arcn->type == PAX_DIR)
    240 		return(1);
    241 	return(mk_link(arcn->org_name, &(arcn->sb), arcn->name, 1));
    242 }
    243 
    244 /*
    245  * chk_same()
    246  *	In copy mode if we are not trying to make hard links between the src
    247  *	and destinations, make sure we are not going to overwrite ourselves by
    248  *	accident. This slows things down a little, but we have to protect all
    249  *	those people who make typing errors.
    250  * Return:
    251  *	1 the target does not exist, go ahead and copy
    252  *	0 skip it file exists (-k) or may be the same as source file
    253  */
    254 
    255 int
    256 chk_same(ARCHD *arcn)
    257 {
    258 	struct stat sb;
    259 
    260 	/*
    261 	 * if file does not exist, return. if file exists and -k, skip it
    262 	 * quietly
    263 	 */
    264 	if (lstat(arcn->name, &sb) < 0)
    265 		return(1);
    266 	if (kflag)
    267 		return(0);
    268 
    269 	/*
    270 	 * better make sure the user does not have src == dest by mistake
    271 	 */
    272 	if ((arcn->sb.st_dev == sb.st_dev) && (arcn->sb.st_ino == sb.st_ino)) {
    273 		tty_warn(1, "Unable to copy %s, file would overwrite itself",
    274 		    arcn->name);
    275 		return(0);
    276 	}
    277 	return(1);
    278 }
    279 
    280 /*
    281  * mk_link()
    282  *	try to make a hard link between two files. if ign set, we do not
    283  *	complain.
    284  * Return:
    285  *	0 if successful (or we are done with this file but no error, such as
    286  *	finding the from file exists and the user has set -k).
    287  *	1 when ign was set to indicates we could not make the link but we
    288  *	should try to copy/extract the file as that might work (and is an
    289  *	allowed option). -1 an error occurred.
    290  */
    291 
    292 static int
    293 mk_link(char *to, struct stat *to_sb, char *from, int ign)
    294 {
    295 	struct stat sb;
    296 	int oerrno;
    297 
    298 	/*
    299 	 * if from file exists, it has to be unlinked to make the link. If the
    300 	 * file exists and -k is set, skip it quietly
    301 	 */
    302 	if (lstat(from, &sb) == 0) {
    303 		if (kflag)
    304 			return(0);
    305 
    306 		/*
    307 		 * make sure it is not the same file, protect the user
    308 		 */
    309 		if ((to_sb->st_dev==sb.st_dev)&&(to_sb->st_ino == sb.st_ino)) {
    310 			tty_warn(1, "Cannot link file %s to itself", to);
    311 			return(-1);
    312 		}
    313 
    314 		/*
    315 		 * try to get rid of the file, based on the type
    316 		 */
    317 		if (S_ISDIR(sb.st_mode)) {
    318 			if (rmdir(from) < 0) {
    319 				syswarn(1, errno, "Cannot remove %s", from);
    320 				return(-1);
    321 			}
    322 		} else if (unlink(from) < 0) {
    323 			if (!ign) {
    324 				syswarn(1, errno, "Cannot remove %s", from);
    325 				return(-1);
    326 			}
    327 			return(1);
    328 		}
    329 	}
    330 
    331 	/*
    332 	 * from file is gone (or did not exist), try to make the hard link.
    333 	 * if it fails, check the path and try it again (if chk_path() says to
    334 	 * try again)
    335 	 */
    336 	for (;;) {
    337 		if (link(to, from) == 0)
    338 			break;
    339 		oerrno = errno;
    340 		if (chk_path(from, to_sb->st_uid, to_sb->st_gid) == 0)
    341 			continue;
    342 		if (!ign) {
    343 			syswarn(1, oerrno, "Cannot link to %s from %s", to,
    344 			    from);
    345 			return(-1);
    346 		}
    347 		return(1);
    348 	}
    349 
    350 	/*
    351 	 * all right the link was made
    352 	 */
    353 	return(0);
    354 }
    355 
    356 /*
    357  * node_creat()
    358  *	create an entry in the file system (other than a file or hard link).
    359  *	If successful, sets uid/gid modes and times as required.
    360  * Return:
    361  *	0 if ok, -1 otherwise
    362  */
    363 
    364 int
    365 node_creat(ARCHD *arcn)
    366 {
    367 	int res;
    368 	int ign = 0;
    369 	int oerrno;
    370 	int pass = 0;
    371 	mode_t file_mode;
    372 	struct stat sb;
    373 	char target[MAXPATHLEN];
    374 	char *nm = arcn->name;
    375 	int len;
    376 
    377 	/*
    378 	 * create node based on type, if that fails try to unlink the node and
    379 	 * try again. finally check the path and try again. As noted in the
    380 	 * file and link creation routines, this method seems to exhibit the
    381 	 * best performance in general use workloads.
    382 	 */
    383 	file_mode = arcn->sb.st_mode & FILEBITS;
    384 
    385 	for (;;) {
    386 		switch(arcn->type) {
    387 		case PAX_DIR:
    388 			/*
    389 			 * If -h (or -L) was given in tar-mode, follow the
    390 			 * potential symlink chain before trying to create the
    391 			 * directory.
    392 			 */
    393 			if (strcmp(NM_TAR, argv0) == 0 && Lflag) {
    394 				while (lstat(nm, &sb) == 0 &&
    395 				    S_ISLNK(sb.st_mode)) {
    396 					len = readlink(nm, target,
    397 					    sizeof target - 1);
    398 					if (len == -1) {
    399 						syswarn(0, errno,
    400 						   "cannot follow symlink %s in chain for %s",
    401 						    nm, arcn->name);
    402 						res = -1;
    403 						goto badlink;
    404 					}
    405 					target[len] = '\0';
    406 					nm = target;
    407 				}
    408 			}
    409 			res = mkdir(nm, file_mode);
    410 
    411 badlink:
    412 			if (ign)
    413 				res = 0;
    414 			break;
    415 		case PAX_CHR:
    416 			file_mode |= S_IFCHR;
    417 			res = mknod(nm, file_mode, arcn->sb.st_rdev);
    418 			break;
    419 		case PAX_BLK:
    420 			file_mode |= S_IFBLK;
    421 			res = mknod(nm, file_mode, arcn->sb.st_rdev);
    422 			break;
    423 		case PAX_FIF:
    424 			res = mkfifo(nm, file_mode);
    425 			break;
    426 		case PAX_SCK:
    427 			/*
    428 			 * Skip sockets, operation has no meaning under BSD
    429 			 */
    430 			tty_warn(0,
    431 			    "%s skipped. Sockets cannot be copied or extracted",
    432 			    nm);
    433 			return(-1);
    434 		case PAX_SLK:
    435 			res = symlink(arcn->ln_name, nm);
    436 			break;
    437 		case PAX_CTG:
    438 		case PAX_HLK:
    439 		case PAX_HRG:
    440 		case PAX_REG:
    441 		default:
    442 			/*
    443 			 * we should never get here
    444 			 */
    445 			tty_warn(0, "%s has an unknown file type, skipping",
    446 			    nm);
    447 			return(-1);
    448 		}
    449 
    450 		/*
    451 		 * if we were able to create the node break out of the loop,
    452 		 * otherwise try to unlink the node and try again. if that
    453 		 * fails check the full path and try a final time.
    454 		 */
    455 		if (res == 0)
    456 			break;
    457 
    458 		/*
    459 		 * we failed to make the node
    460 		 */
    461 		oerrno = errno;
    462 		if ((ign = unlnk_exist(nm, arcn->type)) < 0)
    463 			return(-1);
    464 
    465 		if (++pass <= 1)
    466 			continue;
    467 
    468 		if (nodirs || chk_path(nm,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
    469 			syswarn(1, oerrno, "Cannot create %s", nm);
    470 			return(-1);
    471 		}
    472 	}
    473 
    474 	/*
    475 	 * we were able to create the node. set uid/gid, modes and times
    476 	 */
    477 	if (pids)
    478 		res = set_ids(nm, arcn->sb.st_uid, arcn->sb.st_gid);
    479 	else
    480 		res = 0;
    481 
    482 	/*
    483 	 * IMPORTANT SECURITY NOTE:
    484 	 * if not preserving mode or we cannot set uid/gid, then PROHIBIT any
    485 	 * set uid/gid bits
    486 	 */
    487 	if (!pmode || res)
    488 		arcn->sb.st_mode &= ~(SETBITS);
    489 	if (pmode)
    490 		set_pmode(arcn->name, arcn->sb.st_mode);
    491 
    492 	if (arcn->type == PAX_DIR && strcmp(NM_CPIO, argv0) != 0) {
    493 		/*
    494 		 * Dirs must be processed again at end of extract to set times
    495 		 * and modes to agree with those stored in the archive. However
    496 		 * to allow extract to continue, we may have to also set owner
    497 		 * rights. This allows nodes in the archive that are children
    498 		 * of this directory to be extracted without failure. Both time
    499 		 * and modes will be fixed after the entire archive is read and
    500 		 * before pax exits.
    501 		 */
    502 		if (access(nm, R_OK | W_OK | X_OK) < 0) {
    503 			if (lstat(nm, &sb) < 0) {
    504 				syswarn(0, errno,"Cannot access %s (stat)",
    505 				    arcn->name);
    506 				set_pmode(nm,file_mode | S_IRWXU);
    507 			} else {
    508 				/*
    509 				 * We have to add rights to the dir, so we make
    510 				 * sure to restore the mode. The mode must be
    511 				 * restored AS CREATED and not as stored if
    512 				 * pmode is not set.
    513 				 */
    514 				set_pmode(nm,
    515 				    ((sb.st_mode & FILEBITS) | S_IRWXU));
    516 				if (!pmode)
    517 					arcn->sb.st_mode = sb.st_mode;
    518 			}
    519 
    520 			/*
    521 			 * we have to force the mode to what was set here,
    522 			 * since we changed it from the default as created.
    523 			 */
    524 			add_dir(nm, arcn->nlen, &(arcn->sb), 1);
    525 		} else if (pmode || patime || pmtime)
    526 			add_dir(nm, arcn->nlen, &(arcn->sb), 0);
    527 	}
    528 
    529 #if HAVE_LUTIMES
    530 	if (patime || pmtime)
    531 #else
    532 	if ((patime || pmtime) && arcn->type != PAX_SLK)
    533 #endif
    534 		set_ftime(arcn->name, arcn->sb.st_mtime, arcn->sb.st_atime, 0);
    535 
    536 #if HAVE_STRUCT_STAT_ST_FLAGS
    537 	if (pfflags && arcn->type != PAX_SLK)
    538 		set_chflags(arcn->name, arcn->sb.st_flags);
    539 #endif
    540 	return(0);
    541 }
    542 
    543 /*
    544  * unlnk_exist()
    545  *	Remove node from file system with the specified name. We pass the type
    546  *	of the node that is going to replace it. When we try to create a
    547  *	directory and find that it already exists, we allow processing to
    548  *	continue as proper modes etc will always be set for it later on.
    549  * Return:
    550  *	0 is ok to proceed, no file with the specified name exists
    551  *	-1 we were unable to remove the node, or we should not remove it (-k)
    552  *	1 we found a directory and we were going to create a directory.
    553  */
    554 
    555 int
    556 unlnk_exist(char *name, int type)
    557 {
    558 	struct stat sb;
    559 
    560 	/*
    561 	 * the file does not exist, or -k we are done
    562 	 */
    563 	if (lstat(name, &sb) < 0)
    564 		return(0);
    565 	if (kflag)
    566 		return(-1);
    567 
    568 	if (S_ISDIR(sb.st_mode)) {
    569 		/*
    570 		 * try to remove a directory, if it fails and we were going to
    571 		 * create a directory anyway, tell the caller (return a 1)
    572 		 */
    573 		if (rmdir(name) < 0) {
    574 			if (type == PAX_DIR)
    575 				return(1);
    576 			syswarn(1, errno, "Cannot remove directory %s", name);
    577 			return(-1);
    578 		}
    579 		return(0);
    580 	}
    581 
    582 	/*
    583 	 * try to get rid of all non-directory type nodes
    584 	 */
    585 	if (unlink(name) < 0) {
    586 		(void)fflush(listf);
    587 		syswarn(1, errno, "Cannot unlink %s", name);
    588 		return(-1);
    589 	}
    590 	return(0);
    591 }
    592 
    593 /*
    594  * chk_path()
    595  *	We were trying to create some kind of node in the file system and it
    596  *	failed. chk_path() makes sure the path up to the node exists and is
    597  *	writable. When we have to create a directory that is missing along the
    598  *	path somewhere, the directory we create will be set to the same
    599  *	uid/gid as the file has (when uid and gid are being preserved).
    600  *	NOTE: this routine is a real performance loss. It is only used as a
    601  *	last resort when trying to create entries in the file system.
    602  * Return:
    603  *	-1 when it could find nothing it is allowed to fix.
    604  *	0 otherwise
    605  */
    606 
    607 int
    608 chk_path( char *name, uid_t st_uid, gid_t st_gid)
    609 {
    610 	char *spt = name;
    611 	struct stat sb;
    612 	int retval = -1;
    613 
    614 	/*
    615 	 * watch out for paths with nodes stored directly in / (e.g. /bozo)
    616 	 */
    617 	if (*spt == '/')
    618 		++spt;
    619 
    620 	for(;;) {
    621 		/*
    622 		 * work forward from the first / and check each part of
    623 		 * the path
    624 		 */
    625 		spt = strchr(spt, '/');
    626 		if (spt == NULL)
    627 			break;
    628 		*spt = '\0';
    629 
    630 		/*
    631 		 * if it exists we assume it is a directory, it is not within
    632 		 * the spec (at least it seems to read that way) to alter the
    633 		 * file system for nodes NOT EXPLICITLY stored on the archive.
    634 		 * If that assumption is changed, you would test the node here
    635 		 * and figure out how to get rid of it (probably like some
    636 		 * recursive unlink()) or fix up the directory permissions if
    637 		 * required (do an access()).
    638 		 */
    639 		if (lstat(name, &sb) == 0) {
    640 			*(spt++) = '/';
    641 			continue;
    642 		}
    643 
    644 		/*
    645 		 * the path fails at this point, see if we can create the
    646 		 * needed directory and continue on
    647 		 */
    648 		if (mkdir(name, S_IRWXU | S_IRWXG | S_IRWXO) < 0) {
    649 			*spt = '/';
    650 			retval = -1;
    651 			break;
    652 		}
    653 
    654 		/*
    655 		 * we were able to create the directory. We will tell the
    656 		 * caller that we found something to fix, and it is ok to try
    657 		 * and create the node again.
    658 		 */
    659 		retval = 0;
    660 		if (pids)
    661 			(void)set_ids(name, st_uid, st_gid);
    662 
    663 		/*
    664 		 * make sure the user doesn't have some strange umask that
    665 		 * causes this newly created directory to be unusable. We fix
    666 		 * the modes and restore them back to the creation default at
    667 		 * the end of pax
    668 		 */
    669 		if ((access(name, R_OK | W_OK | X_OK) < 0) &&
    670 		    (lstat(name, &sb) == 0)) {
    671 			set_pmode(name, ((sb.st_mode & FILEBITS) | S_IRWXU));
    672 			add_dir(name, spt - name, &sb, 1);
    673 		}
    674 		*(spt++) = '/';
    675 		continue;
    676 	}
    677 	return(retval);
    678 }
    679 
    680 /*
    681  * set_ftime()
    682  *	Set the access time and modification time for a named file. If frc
    683  *	is non-zero we force these times to be set even if the user did not
    684  *	request access and/or modification time preservation (this is also
    685  *	used by -t to reset access times).
    686  *	When ign is zero, only those times the user has asked for are set, the
    687  *	other ones are left alone. We do not assume the un-documented feature
    688  *	of many utimes() implementations that consider a 0 time value as a do
    689  *	not set request.
    690  */
    691 
    692 void
    693 set_ftime(char *fnm, time_t mtime, time_t atime, int frc)
    694 {
    695 	struct timeval tv[2];
    696 	struct stat sb;
    697 
    698 	tv[0].tv_sec = (long)atime;
    699 	tv[0].tv_usec = 0;
    700 	tv[1].tv_sec = (long)mtime;
    701 	tv[1].tv_usec = 0;
    702 	if (!frc && (!patime || !pmtime)) {
    703 		/*
    704 		 * if we are not forcing, only set those times the user wants
    705 		 * set. We get the current values of the times if we need them.
    706 		 */
    707 		if (lstat(fnm, &sb) == 0) {
    708 #ifdef BSD4_4
    709 			if (!patime)
    710 				TIMESPEC_TO_TIMEVAL(&tv[0], &sb.st_atimespec);
    711 			if (!pmtime)
    712 				TIMESPEC_TO_TIMEVAL(&tv[1], &sb.st_mtimespec);
    713 #else
    714 			if (!patime)
    715 				tv[0].tv_sec = sb.st_atime;
    716 			if (!pmtime)
    717 				tv[1].tv_sec = sb.st_mtime;
    718 #endif
    719 		} else
    720 			syswarn(0, errno, "Cannot obtain file stats %s", fnm);
    721 	}
    722 
    723 	/*
    724 	 * set the times
    725 	 */
    726 #if HAVE_LUTIMES
    727 	if (lutimes(fnm, tv))
    728 #else
    729 	if (utimes(fnm, tv))
    730 #endif
    731 		syswarn(1, errno, "Access/modification time set failed on: %s",
    732 		    fnm);
    733 	return;
    734 }
    735 
    736 /*
    737  * set_ids()
    738  *	set the uid and gid of a file system node
    739  * Return:
    740  *	0 when set, -1 on failure
    741  */
    742 
    743 int
    744 set_ids(char *fnm, uid_t uid, gid_t gid)
    745 {
    746 	if (geteuid() == 0)
    747 		if (lchown(fnm, uid, gid)) {
    748 			(void)fflush(listf);
    749 			syswarn(1, errno, "Cannot set file uid/gid of %s",
    750 			    fnm);
    751 			return(-1);
    752 		}
    753 	return(0);
    754 }
    755 
    756 /*
    757  * set_pmode()
    758  *	Set file access mode
    759  */
    760 
    761 void
    762 set_pmode(char *fnm, mode_t mode)
    763 {
    764 	mode &= ABITS;
    765 	if (lchmod(fnm, mode)) {
    766 		(void)fflush(listf);
    767 		syswarn(1, errno, "Cannot set permissions on %s", fnm);
    768 	}
    769 	return;
    770 }
    771 
    772 /*
    773  * set_chflags()
    774  *	Set 4.4BSD file flags
    775  */
    776 void
    777 set_chflags(char *fnm, u_int32_t flags)
    778 {
    779 
    780 #if 0
    781 	if (chflags(fnm, flags) < 0 && errno != EOPNOTSUPP)
    782 		syswarn(1, errno, "Cannot set file flags on %s", fnm);
    783 #endif
    784 	return;
    785 }
    786 
    787 /*
    788  * file_write()
    789  *	Write/copy a file (during copy or archive extract). This routine knows
    790  *	how to copy files with lseek holes in it. (Which are read as file
    791  *	blocks containing all 0's but do not have any file blocks associated
    792  *	with the data). Typical examples of these are files created by dbm
    793  *	variants (.pag files). While the file size of these files are huge, the
    794  *	actual storage is quite small (the files are sparse). The problem is
    795  *	the holes read as all zeros so are probably stored on the archive that
    796  *	way (there is no way to determine if the file block is really a hole,
    797  *	we only know that a file block of all zero's can be a hole).
    798  *	At this writing, no major archive format knows how to archive files
    799  *	with holes. However, on extraction (or during copy, -rw) we have to
    800  *	deal with these files. Without detecting the holes, the files can
    801  *	consume a lot of file space if just written to disk. This replacement
    802  *	for write when passed the basic allocation size of a file system block,
    803  *	uses lseek whenever it detects the input data is all 0 within that
    804  *	file block. In more detail, the strategy is as follows:
    805  *	While the input is all zero keep doing an lseek. Keep track of when we
    806  *	pass over file block boundaries. Only write when we hit a non zero
    807  *	input. once we have written a file block, we continue to write it to
    808  *	the end (we stop looking at the input). When we reach the start of the
    809  *	next file block, start checking for zero blocks again. Working on file
    810  *	block boundaries significantly reduces the overhead when copying files
    811  *	that are NOT very sparse. This overhead (when compared to a write) is
    812  *	almost below the measurement resolution on many systems. Without it,
    813  *	files with holes cannot be safely copied. It does has a side effect as
    814  *	it can put holes into files that did not have them before, but that is
    815  *	not a problem since the file contents are unchanged (in fact it saves
    816  *	file space). (Except on paging files for diskless clients. But since we
    817  *	cannot determine one of those file from here, we ignore them). If this
    818  *	ever ends up on a system where CTG files are supported and the holes
    819  *	are not desired, just do a conditional test in those routines that
    820  *	call file_write() and have it call write() instead. BEFORE CLOSING THE
    821  *	FILE, make sure to call file_flush() when the last write finishes with
    822  *	an empty block. A lot of file systems will not create an lseek hole at
    823  *	the end. In this case we drop a single 0 at the end to force the
    824  *	trailing 0's in the file.
    825  *	---Parameters---
    826  *	rem: how many bytes left in this file system block
    827  *	isempt: have we written to the file block yet (is it empty)
    828  *	sz: basic file block allocation size
    829  *	cnt: number of bytes on this write
    830  *	str: buffer to write
    831  * Return:
    832  *	number of bytes written, -1 on write (or lseek) error.
    833  */
    834 
    835 int
    836 file_write(int fd, char *str, int cnt, int *rem, int *isempt, int sz,
    837 	char *name)
    838 {
    839 	char *pt;
    840 	char *end;
    841 	int wcnt;
    842 	char *st = str;
    843 	char **strp;
    844 
    845 	/*
    846 	 * while we have data to process
    847 	 */
    848 	while (cnt) {
    849 		if (!*rem) {
    850 			/*
    851 			 * We are now at the start of file system block again
    852 			 * (or what we think one is...). start looking for
    853 			 * empty blocks again
    854 			 */
    855 			*isempt = 1;
    856 			*rem = sz;
    857 		}
    858 
    859 		/*
    860 		 * only examine up to the end of the current file block or
    861 		 * remaining characters to write, whatever is smaller
    862 		 */
    863 		wcnt = MIN(cnt, *rem);
    864 		cnt -= wcnt;
    865 		*rem -= wcnt;
    866 		if (*isempt) {
    867 			/*
    868 			 * have not written to this block yet, so we keep
    869 			 * looking for zero's
    870 			 */
    871 			pt = st;
    872 			end = st + wcnt;
    873 
    874 			/*
    875 			 * look for a zero filled buffer
    876 			 */
    877 			while ((pt < end) && (*pt == '\0'))
    878 				++pt;
    879 
    880 			if (pt == end) {
    881 				/*
    882 				 * skip, buf is empty so far
    883 				 */
    884 				if (fd > -1 &&
    885 				    lseek(fd, (off_t)wcnt, SEEK_CUR) < 0) {
    886 					syswarn(1, errno, "File seek on %s",
    887 					    name);
    888 					return(-1);
    889 				}
    890 				st = pt;
    891 				continue;
    892 			}
    893 			/*
    894 			 * drat, the buf is not zero filled
    895 			 */
    896 			*isempt = 0;
    897 		}
    898 
    899 		/*
    900 		 * have non-zero data in this file system block, have to write
    901 		 */
    902 		switch (fd) {
    903 		case -1:
    904 			strp = &gnu_name_string;
    905 			break;
    906 		case -2:
    907 			strp = &gnu_link_string;
    908 			break;
    909 		default:
    910 			strp = NULL;
    911 			break;
    912 		}
    913 		if (strp) {
    914 			if (*strp)
    915 				err(1, "WARNING! Major Internal Error! GNU hack Failing!");
    916 			*strp = malloc(wcnt + 1);
    917 			if (*strp == NULL) {
    918 				tty_warn(1, "Out of memory");
    919 				return(-1);
    920 			}
    921 			strlcpy(*strp, st, wcnt);
    922 			break;
    923 		} else if (xwrite(fd, st, wcnt) != wcnt) {
    924 			syswarn(1, errno, "Failed write to file %s", name);
    925 			return(-1);
    926 		}
    927 		st += wcnt;
    928 	}
    929 	return(st - str);
    930 }
    931 
    932 /*
    933  * file_flush()
    934  *	when the last file block in a file is zero, many file systems will not
    935  *	let us create a hole at the end. To get the last block with zeros, we
    936  *	write the last BYTE with a zero (back up one byte and write a zero).
    937  */
    938 
    939 void
    940 file_flush(int fd, char *fname, int isempt)
    941 {
    942 	static char blnk[] = "\0";
    943 
    944 	/*
    945 	 * silly test, but make sure we are only called when the last block is
    946 	 * filled with all zeros.
    947 	 */
    948 	if (!isempt)
    949 		return;
    950 
    951 	/*
    952 	 * move back one byte and write a zero
    953 	 */
    954 	if (lseek(fd, (off_t)-1, SEEK_CUR) < 0) {
    955 		syswarn(1, errno, "Failed seek on file %s", fname);
    956 		return;
    957 	}
    958 
    959 	if (write_with_restart(fd, blnk, 1) < 0)
    960 		syswarn(1, errno, "Failed write to file %s", fname);
    961 	return;
    962 }
    963 
    964 /*
    965  * rdfile_close()
    966  *	close a file we have been reading (to copy or archive). If we have to
    967  *	reset access time (tflag) do so (the times are stored in arcn).
    968  */
    969 
    970 void
    971 rdfile_close(ARCHD *arcn, int *fd)
    972 {
    973 	/*
    974 	 * make sure the file is open
    975 	 */
    976 	if (*fd < 0)
    977 		return;
    978 
    979 	(void)close(*fd);
    980 	*fd = -1;
    981 	if (!tflag)
    982 		return;
    983 
    984 	/*
    985 	 * user wants last access time reset
    986 	 */
    987 	set_ftime(arcn->org_name, arcn->sb.st_mtime, arcn->sb.st_atime, 1);
    988 	return;
    989 }
    990 
    991 /*
    992  * set_crc()
    993  *	read a file to calculate its crc. This is a real drag. Archive formats
    994  *	that have this, end up reading the file twice (we have to write the
    995  *	header WITH the crc before writing the file contents. Oh well...
    996  * Return:
    997  *	0 if was able to calculate the crc, -1 otherwise
    998  */
    999 
   1000 int
   1001 set_crc(ARCHD *arcn, int fd)
   1002 {
   1003 	int i;
   1004 	int res;
   1005 	off_t cpcnt = 0L;
   1006 	u_long size;
   1007 	unsigned long crc = 0L;
   1008 	char tbuf[FILEBLK];
   1009 	struct stat sb;
   1010 
   1011 	if (fd < 0) {
   1012 		/*
   1013 		 * hmm, no fd, should never happen. well no crc then.
   1014 		 */
   1015 		arcn->crc = 0L;
   1016 		return(0);
   1017 	}
   1018 
   1019 	if ((size = (u_long)arcn->sb.st_blksize) > (u_long)sizeof(tbuf))
   1020 		size = (u_long)sizeof(tbuf);
   1021 
   1022 	/*
   1023 	 * read all the bytes we think that there are in the file. If the user
   1024 	 * is trying to archive an active file, forget this file.
   1025 	 */
   1026 	for(;;) {
   1027 		if ((res = read(fd, tbuf, size)) <= 0)
   1028 			break;
   1029 		cpcnt += res;
   1030 		for (i = 0; i < res; ++i)
   1031 			crc += (tbuf[i] & 0xff);
   1032 	}
   1033 
   1034 	/*
   1035 	 * safety check. we want to avoid archiving files that are active as
   1036 	 * they can create inconsistant archive copies.
   1037 	 */
   1038 	if (cpcnt != arcn->sb.st_size)
   1039 		tty_warn(1, "File changed size %s", arcn->org_name);
   1040 	else if (fstat(fd, &sb) < 0)
   1041 		syswarn(1, errno, "Failed stat on %s", arcn->org_name);
   1042 	else if (arcn->sb.st_mtime != sb.st_mtime)
   1043 		tty_warn(1, "File %s was modified during read", arcn->org_name);
   1044 	else if (lseek(fd, (off_t)0L, SEEK_SET) < 0)
   1045 		syswarn(1, errno, "File rewind failed on: %s", arcn->org_name);
   1046 	else {
   1047 		arcn->crc = crc;
   1048 		return(0);
   1049 	}
   1050 	return(-1);
   1051 }
   1052