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