Home | History | Annotate | Line # | Download | only in pax
file_subs.c revision 1.13
      1 /*	$NetBSD: file_subs.c,v 1.13 1999/11/01 01:35:58 mrg 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. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the University of
     22  *	California, Berkeley and its contributors.
     23  * 4. Neither the name of the University nor the names of its contributors
     24  *    may be used to endorse or promote products derived from this software
     25  *    without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     37  * SUCH DAMAGE.
     38  */
     39 
     40 #include <sys/cdefs.h>
     41 #ifndef 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.13 1999/11/01 01:35:58 mrg 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 <err.h>
     55 #include <fcntl.h>
     56 #include <string.h>
     57 #include <stdio.h>
     58 #include <ctype.h>
     59 #include <errno.h>
     60 #include <sys/uio.h>
     61 #include <stdlib.h>
     62 #include "pax.h"
     63 #include "extern.h"
     64 
     65 static int
     66 mk_link __P((char *,struct stat *,char *, int));
     67 
     68 /*
     69  * routines that deal with file operations such as: creating, removing;
     70  * and setting access modes, uid/gid and times of files
     71  */
     72 
     73 #define FILEBITS		(S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
     74 #define SETBITS			(S_ISUID | S_ISGID)
     75 #define ABITS			(FILEBITS | SETBITS)
     76 
     77 /*
     78  * file_creat()
     79  *	Create and open a file.
     80  * Return:
     81  *	file descriptor or -1 for failure
     82  */
     83 
     84 #if __STDC__
     85 int
     86 file_creat(ARCHD *arcn)
     87 #else
     88 int
     89 file_creat(arcn)
     90 	ARCHD *arcn;
     91 #endif
     92 {
     93 	int fd = -1;
     94 	mode_t file_mode;
     95 	int oerrno;
     96 
     97 	/*
     98 	 * assume file doesn't exist, so just try to create it, most times this
     99 	 * works. We have to take special handling when the file does exist. To
    100 	 * detect this, we use O_EXCL. For example when trying to create a
    101 	 * file and a character device or fifo exists with the same name, we
    102 	 * can accidently open the device by mistake (or block waiting to open)
    103 	 * If we find that the open has failed, then figure spend the effore to
    104 	 * figure out why. This strategy was found to have better average
    105 	 * performance in common use than checking the file (and the path)
    106 	 * first with lstat.
    107 	 */
    108 	file_mode = arcn->sb.st_mode & FILEBITS;
    109 	if ((fd = open(arcn->name, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL,
    110 	    file_mode)) >= 0)
    111 		return(fd);
    112 
    113 	/*
    114 	 * the file seems to exist. First we try to get rid of it (found to be
    115 	 * the second most common failure when traced). If this fails, only
    116 	 * then we go to the expense to check and create the path to the file
    117 	 */
    118 	if (unlnk_exist(arcn->name, arcn->type) != 0)
    119 		return(-1);
    120 
    121 	for (;;) {
    122 		/*
    123 		 * try to open it again, if this fails, check all the nodes in
    124 		 * the path and give it a final try. if chk_path() finds that
    125 		 * it cannot fix anything, we will skip the last attempt
    126 		 */
    127 		if ((fd = open(arcn->name, O_WRONLY | O_CREAT | O_TRUNC,
    128 		    file_mode)) >= 0)
    129 			break;
    130 		oerrno = errno;
    131 		if (chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
    132 			syswarn(1, oerrno, "Unable to create %s", arcn->name);
    133 			return(-1);
    134 		}
    135 	}
    136 	return(fd);
    137 }
    138 
    139 /*
    140  * file_close()
    141  *	Close file descriptor to a file just created by pax. Sets modes,
    142  *	ownership and times as required.
    143  * Return:
    144  *	0 for success, -1 for failure
    145  */
    146 
    147 #if __STDC__
    148 void
    149 file_close(ARCHD *arcn, int fd)
    150 #else
    151 void
    152 file_close(arcn, fd)
    153 	ARCHD *arcn;
    154 	int fd;
    155 #endif
    156 {
    157 	int res = 0;
    158 
    159 	if (fd < 0)
    160 		return;
    161 	if (close(fd) < 0)
    162 		syswarn(0, errno, "Unable to close file descriptor on %s",
    163 		    arcn->name);
    164 
    165 	/*
    166 	 * set owner/groups first as this may strip off mode bits we want
    167 	 * then set file permission modes. Then set file access and
    168 	 * modification times.
    169 	 */
    170 	if (pids)
    171 		res = set_ids(arcn->name, arcn->sb.st_uid, arcn->sb.st_gid);
    172 
    173 	/*
    174 	 * IMPORTANT SECURITY NOTE:
    175 	 * if not preserving mode or we cannot set uid/gid, then PROHIBIT
    176 	 * set uid/gid bits
    177 	 */
    178 	if (!pmode || res)
    179 		arcn->sb.st_mode &= ~(SETBITS);
    180 	if (pmode)
    181 		set_pmode(arcn->name, arcn->sb.st_mode);
    182 	if (patime || pmtime)
    183 		set_ftime(arcn->name, arcn->sb.st_mtime, arcn->sb.st_atime, 0);
    184 	if (pfflags)
    185 		set_chflags(arcn->name, arcn->sb.st_flags);
    186 }
    187 
    188 /*
    189  * lnk_creat()
    190  *	Create a hard link to arcn->ln_name from arcn->name. arcn->ln_name
    191  *	must exist;
    192  * Return:
    193  *	0 if ok, -1 otherwise
    194  */
    195 
    196 #if __STDC__
    197 int
    198 lnk_creat(ARCHD *arcn)
    199 #else
    200 int
    201 lnk_creat(arcn)
    202 	ARCHD *arcn;
    203 #endif
    204 {
    205 	struct stat sb;
    206 
    207 	/*
    208 	 * we may be running as root, so we have to be sure that link target
    209 	 * is not a directory, so we lstat and check
    210 	 */
    211 	if (lstat(arcn->ln_name, &sb) < 0) {
    212 		syswarn(1,errno,"Unable to link to %s from %s", arcn->ln_name,
    213 		    arcn->name);
    214 		return(-1);
    215 	}
    216 
    217 	if (S_ISDIR(sb.st_mode)) {
    218 		tty_warn(1, "A hard link to the directory %s is not allowed",
    219 		    arcn->ln_name);
    220 		return(-1);
    221 	}
    222 
    223 	return(mk_link(arcn->ln_name, &sb, arcn->name, 0));
    224 }
    225 
    226 /*
    227  * cross_lnk()
    228  *	Create a hard link to arcn->org_name from arcn->name. Only used in copy
    229  *	with the -l flag. No warning or error if this does not succeed (we will
    230  *	then just create the file)
    231  * Return:
    232  *	1 if copy() should try to create this file node
    233  *	0 if cross_lnk() ok, -1 for fatal flaw (like linking to self).
    234  */
    235 
    236 #if __STDC__
    237 int
    238 cross_lnk(ARCHD *arcn)
    239 #else
    240 int
    241 cross_lnk(arcn)
    242 	ARCHD *arcn;
    243 #endif
    244 {
    245 	/*
    246 	 * try to make a link to orginal file (-l flag in copy mode). make sure
    247 	 * we do not try to link to directories in case we are running as root
    248 	 * (and it might succeed).
    249 	 */
    250 	if (arcn->type == PAX_DIR)
    251 		return(1);
    252 	return(mk_link(arcn->org_name, &(arcn->sb), arcn->name, 1));
    253 }
    254 
    255 /*
    256  * chk_same()
    257  *	In copy mode if we are not trying to make hard links between the src
    258  *	and destinations, make sure we are not going to overwrite ourselves by
    259  *	accident. This slows things down a little, but we have to protect all
    260  *	those people who make typing errors.
    261  * Return:
    262  *	1 the target does not exist, go ahead and copy
    263  *	0 skip it file exists (-k) or may be the same as source file
    264  */
    265 
    266 #if __STDC__
    267 int
    268 chk_same(ARCHD *arcn)
    269 #else
    270 int
    271 chk_same(arcn)
    272 	ARCHD *arcn;
    273 #endif
    274 {
    275 	struct stat sb;
    276 
    277 	/*
    278 	 * if file does not exist, return. if file exists and -k, skip it
    279 	 * quietly
    280 	 */
    281 	if (lstat(arcn->name, &sb) < 0)
    282 		return(1);
    283 	if (kflag)
    284 		return(0);
    285 
    286 	/*
    287 	 * better make sure the user does not have src == dest by mistake
    288 	 */
    289 	if ((arcn->sb.st_dev == sb.st_dev) && (arcn->sb.st_ino == sb.st_ino)) {
    290 		tty_warn(1, "Unable to copy %s, file would overwrite itself",
    291 		    arcn->name);
    292 		return(0);
    293 	}
    294 	return(1);
    295 }
    296 
    297 /*
    298  * mk_link()
    299  *	try to make a hard link between two files. if ign set, we do not
    300  *	complain.
    301  * Return:
    302  *	0 if successful (or we are done with this file but no error, such as
    303  *	finding the from file exists and the user has set -k).
    304  *	1 when ign was set to indicates we could not make the link but we
    305  *	should try to copy/extract the file as that might work (and is an
    306  *	allowed option). -1 an error occurred.
    307  */
    308 
    309 #if __STDC__
    310 static int
    311 mk_link(char *to, struct stat *to_sb, char *from,
    312 	int ign)
    313 #else
    314 static int
    315 mk_link(to, to_sb, from, ign)
    316 	char *to;
    317 	struct stat *to_sb;
    318 	char *from;
    319 	int ign;
    320 #endif
    321 {
    322 	struct stat sb;
    323 	int oerrno;
    324 
    325 	/*
    326 	 * if from file exists, it has to be unlinked to make the link. If the
    327 	 * file exists and -k is set, skip it quietly
    328 	 */
    329 	if (lstat(from, &sb) == 0) {
    330 		if (kflag)
    331 			return(0);
    332 
    333 		/*
    334 		 * make sure it is not the same file, protect the user
    335 		 */
    336 		if ((to_sb->st_dev==sb.st_dev)&&(to_sb->st_ino == sb.st_ino)) {
    337 			tty_warn(1, "Unable to link file %s to itself", to);
    338 			return(-1);;
    339 		}
    340 
    341 		/*
    342 		 * try to get rid of the file, based on the type
    343 		 */
    344 		if (S_ISDIR(sb.st_mode)) {
    345 			if (rmdir(from) < 0) {
    346 				syswarn(1, errno, "Unable to remove %s", from);
    347 				return(-1);
    348 			}
    349 		} else if (unlink(from) < 0) {
    350 			if (!ign) {
    351 				syswarn(1, errno, "Unable to remove %s", from);
    352 				return(-1);
    353 			}
    354 			return(1);
    355 		}
    356 	}
    357 
    358 	/*
    359 	 * from file is gone (or did not exist), try to make the hard link.
    360 	 * if it fails, check the path and try it again (if chk_path() says to
    361 	 * try again)
    362 	 */
    363 	for (;;) {
    364 		if (link(to, from) == 0)
    365 			break;
    366 		oerrno = errno;
    367 		if (chk_path(from, to_sb->st_uid, to_sb->st_gid) == 0)
    368 			continue;
    369 		if (!ign) {
    370 			syswarn(1, oerrno, "Could not link to %s from %s", to,
    371 			    from);
    372 			return(-1);
    373 		}
    374 		return(1);
    375 	}
    376 
    377 	/*
    378 	 * all right the link was made
    379 	 */
    380 	return(0);
    381 }
    382 
    383 /*
    384  * node_creat()
    385  *	create an entry in the file system (other than a file or hard link).
    386  *	If successful, sets uid/gid modes and times as required.
    387  * Return:
    388  *	0 if ok, -1 otherwise
    389  */
    390 
    391 #if __STDC__
    392 int
    393 node_creat(ARCHD *arcn)
    394 #else
    395 int
    396 node_creat(arcn)
    397 	ARCHD *arcn;
    398 #endif
    399 {
    400 	int res;
    401 	int ign = 0;
    402 	int oerrno;
    403 	int pass = 0;
    404 	mode_t file_mode;
    405 	struct stat sb;
    406 
    407 	/*
    408 	 * create node based on type, if that fails try to unlink the node and
    409 	 * try again. finally check the path and try again. As noted in the
    410 	 * file and link creation routines, this method seems to exhibit the
    411 	 * best performance in general use workloads.
    412 	 */
    413 	file_mode = arcn->sb.st_mode & FILEBITS;
    414 
    415 	for (;;) {
    416 		switch(arcn->type) {
    417 		case PAX_DIR:
    418 			res = mkdir(arcn->name, file_mode);
    419 			if (ign)
    420 				res = 0;
    421 			break;
    422 		case PAX_CHR:
    423 			file_mode |= S_IFCHR;
    424 			res = mknod(arcn->name, file_mode, arcn->sb.st_rdev);
    425 			break;
    426 		case PAX_BLK:
    427 			file_mode |= S_IFBLK;
    428 			res = mknod(arcn->name, file_mode, arcn->sb.st_rdev);
    429 			break;
    430 		case PAX_FIF:
    431 			res = mkfifo(arcn->name, file_mode);
    432 			break;
    433 		case PAX_SCK:
    434 			/*
    435 			 * Skip sockets, operation has no meaning under BSD
    436 			 */
    437 			tty_warn(0,
    438 			    "%s skipped. Sockets cannot be copied or extracted",
    439 			    arcn->name);
    440 			return(-1);
    441 		case PAX_SLK:
    442 			res = symlink(arcn->ln_name, arcn->name);
    443 			break;
    444 		case PAX_CTG:
    445 		case PAX_HLK:
    446 		case PAX_HRG:
    447 		case PAX_REG:
    448 		default:
    449 			/*
    450 			 * we should never get here
    451 			 */
    452 			tty_warn(0, "%s has an unknown file type, skipping",
    453 				arcn->name);
    454 			return(-1);
    455 		}
    456 
    457 		/*
    458 		 * if we were able to create the node break out of the loop,
    459 		 * otherwise try to unlink the node and try again. if that
    460 		 * fails check the full path and try a final time.
    461 		 */
    462 		if (res == 0)
    463 			break;
    464 
    465 		/*
    466 		 * we failed to make the node
    467 		 */
    468 		oerrno = errno;
    469 		if ((ign = unlnk_exist(arcn->name, arcn->type)) < 0)
    470 			return(-1);
    471 
    472 		if (++pass <= 1)
    473 			continue;
    474 
    475 		if (chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
    476 			syswarn(1, oerrno, "Could not create: %s", arcn->name);
    477 			return(-1);
    478 		}
    479 	}
    480 
    481 	/*
    482 	 * we were able to create the node. set uid/gid, modes and times
    483 	 */
    484 	if (pids)
    485 		res = set_ids(arcn->name, arcn->sb.st_uid, arcn->sb.st_gid);
    486 	else
    487 		res = 0;
    488 
    489 	/*
    490 	 * IMPORTANT SECURITY NOTE:
    491 	 * if not preserving mode or we cannot set uid/gid, then PROHIBIT any
    492 	 * set uid/gid bits
    493 	 */
    494 	if (!pmode || res)
    495 		arcn->sb.st_mode &= ~(SETBITS);
    496 	if (pmode)
    497 		set_pmode(arcn->name, arcn->sb.st_mode);
    498 
    499 	if (arcn->type == PAX_DIR) {
    500 		/*
    501 		 * Dirs must be processed again at end of extract to set times
    502 		 * and modes to agree with those stored in the archive. However
    503 		 * to allow extract to continue, we may have to also set owner
    504 		 * rights. This allows nodes in the archive that are children
    505 		 * of this directory to be extracted without failure. Both time
    506 		 * and modes will be fixed after the entire archive is read and
    507 		 * before pax exits.
    508 		 */
    509 		if (access(arcn->name, R_OK | W_OK | X_OK) < 0) {
    510 			if (lstat(arcn->name, &sb) < 0) {
    511 				syswarn(0, errno,"Could not access %s (stat)",
    512 				    arcn->name);
    513 				set_pmode(arcn->name,file_mode | S_IRWXU);
    514 			} else {
    515 				/*
    516 				 * We have to add rights to the dir, so we make
    517 				 * sure to restore the mode. The mode must be
    518 				 * restored AS CREATED and not as stored if
    519 				 * pmode is not set.
    520 				 */
    521 				set_pmode(arcn->name,
    522 				    ((sb.st_mode & FILEBITS) | S_IRWXU));
    523 				if (!pmode)
    524 					arcn->sb.st_mode = sb.st_mode;
    525 			}
    526 
    527 			/*
    528 			 * we have to force the mode to what was set here,
    529 			 * since we changed it from the default as created.
    530 			 */
    531 			add_dir(arcn->name, arcn->nlen, &(arcn->sb), 1);
    532 		} else if (pmode || patime || pmtime)
    533 			add_dir(arcn->name, arcn->nlen, &(arcn->sb), 0);
    534 	}
    535 
    536 	if (patime || pmtime)
    537 		set_ftime(arcn->name, arcn->sb.st_mtime, arcn->sb.st_atime, 0);
    538 	if (pfflags)
    539 		set_chflags(arcn->name, arcn->sb.st_flags);
    540 	return(0);
    541 }
    542 
    543 /*
    544  * unlnk_exist()
    545  *	Remove node from file system with the specified name. We pass the type
    546  *	of the node that is going to replace it. When we try to create a
    547  *	directory and find that it already exists, we allow processing to
    548  *	continue as proper modes etc will always be set for it later on.
    549  * Return:
    550  *	0 is ok to proceed, no file with the specified name exists
    551  *	-1 we were unable to remove the node, or we should not remove it (-k)
    552  *	1 we found a directory and we were going to create a directory.
    553  */
    554 
    555 #if __STDC__
    556 int
    557 unlnk_exist(char *name, int type)
    558 #else
    559 int
    560 unlnk_exist(name, type)
    561 	char *name;
    562 	int type;
    563 #endif
    564 {
    565 	struct stat sb;
    566 
    567 	/*
    568 	 * the file does not exist, or -k we are done
    569 	 */
    570 	if (lstat(name, &sb) < 0)
    571 		return(0);
    572 	if (kflag)
    573 		return(-1);
    574 
    575 	if (S_ISDIR(sb.st_mode)) {
    576 		/*
    577 		 * try to remove a directory, if it fails and we were going to
    578 		 * create a directory anyway, tell the caller (return a 1)
    579 		 */
    580 		if (rmdir(name) < 0) {
    581 			if (type == PAX_DIR)
    582 				return(1);
    583 			syswarn(1,errno,"Unable to remove directory %s", name);
    584 			return(-1);
    585 		}
    586 		return(0);
    587 	}
    588 
    589 	/*
    590 	 * try to get rid of all non-directory type nodes
    591 	 */
    592 	if (unlink(name) < 0) {
    593 		syswarn(1, errno, "Could not unlink %s", name);
    594 		return(-1);
    595 	}
    596 	return(0);
    597 }
    598 
    599 /*
    600  * chk_path()
    601  *	We were trying to create some kind of node in the file system and it
    602  *	failed. chk_path() makes sure the path up to the node exists and is
    603  *	writeable. When we have to create a directory that is missing along the
    604  *	path somewhere, the directory we create will be set to the same
    605  *	uid/gid as the file has (when uid and gid are being preserved).
    606  *	NOTE: this routine is a real performance loss. It is only used as a
    607  *	last resort when trying to create entries in the file system.
    608  * Return:
    609  *	-1 when it could find nothing it is allowed to fix.
    610  *	0 otherwise
    611  */
    612 
    613 #if __STDC__
    614 int
    615 chk_path( char *name, uid_t st_uid, gid_t st_gid)
    616 #else
    617 int
    618 chk_path(name, st_uid, st_gid)
    619 	char *name;
    620 	uid_t st_uid;
    621 	gid_t st_gid;
    622 #endif
    623 {
    624 	char *spt = name;
    625 	struct stat sb;
    626 	int retval = -1;
    627 
    628 	/*
    629 	 * watch out for paths with nodes stored directly in / (e.g. /bozo)
    630 	 */
    631 	if (*spt == '/')
    632 		++spt;
    633 
    634 	for(;;) {
    635 		/*
    636 		 * work foward from the first / and check each part of the path
    637 		 */
    638 		spt = strchr(spt, '/');
    639 		if (spt == NULL)
    640 			break;
    641 		*spt = '\0';
    642 
    643 		/*
    644 		 * if it exists we assume it is a directory, it is not within
    645 		 * the spec (at least it seems to read that way) to alter the
    646 		 * file system for nodes NOT EXPLICITLY stored on the archive.
    647 		 * If that assumption is changed, you would test the node here
    648 		 * and figure out how to get rid of it (probably like some
    649 		 * recursive unlink()) or fix up the directory permissions if
    650 		 * required (do an access()).
    651 		 */
    652 		if (lstat(name, &sb) == 0) {
    653 			*(spt++) = '/';
    654 			continue;
    655 		}
    656 
    657 		/*
    658 		 * the path fails at this point, see if we can create the
    659 		 * needed directory and continue on
    660 		 */
    661 		if (mkdir(name, S_IRWXU | S_IRWXG | S_IRWXO) < 0) {
    662 			*spt = '/';
    663 			retval = -1;
    664 			break;
    665 		}
    666 
    667 		/*
    668 		 * we were able to create the directory. We will tell the
    669 		 * caller that we found something to fix, and it is ok to try
    670 		 * and create the node again.
    671 		 */
    672 		retval = 0;
    673 		if (pids)
    674 			(void)set_ids(name, st_uid, st_gid);
    675 
    676 		/*
    677 		 * make sure the user doen't have some strange umask that
    678 		 * causes this newly created directory to be unusable. We fix
    679 		 * the modes and restore them back to the creation default at
    680 		 * the end of pax
    681 		 */
    682 		if ((access(name, R_OK | W_OK | X_OK) < 0) &&
    683 		    (lstat(name, &sb) == 0)) {
    684 			set_pmode(name, ((sb.st_mode & FILEBITS) | S_IRWXU));
    685 			add_dir(name, spt - name, &sb, 1);
    686 		}
    687 		*(spt++) = '/';
    688 		continue;
    689 	}
    690 	return(retval);
    691 }
    692 
    693 /*
    694  * set_ftime()
    695  *	Set the access time and modification time for a named file. If frc is
    696  *	non-zero we force these times to be set even if the the user did not
    697  *	request access and/or modification time preservation (this is also
    698  *	used by -t to reset access times).
    699  *	When ign is zero, only those times the user has asked for are set, the
    700  *	other ones are left alone. We do not assume the un-documented feature
    701  *	of many utimes() implementations that consider a 0 time value as a do
    702  *	not set request.
    703  */
    704 
    705 #if __STDC__
    706 void
    707 set_ftime(char *fnm, time_t mtime, time_t atime, int frc)
    708 #else
    709 void
    710 set_ftime(fnm, mtime, atime, frc)
    711 	char *fnm;
    712 	time_t mtime;
    713 	time_t atime;
    714 	int frc;
    715 #endif
    716 {
    717 	struct timeval tv[2];
    718 	struct stat sb;
    719 
    720 	tv[0].tv_sec = (long)atime;
    721 	tv[0].tv_usec = 0;
    722 	tv[1].tv_sec = (long)mtime;
    723 	tv[1].tv_usec = 0;
    724 	if (!frc && (!patime || !pmtime)) {
    725 		/*
    726 		 * if we are not forcing, only set those times the user wants
    727 		 * set. We get the current values of the times if we need them.
    728 		 */
    729 		if (lstat(fnm, &sb) == 0) {
    730 			if (!patime)
    731 				TIMESPEC_TO_TIMEVAL(&tv[0], &sb.st_atimespec);
    732 			if (!pmtime)
    733 				TIMESPEC_TO_TIMEVAL(&tv[1], &sb.st_mtimespec);
    734 		} else
    735 			syswarn(0,errno,"Unable to obtain file stats %s", fnm);
    736 	}
    737 
    738 	/*
    739 	 * set the times
    740 	 */
    741 	if (lutimes(fnm, tv) < 0)
    742 		syswarn(1, errno, "Access/modification time set failed on: %s",
    743 		    fnm);
    744 	return;
    745 }
    746 
    747 /*
    748  * set_ids()
    749  *	set the uid and gid of a file system node
    750  * Return:
    751  *	0 when set, -1 on failure
    752  */
    753 
    754 #if __STDC__
    755 int
    756 set_ids(char *fnm, uid_t uid, gid_t gid)
    757 #else
    758 int
    759 set_ids(fnm, uid, gid)
    760 	char *fnm;
    761 	uid_t uid;
    762 	gid_t gid;
    763 #endif
    764 {
    765 	if (lchown(fnm, uid, gid) < 0) {
    766 		syswarn(1, errno, "Unable to set file uid/gid of %s", fnm);
    767 		return(-1);
    768 	}
    769 	return(0);
    770 }
    771 
    772 /*
    773  * set_pmode()
    774  *	Set file access mode
    775  */
    776 
    777 #if __STDC__
    778 void
    779 set_pmode(char *fnm, mode_t mode)
    780 #else
    781 void
    782 set_pmode(fnm, mode)
    783 	char *fnm;
    784 	mode_t mode;
    785 #endif
    786 {
    787 	mode &= ABITS;
    788 	if (lchmod(fnm, mode) < 0)
    789 		syswarn(1, errno, "Could not set permissions on %s", fnm);
    790 	return;
    791 }
    792 
    793 /*
    794  * set_chflags()
    795  *	Set 4.4BSD file flags
    796  */
    797 #if __STDC__
    798 void
    799 set_chflags(char *fnm, u_int32_t flags)
    800 #else
    801 void
    802 set_pmode(fnm, flags)
    803 	char *fnm;
    804 	u_int32_t flags;
    805 #endif
    806 {
    807 
    808 	if (chflags(fnm, flags) < 0)
    809 		syswarn(1, errno, "Could not set file flags on %s", fnm);
    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 boundries. 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 boundries 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 #if __STDC__
    862 int
    863 file_write(int fd, char *str, int cnt, int *rem, int *isempt, int sz,
    864 	char *name)
    865 #else
    866 int
    867 file_write(fd, str, cnt, rem, isempt, sz, name)
    868 	int fd;
    869 	char *str;
    870 	int cnt;
    871 	int *rem;
    872 	int *isempt;
    873 	int sz;
    874 	char *name;
    875 #endif
    876 {
    877 	char *pt;
    878 	char *end;
    879 	int wcnt;
    880 	char *st = str;
    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 		if (fd == -1) {
    940 			/* GNU hack */
    941 			if (gnu_hack_string)
    942 				err(1, "WARNING! Major Internal Error! GNU hack Failing!");
    943 			gnu_hack_string = malloc(wcnt + 1);
    944 			if (gnu_hack_string == NULL) {
    945 				tty_warn(1, "Out of memory");
    946 				return(-1);
    947 			}
    948 			strncpy(gnu_hack_string, st, wcnt);
    949 			gnu_hack_string[wcnt] = 0;
    950 		} else if (write(fd, st, wcnt) != wcnt) {
    951 			syswarn(1, errno, "Failed write to file %s", name);
    952 			return(-1);
    953 		}
    954 		st += wcnt;
    955 	}
    956 	return(st - str);
    957 }
    958 
    959 /*
    960  * file_flush()
    961  *	when the last file block in a file is zero, many file systems will not
    962  *	let us create a hole at the end. To get the last block with zeros, we
    963  *	write the last BYTE with a zero (back up one byte and write a zero).
    964  */
    965 
    966 #if __STDC__
    967 void
    968 file_flush(int fd, char *fname, int isempt)
    969 #else
    970 void
    971 file_flush(fd, fname, isempt)
    972 	int fd;
    973 	char *fname;
    974 	int isempt;
    975 #endif
    976 {
    977 	static char blnk[] = "\0";
    978 
    979 	/*
    980 	 * silly test, but make sure we are only called when the last block is
    981 	 * filled with all zeros.
    982 	 */
    983 	if (!isempt)
    984 		return;
    985 
    986 	/*
    987 	 * move back one byte and write a zero
    988 	 */
    989 	if (lseek(fd, (off_t)-1, SEEK_CUR) < 0) {
    990 		syswarn(1, errno, "Failed seek on file %s", fname);
    991 		return;
    992 	}
    993 
    994 	if (write(fd, blnk, 1) < 0)
    995 		syswarn(1, errno, "Failed write to file %s", fname);
    996 	return;
    997 }
    998 
    999 /*
   1000  * rdfile_close()
   1001  *	close a file we have been reading (to copy or archive). If we have to
   1002  *	reset access time (tflag) do so (the times are stored in arcn).
   1003  */
   1004 
   1005 #if __STDC__
   1006 void
   1007 rdfile_close(ARCHD *arcn, int *fd)
   1008 #else
   1009 void
   1010 rdfile_close(arcn, fd)
   1011 	ARCHD *arcn;
   1012 	int *fd;
   1013 #endif
   1014 {
   1015 	/*
   1016 	 * make sure the file is open
   1017 	 */
   1018 	if (*fd < 0)
   1019 		return;
   1020 
   1021 	(void)close(*fd);
   1022 	*fd = -1;
   1023 	if (!tflag)
   1024 		return;
   1025 
   1026 	/*
   1027 	 * user wants last access time reset
   1028 	 */
   1029 	set_ftime(arcn->org_name, arcn->sb.st_mtime, arcn->sb.st_atime, 1);
   1030 	return;
   1031 }
   1032 
   1033 /*
   1034  * set_crc()
   1035  *	read a file to calculate its crc. This is a real drag. Archive formats
   1036  *	that have this, end up reading the file twice (we have to write the
   1037  *	header WITH the crc before writing the file contents. Oh well...
   1038  * Return:
   1039  *	0 if was able to calculate the crc, -1 otherwise
   1040  */
   1041 
   1042 #if __STDC__
   1043 int
   1044 set_crc(ARCHD *arcn, int fd)
   1045 #else
   1046 int
   1047 set_crc(arcn, fd)
   1048 	ARCHD *arcn;
   1049 	int fd;
   1050 #endif
   1051 {
   1052 	int i;
   1053 	int res;
   1054 	off_t cpcnt = 0L;
   1055 	u_long size;
   1056 	unsigned long crc = 0L;
   1057 	char tbuf[FILEBLK];
   1058 	struct stat sb;
   1059 
   1060 	if (fd < 0) {
   1061 		/*
   1062 		 * hmm, no fd, should never happen. well no crc then.
   1063 		 */
   1064 		arcn->crc = 0L;
   1065 		return(0);
   1066 	}
   1067 
   1068 	if ((size = (u_long)arcn->sb.st_blksize) > (u_long)sizeof(tbuf))
   1069 		size = (u_long)sizeof(tbuf);
   1070 
   1071 	/*
   1072 	 * read all the bytes we think that there are in the file. If the user
   1073 	 * is trying to archive an active file, forget this file.
   1074 	 */
   1075 	for(;;) {
   1076 		if ((res = read(fd, tbuf, size)) <= 0)
   1077 			break;
   1078 		cpcnt += res;
   1079 		for (i = 0; i < res; ++i)
   1080 			crc += (tbuf[i] & 0xff);
   1081 	}
   1082 
   1083 	/*
   1084 	 * safety check. we want to avoid archiving files that are active as
   1085 	 * they can create inconsistant archive copies.
   1086 	 */
   1087 	if (cpcnt != arcn->sb.st_size)
   1088 		tty_warn(1, "File changed size %s", arcn->org_name);
   1089 	else if (fstat(fd, &sb) < 0)
   1090 		syswarn(1, errno, "Failed stat on %s", arcn->org_name);
   1091 	else if (arcn->sb.st_mtime != sb.st_mtime)
   1092 		tty_warn(1, "File %s was modified during read", arcn->org_name);
   1093 	else if (lseek(fd, (off_t)0L, SEEK_SET) < 0)
   1094 		syswarn(1, errno, "File rewind failed on: %s", arcn->org_name);
   1095 	else {
   1096 		arcn->crc = crc;
   1097 		return(0);
   1098 	}
   1099 	return(-1);
   1100 }
   1101