Home | History | Annotate | Line # | Download | only in pax
file_subs.c revision 1.49
      1 /*	$NetBSD: file_subs.c,v 1.49 2004/06/26 13:28:09 grant 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.49 2004/06/26 13:28:09 grant 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(0, "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) && strcmp(from, ".") != 0) {
    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 		 * it must be a file that exists but we can't create or
    499 		 * remove, but we must avoid the infinite loop.
    500 		 */
    501 		break;
    502 	}
    503 
    504 	/*
    505 	 * we were able to create the node. set uid/gid, modes and times
    506 	 */
    507 	if (pids)
    508 		res = set_ids(nm, arcn->sb.st_uid, arcn->sb.st_gid);
    509 	else
    510 		res = 0;
    511 
    512 	/*
    513 	 * IMPORTANT SECURITY NOTE:
    514 	 * if not preserving mode or we cannot set uid/gid, then PROHIBIT any
    515 	 * set uid/gid bits
    516 	 */
    517 	if (!pmode || res)
    518 		arcn->sb.st_mode &= ~SETBITS(arcn->type == PAX_DIR);
    519 	if (pmode)
    520 		set_pmode(arcn->name, arcn->sb.st_mode);
    521 
    522 	if (arcn->type == PAX_DIR && strcmp(NM_CPIO, argv0) != 0) {
    523 		/*
    524 		 * Dirs must be processed again at end of extract to set times
    525 		 * and modes to agree with those stored in the archive. However
    526 		 * to allow extract to continue, we may have to also set owner
    527 		 * rights. This allows nodes in the archive that are children
    528 		 * of this directory to be extracted without failure. Both time
    529 		 * and modes will be fixed after the entire archive is read and
    530 		 * before pax exits.
    531 		 */
    532 		if (access(nm, R_OK | W_OK | X_OK) < 0) {
    533 			if (lstat(nm, &sb) < 0) {
    534 				syswarn(0, errno,"Cannot access %s (stat)",
    535 				    arcn->name);
    536 				set_pmode(nm,file_mode | S_IRWXU);
    537 			} else {
    538 				/*
    539 				 * We have to add rights to the dir, so we make
    540 				 * sure to restore the mode. The mode must be
    541 				 * restored AS CREATED and not as stored if
    542 				 * pmode is not set.
    543 				 */
    544 				set_pmode(nm, ((sb.st_mode &
    545 				    FILEBITS(arcn->type == PAX_DIR)) |
    546 				    S_IRWXU));
    547 				if (!pmode)
    548 					arcn->sb.st_mode = sb.st_mode;
    549 			}
    550 
    551 			/*
    552 			 * we have to force the mode to what was set here,
    553 			 * since we changed it from the default as created.
    554 			 */
    555 			add_dir(nm, arcn->nlen, &(arcn->sb), 1);
    556 		} else if (pmode || patime || pmtime)
    557 			add_dir(nm, arcn->nlen, &(arcn->sb), 0);
    558 	}
    559 
    560 #if HAVE_LUTIMES
    561 	if (patime || pmtime)
    562 #else
    563 	if ((patime || pmtime) && arcn->type != PAX_SLK)
    564 #endif
    565 		set_ftime(arcn->name, arcn->sb.st_mtime, arcn->sb.st_atime, 0);
    566 
    567 #if HAVE_STRUCT_STAT_ST_FLAGS
    568 	if (pfflags && arcn->type != PAX_SLK)
    569 		set_chflags(arcn->name, arcn->sb.st_flags);
    570 #endif
    571 	return(0);
    572 }
    573 
    574 /*
    575  * unlnk_exist()
    576  *	Remove node from file system with the specified name. We pass the type
    577  *	of the node that is going to replace it. When we try to create a
    578  *	directory and find that it already exists, we allow processing to
    579  *	continue as proper modes etc will always be set for it later on.
    580  * Return:
    581  *	0 is ok to proceed, no file with the specified name exists
    582  *	-1 we were unable to remove the node, or we should not remove it (-k)
    583  *	1 we found a directory and we were going to create a directory.
    584  */
    585 
    586 int
    587 unlnk_exist(char *name, int type)
    588 {
    589 	struct stat sb;
    590 
    591 	/*
    592 	 * the file does not exist, or -k we are done
    593 	 */
    594 	if (lstat(name, &sb) < 0)
    595 		return(0);
    596 	if (kflag)
    597 		return(-1);
    598 
    599 	if (S_ISDIR(sb.st_mode)) {
    600 		/*
    601 		 * try to remove a directory, if it fails and we were going to
    602 		 * create a directory anyway, tell the caller (return a 1).
    603 		 *
    604 		 * don't try to remove the directory if the name is "."
    605 		 * otherwise later file/directory creation fails.
    606 		 */
    607 		if (strcmp(name, ".") == 0)
    608 			return(1);
    609 		if (rmdir(name) < 0) {
    610 			if (type == PAX_DIR)
    611 				return(1);
    612 			syswarn(1, errno, "Cannot remove directory %s", name);
    613 			return(-1);
    614 		}
    615 		return(0);
    616 	}
    617 
    618 	/*
    619 	 * try to get rid of all non-directory type nodes
    620 	 */
    621 	if (unlink(name) < 0) {
    622 		(void)fflush(listf);
    623 		syswarn(1, errno, "Cannot unlink %s", name);
    624 		return(-1);
    625 	}
    626 	return(0);
    627 }
    628 
    629 /*
    630  * chk_path()
    631  *	We were trying to create some kind of node in the file system and it
    632  *	failed. chk_path() makes sure the path up to the node exists and is
    633  *	writable. When we have to create a directory that is missing along the
    634  *	path somewhere, the directory we create will be set to the same
    635  *	uid/gid as the file has (when uid and gid are being preserved).
    636  *	NOTE: this routine is a real performance loss. It is only used as a
    637  *	last resort when trying to create entries in the file system.
    638  * Return:
    639  *	-1 when it could find nothing it is allowed to fix.
    640  *	0 otherwise
    641  */
    642 
    643 int
    644 chk_path(char *name, uid_t st_uid, gid_t st_gid)
    645 {
    646 	char *spt = name;
    647 	struct stat sb;
    648 	int retval = -1;
    649 
    650 	/*
    651 	 * watch out for paths with nodes stored directly in / (e.g. /bozo)
    652 	 */
    653 	if (*spt == '/')
    654 		++spt;
    655 
    656 	for(;;) {
    657 		/*
    658 		 * work forward from the first / and check each part of
    659 		 * the path
    660 		 */
    661 		spt = strchr(spt, '/');
    662 		if (spt == NULL)
    663 			break;
    664 		*spt = '\0';
    665 
    666 		/*
    667 		 * if it exists we assume it is a directory, it is not within
    668 		 * the spec (at least it seems to read that way) to alter the
    669 		 * file system for nodes NOT EXPLICITLY stored on the archive.
    670 		 * If that assumption is changed, you would test the node here
    671 		 * and figure out how to get rid of it (probably like some
    672 		 * recursive unlink()) or fix up the directory permissions if
    673 		 * required (do an access()).
    674 		 */
    675 		if (lstat(name, &sb) == 0) {
    676 			*(spt++) = '/';
    677 			continue;
    678 		}
    679 
    680 		/*
    681 		 * the path fails at this point, see if we can create the
    682 		 * needed directory and continue on
    683 		 */
    684 		if (mkdir(name, S_IRWXU | S_IRWXG | S_IRWXO) < 0) {
    685 			*spt = '/';
    686 			retval = -1;
    687 			break;
    688 		}
    689 
    690 		/*
    691 		 * we were able to create the directory. We will tell the
    692 		 * caller that we found something to fix, and it is ok to try
    693 		 * and create the node again.
    694 		 */
    695 		retval = 0;
    696 		if (pids)
    697 			(void)set_ids(name, st_uid, st_gid);
    698 
    699 		/*
    700 		 * make sure the user doesn't have some strange umask that
    701 		 * causes this newly created directory to be unusable. We fix
    702 		 * the modes and restore them back to the creation default at
    703 		 * the end of pax
    704 		 */
    705 		if ((access(name, R_OK | W_OK | X_OK) < 0) &&
    706 		    (lstat(name, &sb) == 0)) {
    707 			set_pmode(name, ((sb.st_mode & FILEBITS(0)) |
    708 			    S_IRWXU));
    709 			add_dir(name, spt - name, &sb, 1);
    710 		}
    711 		*(spt++) = '/';
    712 		continue;
    713 	}
    714 	return(retval);
    715 }
    716 
    717 /*
    718  * set_ftime()
    719  *	Set the access time and modification time for a named file. If frc
    720  *	is non-zero we force these times to be set even if the user did not
    721  *	request access and/or modification time preservation (this is also
    722  *	used by -t to reset access times).
    723  *	When ign is zero, only those times the user has asked for are set, the
    724  *	other ones are left alone. We do not assume the un-documented feature
    725  *	of many utimes() implementations that consider a 0 time value as a do
    726  *	not set request.
    727  */
    728 
    729 void
    730 set_ftime(char *fnm, time_t mtime, time_t atime, int frc)
    731 {
    732 	struct timeval tv[2];
    733 	struct stat sb;
    734 
    735 	tv[0].tv_sec = (long)atime;
    736 	tv[0].tv_usec = 0;
    737 	tv[1].tv_sec = (long)mtime;
    738 	tv[1].tv_usec = 0;
    739 	if (!frc && (!patime || !pmtime)) {
    740 		/*
    741 		 * if we are not forcing, only set those times the user wants
    742 		 * set. We get the current values of the times if we need them.
    743 		 */
    744 		if (lstat(fnm, &sb) == 0) {
    745 #if BSD4_4 && !HAVE_NBTOOL_CONFIG_H
    746 			if (!patime)
    747 				TIMESPEC_TO_TIMEVAL(&tv[0], &sb.st_atimespec);
    748 			if (!pmtime)
    749 				TIMESPEC_TO_TIMEVAL(&tv[1], &sb.st_mtimespec);
    750 #else
    751 			if (!patime)
    752 				tv[0].tv_sec = sb.st_atime;
    753 			if (!pmtime)
    754 				tv[1].tv_sec = sb.st_mtime;
    755 #endif
    756 		} else
    757 			syswarn(0, errno, "Cannot obtain file stats %s", fnm);
    758 	}
    759 
    760 	/*
    761 	 * set the times
    762 	 */
    763 #if HAVE_LUTIMES
    764 	if (lutimes(fnm, tv))
    765 #else
    766 	if (utimes(fnm, tv))
    767 #endif
    768 		syswarn(1, errno, "Access/modification time set failed on: %s",
    769 		    fnm);
    770 	return;
    771 }
    772 
    773 /*
    774  * set_ids()
    775  *	set the uid and gid of a file system node
    776  * Return:
    777  *	0 when set, -1 on failure
    778  */
    779 
    780 int
    781 set_ids(char *fnm, uid_t uid, gid_t gid)
    782 {
    783 	if (geteuid() == 0)
    784 		if (lchown(fnm, uid, gid)) {
    785 			(void)fflush(listf);
    786 			syswarn(1, errno, "Cannot set file uid/gid of %s",
    787 			    fnm);
    788 			return(-1);
    789 		}
    790 	return(0);
    791 }
    792 
    793 /*
    794  * set_pmode()
    795  *	Set file access mode
    796  */
    797 
    798 void
    799 set_pmode(char *fnm, mode_t mode)
    800 {
    801 	mode &= A_BITS;
    802 	if (lchmod(fnm, mode)) {
    803 		(void)fflush(listf);
    804 		syswarn(1, errno, "Cannot set permissions on %s", fnm);
    805 	}
    806 	return;
    807 }
    808 
    809 /*
    810  * set_chflags()
    811  *	Set 4.4BSD file flags
    812  */
    813 void
    814 set_chflags(char *fnm, u_int32_t flags)
    815 {
    816 
    817 #if 0
    818 	if (chflags(fnm, flags) < 0 && errno != EOPNOTSUPP)
    819 		syswarn(1, errno, "Cannot set file flags on %s", fnm);
    820 #endif
    821 	return;
    822 }
    823 
    824 /*
    825  * file_write()
    826  *	Write/copy a file (during copy or archive extract). This routine knows
    827  *	how to copy files with lseek holes in it. (Which are read as file
    828  *	blocks containing all 0's but do not have any file blocks associated
    829  *	with the data). Typical examples of these are files created by dbm
    830  *	variants (.pag files). While the file size of these files are huge, the
    831  *	actual storage is quite small (the files are sparse). The problem is
    832  *	the holes read as all zeros so are probably stored on the archive that
    833  *	way (there is no way to determine if the file block is really a hole,
    834  *	we only know that a file block of all zero's can be a hole).
    835  *	At this writing, no major archive format knows how to archive files
    836  *	with holes. However, on extraction (or during copy, -rw) we have to
    837  *	deal with these files. Without detecting the holes, the files can
    838  *	consume a lot of file space if just written to disk. This replacement
    839  *	for write when passed the basic allocation size of a file system block,
    840  *	uses lseek whenever it detects the input data is all 0 within that
    841  *	file block. In more detail, the strategy is as follows:
    842  *	While the input is all zero keep doing an lseek. Keep track of when we
    843  *	pass over file block boundaries. Only write when we hit a non zero
    844  *	input. once we have written a file block, we continue to write it to
    845  *	the end (we stop looking at the input). When we reach the start of the
    846  *	next file block, start checking for zero blocks again. Working on file
    847  *	block boundaries significantly reduces the overhead when copying files
    848  *	that are NOT very sparse. This overhead (when compared to a write) is
    849  *	almost below the measurement resolution on many systems. Without it,
    850  *	files with holes cannot be safely copied. It does has a side effect as
    851  *	it can put holes into files that did not have them before, but that is
    852  *	not a problem since the file contents are unchanged (in fact it saves
    853  *	file space). (Except on paging files for diskless clients. But since we
    854  *	cannot determine one of those file from here, we ignore them). If this
    855  *	ever ends up on a system where CTG files are supported and the holes
    856  *	are not desired, just do a conditional test in those routines that
    857  *	call file_write() and have it call write() instead. BEFORE CLOSING THE
    858  *	FILE, make sure to call file_flush() when the last write finishes with
    859  *	an empty block. A lot of file systems will not create an lseek hole at
    860  *	the end. In this case we drop a single 0 at the end to force the
    861  *	trailing 0's in the file.
    862  *	---Parameters---
    863  *	rem: how many bytes left in this file system block
    864  *	isempt: have we written to the file block yet (is it empty)
    865  *	sz: basic file block allocation size
    866  *	cnt: number of bytes on this write
    867  *	str: buffer to write
    868  * Return:
    869  *	number of bytes written, -1 on write (or lseek) error.
    870  */
    871 
    872 int
    873 file_write(int fd, char *str, int cnt, int *rem, int *isempt, int sz,
    874 	char *name)
    875 {
    876 	char *pt;
    877 	char *end;
    878 	int wcnt;
    879 	char *st = str;
    880 	char **strp;
    881 
    882 	/*
    883 	 * while we have data to process
    884 	 */
    885 	while (cnt) {
    886 		if (!*rem) {
    887 			/*
    888 			 * We are now at the start of file system block again
    889 			 * (or what we think one is...). start looking for
    890 			 * empty blocks again
    891 			 */
    892 			*isempt = 1;
    893 			*rem = sz;
    894 		}
    895 
    896 		/*
    897 		 * only examine up to the end of the current file block or
    898 		 * remaining characters to write, whatever is smaller
    899 		 */
    900 		wcnt = MIN(cnt, *rem);
    901 		cnt -= wcnt;
    902 		*rem -= wcnt;
    903 		if (*isempt) {
    904 			/*
    905 			 * have not written to this block yet, so we keep
    906 			 * looking for zero's
    907 			 */
    908 			pt = st;
    909 			end = st + wcnt;
    910 
    911 			/*
    912 			 * look for a zero filled buffer
    913 			 */
    914 			while ((pt < end) && (*pt == '\0'))
    915 				++pt;
    916 
    917 			if (pt == end) {
    918 				/*
    919 				 * skip, buf is empty so far
    920 				 */
    921 				if (fd > -1 &&
    922 				    lseek(fd, (off_t)wcnt, SEEK_CUR) < 0) {
    923 					syswarn(1, errno, "File seek on %s",
    924 					    name);
    925 					return(-1);
    926 				}
    927 				st = pt;
    928 				continue;
    929 			}
    930 			/*
    931 			 * drat, the buf is not zero filled
    932 			 */
    933 			*isempt = 0;
    934 		}
    935 
    936 		/*
    937 		 * have non-zero data in this file system block, have to write
    938 		 */
    939 		switch (fd) {
    940 		case -1:
    941 			strp = &gnu_name_string;
    942 			break;
    943 		case -2:
    944 			strp = &gnu_link_string;
    945 			break;
    946 		default:
    947 			strp = NULL;
    948 			break;
    949 		}
    950 		if (strp) {
    951 			if (*strp)
    952 				err(1, "WARNING! Major Internal Error! GNU hack Failing!");
    953 			*strp = malloc(wcnt + 1);
    954 			if (*strp == NULL) {
    955 				tty_warn(1, "Out of memory");
    956 				return(-1);
    957 			}
    958 			strlcpy(*strp, st, wcnt);
    959 			break;
    960 		} else if (xwrite(fd, st, wcnt) != wcnt) {
    961 			syswarn(1, errno, "Failed write to file %s", name);
    962 			return(-1);
    963 		}
    964 		st += wcnt;
    965 	}
    966 	return(st - str);
    967 }
    968 
    969 /*
    970  * file_flush()
    971  *	when the last file block in a file is zero, many file systems will not
    972  *	let us create a hole at the end. To get the last block with zeros, we
    973  *	write the last BYTE with a zero (back up one byte and write a zero).
    974  */
    975 
    976 void
    977 file_flush(int fd, char *fname, int isempt)
    978 {
    979 	static char blnk[] = "\0";
    980 
    981 	/*
    982 	 * silly test, but make sure we are only called when the last block is
    983 	 * filled with all zeros.
    984 	 */
    985 	if (!isempt)
    986 		return;
    987 
    988 	/*
    989 	 * move back one byte and write a zero
    990 	 */
    991 	if (lseek(fd, (off_t)-1, SEEK_CUR) < 0) {
    992 		syswarn(1, errno, "Failed seek on file %s", fname);
    993 		return;
    994 	}
    995 
    996 	if (write_with_restart(fd, blnk, 1) < 0)
    997 		syswarn(1, errno, "Failed write to file %s", fname);
    998 	return;
    999 }
   1000 
   1001 /*
   1002  * rdfile_close()
   1003  *	close a file we have been reading (to copy or archive). If we have to
   1004  *	reset access time (tflag) do so (the times are stored in arcn).
   1005  */
   1006 
   1007 void
   1008 rdfile_close(ARCHD *arcn, int *fd)
   1009 {
   1010 	/*
   1011 	 * make sure the file is open
   1012 	 */
   1013 	if (*fd < 0)
   1014 		return;
   1015 
   1016 	(void)close(*fd);
   1017 	*fd = -1;
   1018 	if (!tflag)
   1019 		return;
   1020 
   1021 	/*
   1022 	 * user wants last access time reset
   1023 	 */
   1024 	set_ftime(arcn->org_name, arcn->sb.st_mtime, arcn->sb.st_atime, 1);
   1025 	return;
   1026 }
   1027 
   1028 /*
   1029  * set_crc()
   1030  *	read a file to calculate its crc. This is a real drag. Archive formats
   1031  *	that have this, end up reading the file twice (we have to write the
   1032  *	header WITH the crc before writing the file contents. Oh well...
   1033  * Return:
   1034  *	0 if was able to calculate the crc, -1 otherwise
   1035  */
   1036 
   1037 int
   1038 set_crc(ARCHD *arcn, int fd)
   1039 {
   1040 	int i;
   1041 	int res;
   1042 	off_t cpcnt = 0L;
   1043 	u_long size;
   1044 	unsigned long crc = 0L;
   1045 	char tbuf[FILEBLK];
   1046 	struct stat sb;
   1047 
   1048 	if (fd < 0) {
   1049 		/*
   1050 		 * hmm, no fd, should never happen. well no crc then.
   1051 		 */
   1052 		arcn->crc = 0L;
   1053 		return(0);
   1054 	}
   1055 
   1056 	if ((size = (u_long)arcn->sb.st_blksize) > (u_long)sizeof(tbuf))
   1057 		size = (u_long)sizeof(tbuf);
   1058 
   1059 	/*
   1060 	 * read all the bytes we think that there are in the file. If the user
   1061 	 * is trying to archive an active file, forget this file.
   1062 	 */
   1063 	for(;;) {
   1064 		if ((res = read(fd, tbuf, size)) <= 0)
   1065 			break;
   1066 		cpcnt += res;
   1067 		for (i = 0; i < res; ++i)
   1068 			crc += (tbuf[i] & 0xff);
   1069 	}
   1070 
   1071 	/*
   1072 	 * safety check. we want to avoid archiving files that are active as
   1073 	 * they can create inconsistant archive copies.
   1074 	 */
   1075 	if (cpcnt != arcn->sb.st_size)
   1076 		tty_warn(1, "File changed size %s", arcn->org_name);
   1077 	else if (fstat(fd, &sb) < 0)
   1078 		syswarn(1, errno, "Failed stat on %s", arcn->org_name);
   1079 	else if (arcn->sb.st_mtime != sb.st_mtime)
   1080 		tty_warn(1, "File %s was modified during read", arcn->org_name);
   1081 	else if (lseek(fd, (off_t)0L, SEEK_SET) < 0)
   1082 		syswarn(1, errno, "File rewind failed on: %s", arcn->org_name);
   1083 	else {
   1084 		arcn->crc = crc;
   1085 		return(0);
   1086 	}
   1087 	return(-1);
   1088 }
   1089