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