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