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