11556Srgrimes/*-
21556Srgrimes * Copyright (c) 1992 Keith Muller.
31556Srgrimes * Copyright (c) 1992, 1993
41556Srgrimes *	The Regents of the University of California.  All rights reserved.
51556Srgrimes *
61556Srgrimes * This code is derived from software contributed to Berkeley by
71556Srgrimes * Keith Muller of the University of California, San Diego.
81556Srgrimes *
91556Srgrimes * Redistribution and use in source and binary forms, with or without
101556Srgrimes * modification, are permitted provided that the following conditions
111556Srgrimes * are met:
121556Srgrimes * 1. Redistributions of source code must retain the above copyright
131556Srgrimes *    notice, this list of conditions and the following disclaimer.
141556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
151556Srgrimes *    notice, this list of conditions and the following disclaimer in the
161556Srgrimes *    documentation and/or other materials provided with the distribution.
171556Srgrimes * 4. Neither the name of the University nor the names of its contributors
181556Srgrimes *    may be used to endorse or promote products derived from this software
191556Srgrimes *    without specific prior written permission.
201556Srgrimes *
211556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
221556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
231556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
241556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
251556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
261556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
271556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
281556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
291556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
301556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311556Srgrimes * SUCH DAMAGE.
321556Srgrimes */
331556Srgrimes
341556Srgrimes#ifndef lint
3536049Scharnier#if 0
3636049Scharnierstatic char sccsid[] = "@(#)file_subs.c	8.1 (Berkeley) 5/31/93";
3736049Scharnier#endif
381556Srgrimes#endif /* not lint */
3999110Sobrien#include <sys/cdefs.h>
4099110Sobrien__FBSDID("$FreeBSD$");
411556Srgrimes
421556Srgrimes#include <sys/types.h>
431556Srgrimes#include <sys/time.h>
441556Srgrimes#include <sys/stat.h>
451556Srgrimes#include <unistd.h>
461556Srgrimes#include <fcntl.h>
471556Srgrimes#include <string.h>
481556Srgrimes#include <stdio.h>
491556Srgrimes#include <errno.h>
501556Srgrimes#include <sys/uio.h>
511556Srgrimes#include "pax.h"
5276351Skris#include "options.h"
531556Srgrimes#include "extern.h"
541556Srgrimes
551556Srgrimesstatic int
5690113Simpmk_link(char *,struct stat *,char *, int);
571556Srgrimes
581556Srgrimes/*
591556Srgrimes * routines that deal with file operations such as: creating, removing;
601556Srgrimes * and setting access modes, uid/gid and times of files
611556Srgrimes */
621556Srgrimes
631556Srgrimes#define FILEBITS		(S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
641556Srgrimes#define SETBITS			(S_ISUID | S_ISGID)
651556Srgrimes#define ABITS			(FILEBITS | SETBITS)
661556Srgrimes
671556Srgrimes/*
681556Srgrimes * file_creat()
691556Srgrimes *	Create and open a file.
701556Srgrimes * Return:
711556Srgrimes *	file descriptor or -1 for failure
721556Srgrimes */
731556Srgrimes
741556Srgrimesint
7590113Simpfile_creat(ARCHD *arcn)
761556Srgrimes{
771556Srgrimes	int fd = -1;
781556Srgrimes	mode_t file_mode;
791556Srgrimes	int oerrno;
801556Srgrimes
811556Srgrimes	/*
821556Srgrimes	 * assume file doesn't exist, so just try to create it, most times this
831556Srgrimes	 * works. We have to take special handling when the file does exist. To
841556Srgrimes	 * detect this, we use O_EXCL. For example when trying to create a
851556Srgrimes	 * file and a character device or fifo exists with the same name, we
86222177Suqs	 * can accidentally open the device by mistake (or block waiting to
87222177Suqs	 * open). If we find that the open has failed, then spend the effort
88222177Suqs	 * to figure out why. This strategy was found to have better average
891556Srgrimes	 * performance in common use than checking the file (and the path)
901556Srgrimes	 * first with lstat.
911556Srgrimes	 */
921556Srgrimes	file_mode = arcn->sb.st_mode & FILEBITS;
931556Srgrimes	if ((fd = open(arcn->name, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL,
941556Srgrimes	    file_mode)) >= 0)
951556Srgrimes		return(fd);
961556Srgrimes
971556Srgrimes	/*
981556Srgrimes	 * the file seems to exist. First we try to get rid of it (found to be
991556Srgrimes	 * the second most common failure when traced). If this fails, only
1001556Srgrimes	 * then we go to the expense to check and create the path to the file
1011556Srgrimes	 */
1021556Srgrimes	if (unlnk_exist(arcn->name, arcn->type) != 0)
1031556Srgrimes		return(-1);
1041556Srgrimes
1051556Srgrimes	for (;;) {
1061556Srgrimes		/*
1071556Srgrimes		 * try to open it again, if this fails, check all the nodes in
1081556Srgrimes		 * the path and give it a final try. if chk_path() finds that
1091556Srgrimes		 * it cannot fix anything, we will skip the last attempt
1101556Srgrimes		 */
1111556Srgrimes		if ((fd = open(arcn->name, O_WRONLY | O_CREAT | O_TRUNC,
1121556Srgrimes		    file_mode)) >= 0)
1131556Srgrimes			break;
1141556Srgrimes		oerrno = errno;
11576351Skris		if (nodirs || chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
11676017Skris			syswarn(1, oerrno, "Unable to create %s", arcn->name);
1171556Srgrimes			return(-1);
1181556Srgrimes		}
1191556Srgrimes	}
1201556Srgrimes	return(fd);
1211556Srgrimes}
1221556Srgrimes
1231556Srgrimes/*
1241556Srgrimes * file_close()
1251556Srgrimes *	Close file descriptor to a file just created by pax. Sets modes,
1261556Srgrimes *	ownership and times as required.
1271556Srgrimes * Return:
1281556Srgrimes *	0 for success, -1 for failure
1291556Srgrimes */
1301556Srgrimes
1311556Srgrimesvoid
13290113Simpfile_close(ARCHD *arcn, int fd)
1331556Srgrimes{
1341556Srgrimes	int res = 0;
1351556Srgrimes
1361556Srgrimes	if (fd < 0)
1371556Srgrimes		return;
1381556Srgrimes	if (close(fd) < 0)
13976017Skris		syswarn(0, errno, "Unable to close file descriptor on %s",
1401556Srgrimes		    arcn->name);
1411556Srgrimes
1421556Srgrimes	/*
1431556Srgrimes	 * set owner/groups first as this may strip off mode bits we want
1441556Srgrimes	 * then set file permission modes. Then set file access and
1458855Srgrimes	 * modification times.
1461556Srgrimes	 */
1471556Srgrimes	if (pids)
1481556Srgrimes		res = set_ids(arcn->name, arcn->sb.st_uid, arcn->sb.st_gid);
1491556Srgrimes
1501556Srgrimes	/*
1511556Srgrimes	 * IMPORTANT SECURITY NOTE:
1521556Srgrimes	 * if not preserving mode or we cannot set uid/gid, then PROHIBIT
1531556Srgrimes	 * set uid/gid bits
1541556Srgrimes	 */
1551556Srgrimes	if (!pmode || res)
1561556Srgrimes		arcn->sb.st_mode &= ~(SETBITS);
1571556Srgrimes	if (pmode)
1581556Srgrimes		set_pmode(arcn->name, arcn->sb.st_mode);
1591556Srgrimes	if (patime || pmtime)
1601556Srgrimes		set_ftime(arcn->name, arcn->sb.st_mtime, arcn->sb.st_atime, 0);
1611556Srgrimes}
1621556Srgrimes
1631556Srgrimes/*
1641556Srgrimes * lnk_creat()
1651556Srgrimes *	Create a hard link to arcn->ln_name from arcn->name. arcn->ln_name
1668855Srgrimes *	must exist;
1671556Srgrimes * Return:
1681556Srgrimes *	0 if ok, -1 otherwise
1691556Srgrimes */
1701556Srgrimes
1711556Srgrimesint
17290113Simplnk_creat(ARCHD *arcn)
1731556Srgrimes{
1741556Srgrimes	struct stat sb;
1751556Srgrimes
1761556Srgrimes	/*
1771556Srgrimes	 * we may be running as root, so we have to be sure that link target
1781556Srgrimes	 * is not a directory, so we lstat and check
1791556Srgrimes	 */
1801556Srgrimes	if (lstat(arcn->ln_name, &sb) < 0) {
18176017Skris		syswarn(1,errno,"Unable to link to %s from %s", arcn->ln_name,
1821556Srgrimes		    arcn->name);
1831556Srgrimes		return(-1);
1841556Srgrimes	}
1851556Srgrimes
1861556Srgrimes	if (S_ISDIR(sb.st_mode)) {
18776017Skris		paxwarn(1, "A hard link to the directory %s is not allowed",
1881556Srgrimes		    arcn->ln_name);
1891556Srgrimes		return(-1);
1901556Srgrimes	}
1911556Srgrimes
1921556Srgrimes	return(mk_link(arcn->ln_name, &sb, arcn->name, 0));
1931556Srgrimes}
1941556Srgrimes
1951556Srgrimes/*
1961556Srgrimes * cross_lnk()
1971556Srgrimes *	Create a hard link to arcn->org_name from arcn->name. Only used in copy
19876017Skris *	with the -l flag. No warning or error if this does not succeed (we will
1991556Srgrimes *	then just create the file)
2001556Srgrimes * Return:
2011556Srgrimes *	1 if copy() should try to create this file node
2021556Srgrimes *	0 if cross_lnk() ok, -1 for fatal flaw (like linking to self).
2031556Srgrimes */
2041556Srgrimes
2051556Srgrimesint
20690113Simpcross_lnk(ARCHD *arcn)
2071556Srgrimes{
2081556Srgrimes	/*
20946684Skris	 * try to make a link to original file (-l flag in copy mode). make sure
2101556Srgrimes	 * we do not try to link to directories in case we are running as root
2111556Srgrimes	 * (and it might succeed).
2121556Srgrimes	 */
2131556Srgrimes	if (arcn->type == PAX_DIR)
2141556Srgrimes		return(1);
2151556Srgrimes	return(mk_link(arcn->org_name, &(arcn->sb), arcn->name, 1));
2161556Srgrimes}
2171556Srgrimes
2181556Srgrimes/*
2191556Srgrimes * chk_same()
2201556Srgrimes *	In copy mode if we are not trying to make hard links between the src
2211556Srgrimes *	and destinations, make sure we are not going to overwrite ourselves by
2221556Srgrimes *	accident. This slows things down a little, but we have to protect all
2231556Srgrimes *	those people who make typing errors.
2241556Srgrimes * Return:
2251556Srgrimes *	1 the target does not exist, go ahead and copy
2261556Srgrimes *	0 skip it file exists (-k) or may be the same as source file
2271556Srgrimes */
2281556Srgrimes
2291556Srgrimesint
23090113Simpchk_same(ARCHD *arcn)
2311556Srgrimes{
2321556Srgrimes	struct stat sb;
2331556Srgrimes
2348855Srgrimes	/*
2351556Srgrimes	 * if file does not exist, return. if file exists and -k, skip it
2361556Srgrimes	 * quietly
2371556Srgrimes	 */
2381556Srgrimes	if (lstat(arcn->name, &sb) < 0)
2391556Srgrimes		return(1);
2401556Srgrimes	if (kflag)
2411556Srgrimes		return(0);
2421556Srgrimes
2431556Srgrimes	/*
2441556Srgrimes	 * better make sure the user does not have src == dest by mistake
2451556Srgrimes	 */
2461556Srgrimes	if ((arcn->sb.st_dev == sb.st_dev) && (arcn->sb.st_ino == sb.st_ino)) {
24776017Skris		paxwarn(1, "Unable to copy %s, file would overwrite itself",
2481556Srgrimes		    arcn->name);
2491556Srgrimes		return(0);
2501556Srgrimes	}
2511556Srgrimes	return(1);
2521556Srgrimes}
2531556Srgrimes
2541556Srgrimes/*
2551556Srgrimes * mk_link()
2561556Srgrimes *	try to make a hard link between two files. if ign set, we do not
2571556Srgrimes *	complain.
2581556Srgrimes * Return:
2591556Srgrimes *	0 if successful (or we are done with this file but no error, such as
2601556Srgrimes *	finding the from file exists and the user has set -k).
2611556Srgrimes *	1 when ign was set to indicates we could not make the link but we
2621556Srgrimes *	should try to copy/extract the file as that might work (and is an
2631556Srgrimes *	allowed option). -1 an error occurred.
2641556Srgrimes */
2651556Srgrimes
2661556Srgrimesstatic int
26790113Simpmk_link(char *to, struct stat *to_sb, char *from,
2681556Srgrimes	int ign)
2691556Srgrimes{
2701556Srgrimes	struct stat sb;
2711556Srgrimes	int oerrno;
2721556Srgrimes
2731556Srgrimes	/*
2741556Srgrimes	 * if from file exists, it has to be unlinked to make the link. If the
2751556Srgrimes	 * file exists and -k is set, skip it quietly
2761556Srgrimes	 */
2771556Srgrimes	if (lstat(from, &sb) == 0) {
2781556Srgrimes		if (kflag)
2791556Srgrimes			return(0);
2801556Srgrimes
2811556Srgrimes		/*
2821556Srgrimes		 * make sure it is not the same file, protect the user
2831556Srgrimes		 */
2841556Srgrimes		if ((to_sb->st_dev==sb.st_dev)&&(to_sb->st_ino == sb.st_ino)) {
28576017Skris			paxwarn(1, "Unable to link file %s to itself", to);
286169926Srse			return(-1);
2871556Srgrimes		}
2881556Srgrimes
2891556Srgrimes		/*
2901556Srgrimes		 * try to get rid of the file, based on the type
2911556Srgrimes		 */
2921556Srgrimes		if (S_ISDIR(sb.st_mode)) {
2931556Srgrimes			if (rmdir(from) < 0) {
29476017Skris				syswarn(1, errno, "Unable to remove %s", from);
2951556Srgrimes				return(-1);
2961556Srgrimes			}
2971556Srgrimes		} else if (unlink(from) < 0) {
2981556Srgrimes			if (!ign) {
29976017Skris				syswarn(1, errno, "Unable to remove %s", from);
3001556Srgrimes				return(-1);
3011556Srgrimes			}
3021556Srgrimes			return(1);
3031556Srgrimes		}
3041556Srgrimes	}
3051556Srgrimes
3061556Srgrimes	/*
3071556Srgrimes	 * from file is gone (or did not exist), try to make the hard link.
3081556Srgrimes	 * if it fails, check the path and try it again (if chk_path() says to
3091556Srgrimes	 * try again)
3101556Srgrimes	 */
3111556Srgrimes	for (;;) {
3121556Srgrimes		if (link(to, from) == 0)
3131556Srgrimes			break;
3141556Srgrimes		oerrno = errno;
31576351Skris		if (!nodirs && chk_path(from, to_sb->st_uid, to_sb->st_gid) == 0)
3161556Srgrimes			continue;
3171556Srgrimes		if (!ign) {
31876017Skris			syswarn(1, oerrno, "Could not link to %s from %s", to,
3191556Srgrimes			    from);
3201556Srgrimes			return(-1);
3211556Srgrimes		}
3221556Srgrimes		return(1);
3231556Srgrimes	}
3241556Srgrimes
3251556Srgrimes	/*
3261556Srgrimes	 * all right the link was made
3271556Srgrimes	 */
3281556Srgrimes	return(0);
3291556Srgrimes}
3301556Srgrimes
3311556Srgrimes/*
3321556Srgrimes * node_creat()
333102230Strhodes *	create an entry in the file system (other than a file or hard link).
3341556Srgrimes *	If successful, sets uid/gid modes and times as required.
3351556Srgrimes * Return:
3361556Srgrimes *	0 if ok, -1 otherwise
3371556Srgrimes */
3381556Srgrimes
3391556Srgrimesint
34090113Simpnode_creat(ARCHD *arcn)
3411556Srgrimes{
34290113Simp	int res;
34390113Simp	int ign = 0;
34490113Simp	int oerrno;
34590113Simp	int pass = 0;
3461556Srgrimes	mode_t file_mode;
3471556Srgrimes	struct stat sb;
3481556Srgrimes
3491556Srgrimes	/*
3501556Srgrimes	 * create node based on type, if that fails try to unlink the node and
3511556Srgrimes	 * try again. finally check the path and try again. As noted in the
3521556Srgrimes	 * file and link creation routines, this method seems to exhibit the
3531556Srgrimes	 * best performance in general use workloads.
3541556Srgrimes	 */
3551556Srgrimes	file_mode = arcn->sb.st_mode & FILEBITS;
3561556Srgrimes
3571556Srgrimes	for (;;) {
3581556Srgrimes		switch(arcn->type) {
3591556Srgrimes		case PAX_DIR:
3601556Srgrimes			res = mkdir(arcn->name, file_mode);
3611556Srgrimes			if (ign)
3621556Srgrimes				res = 0;
3631556Srgrimes			break;
3641556Srgrimes		case PAX_CHR:
3651556Srgrimes			file_mode |= S_IFCHR;
3661556Srgrimes			res = mknod(arcn->name, file_mode, arcn->sb.st_rdev);
3671556Srgrimes			break;
3681556Srgrimes		case PAX_BLK:
3691556Srgrimes			file_mode |= S_IFBLK;
3701556Srgrimes			res = mknod(arcn->name, file_mode, arcn->sb.st_rdev);
3711556Srgrimes			break;
3721556Srgrimes		case PAX_FIF:
3731556Srgrimes			res = mkfifo(arcn->name, file_mode);
3741556Srgrimes			break;
3751556Srgrimes		case PAX_SCK:
3761556Srgrimes			/*
3771556Srgrimes			 * Skip sockets, operation has no meaning under BSD
3781556Srgrimes			 */
37976017Skris			paxwarn(0,
3801556Srgrimes			    "%s skipped. Sockets cannot be copied or extracted",
3811556Srgrimes			    arcn->name);
3821556Srgrimes			return(-1);
3831556Srgrimes		case PAX_SLK:
38476351Skris			res = symlink(arcn->ln_name, arcn->name);
3851556Srgrimes			break;
3861556Srgrimes		case PAX_CTG:
3871556Srgrimes		case PAX_HLK:
3881556Srgrimes		case PAX_HRG:
3891556Srgrimes		case PAX_REG:
3901556Srgrimes		default:
3911556Srgrimes			/*
3921556Srgrimes			 * we should never get here
3931556Srgrimes			 */
39476017Skris			paxwarn(0, "%s has an unknown file type, skipping",
3951556Srgrimes				arcn->name);
3961556Srgrimes			return(-1);
3971556Srgrimes		}
3981556Srgrimes
3991556Srgrimes		/*
4001556Srgrimes		 * if we were able to create the node break out of the loop,
4011556Srgrimes		 * otherwise try to unlink the node and try again. if that
4021556Srgrimes		 * fails check the full path and try a final time.
4031556Srgrimes		 */
4041556Srgrimes		if (res == 0)
4051556Srgrimes			break;
4061556Srgrimes
4071556Srgrimes		/*
4081556Srgrimes		 * we failed to make the node
4091556Srgrimes		 */
4101556Srgrimes		oerrno = errno;
4111556Srgrimes		if ((ign = unlnk_exist(arcn->name, arcn->type)) < 0)
4121556Srgrimes			return(-1);
4131556Srgrimes
4141556Srgrimes		if (++pass <= 1)
4151556Srgrimes			continue;
4161556Srgrimes
41776351Skris		if (nodirs || chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
41876017Skris			syswarn(1, oerrno, "Could not create: %s", arcn->name);
4191556Srgrimes			return(-1);
4201556Srgrimes		}
4211556Srgrimes	}
4221556Srgrimes
4231556Srgrimes	/*
4241556Srgrimes	 * we were able to create the node. set uid/gid, modes and times
4251556Srgrimes	 */
4261556Srgrimes	if (pids)
427187976Skientzle		res = set_ids(arcn->name, arcn->sb.st_uid, arcn->sb.st_gid);
4281556Srgrimes	else
4291556Srgrimes		res = 0;
4301556Srgrimes
4311556Srgrimes	/*
4321556Srgrimes	 * IMPORTANT SECURITY NOTE:
4331556Srgrimes	 * if not preserving mode or we cannot set uid/gid, then PROHIBIT any
4341556Srgrimes	 * set uid/gid bits
4351556Srgrimes	 */
4361556Srgrimes	if (!pmode || res)
4371556Srgrimes		arcn->sb.st_mode &= ~(SETBITS);
4381556Srgrimes	if (pmode)
4391556Srgrimes		set_pmode(arcn->name, arcn->sb.st_mode);
4401556Srgrimes
44176351Skris	if (arcn->type == PAX_DIR && strcmp(NM_CPIO, argv0) != 0) {
4421556Srgrimes		/*
4431556Srgrimes		 * Dirs must be processed again at end of extract to set times
4441556Srgrimes		 * and modes to agree with those stored in the archive. However
4451556Srgrimes		 * to allow extract to continue, we may have to also set owner
4461556Srgrimes		 * rights. This allows nodes in the archive that are children
4471556Srgrimes		 * of this directory to be extracted without failure. Both time
4481556Srgrimes		 * and modes will be fixed after the entire archive is read and
4491556Srgrimes		 * before pax exits.
4501556Srgrimes		 */
4511556Srgrimes		if (access(arcn->name, R_OK | W_OK | X_OK) < 0) {
4521556Srgrimes			if (lstat(arcn->name, &sb) < 0) {
45376017Skris				syswarn(0, errno,"Could not access %s (stat)",
4541556Srgrimes				    arcn->name);
4551556Srgrimes				set_pmode(arcn->name,file_mode | S_IRWXU);
4561556Srgrimes			} else {
4571556Srgrimes				/*
4581556Srgrimes				 * We have to add rights to the dir, so we make
4591556Srgrimes				 * sure to restore the mode. The mode must be
4601556Srgrimes				 * restored AS CREATED and not as stored if
4611556Srgrimes				 * pmode is not set.
4621556Srgrimes				 */
4631556Srgrimes				set_pmode(arcn->name,
4641556Srgrimes				    ((sb.st_mode & FILEBITS) | S_IRWXU));
4651556Srgrimes				if (!pmode)
4661556Srgrimes					arcn->sb.st_mode = sb.st_mode;
4671556Srgrimes			}
4681556Srgrimes
4691556Srgrimes			/*
4701556Srgrimes			 * we have to force the mode to what was set here,
4711556Srgrimes			 * since we changed it from the default as created.
4721556Srgrimes			 */
4731556Srgrimes			add_dir(arcn->name, arcn->nlen, &(arcn->sb), 1);
4741556Srgrimes		} else if (pmode || patime || pmtime)
4751556Srgrimes			add_dir(arcn->name, arcn->nlen, &(arcn->sb), 0);
4761556Srgrimes	}
4771556Srgrimes
4781556Srgrimes	if (patime || pmtime)
4791556Srgrimes		set_ftime(arcn->name, arcn->sb.st_mtime, arcn->sb.st_atime, 0);
4801556Srgrimes	return(0);
4811556Srgrimes}
4821556Srgrimes
4831556Srgrimes/*
4841556Srgrimes * unlnk_exist()
485102230Strhodes *	Remove node from file system with the specified name. We pass the type
4861556Srgrimes *	of the node that is going to replace it. When we try to create a
4871556Srgrimes *	directory and find that it already exists, we allow processing to
4881556Srgrimes *	continue as proper modes etc will always be set for it later on.
4891556Srgrimes * Return:
4901556Srgrimes *	0 is ok to proceed, no file with the specified name exists
4911556Srgrimes *	-1 we were unable to remove the node, or we should not remove it (-k)
4921556Srgrimes *	1 we found a directory and we were going to create a directory.
4931556Srgrimes */
4941556Srgrimes
4951556Srgrimesint
49690113Simpunlnk_exist(char *name, int type)
4971556Srgrimes{
4981556Srgrimes	struct stat sb;
4991556Srgrimes
5001556Srgrimes	/*
5011556Srgrimes	 * the file does not exist, or -k we are done
5021556Srgrimes	 */
5031556Srgrimes	if (lstat(name, &sb) < 0)
5041556Srgrimes		return(0);
5051556Srgrimes	if (kflag)
5061556Srgrimes		return(-1);
5071556Srgrimes
5081556Srgrimes	if (S_ISDIR(sb.st_mode)) {
5091556Srgrimes		/*
5101556Srgrimes		 * try to remove a directory, if it fails and we were going to
5111556Srgrimes		 * create a directory anyway, tell the caller (return a 1)
5121556Srgrimes		 */
5131556Srgrimes		if (rmdir(name) < 0) {
5141556Srgrimes			if (type == PAX_DIR)
5158855Srgrimes				return(1);
51676017Skris			syswarn(1,errno,"Unable to remove directory %s", name);
5171556Srgrimes			return(-1);
5181556Srgrimes		}
5191556Srgrimes		return(0);
5201556Srgrimes	}
5211556Srgrimes
5221556Srgrimes	/*
5231556Srgrimes	 * try to get rid of all non-directory type nodes
5241556Srgrimes	 */
5251556Srgrimes	if (unlink(name) < 0) {
52676017Skris		syswarn(1, errno, "Could not unlink %s", name);
5271556Srgrimes		return(-1);
5281556Srgrimes	}
5291556Srgrimes	return(0);
5301556Srgrimes}
5311556Srgrimes
5321556Srgrimes/*
5331556Srgrimes * chk_path()
534102230Strhodes *	We were trying to create some kind of node in the file system and it
5351556Srgrimes *	failed. chk_path() makes sure the path up to the node exists and is
5361556Srgrimes *	writeable. When we have to create a directory that is missing along the
5371556Srgrimes *	path somewhere, the directory we create will be set to the same
5381556Srgrimes *	uid/gid as the file has (when uid and gid are being preserved).
5391556Srgrimes *	NOTE: this routine is a real performance loss. It is only used as a
540102230Strhodes *	last resort when trying to create entries in the file system.
5411556Srgrimes * Return:
5421556Srgrimes *	-1 when it could find nothing it is allowed to fix.
5431556Srgrimes *	0 otherwise
5441556Srgrimes */
5451556Srgrimes
5461556Srgrimesint
54790113Simpchk_path( char *name, uid_t st_uid, gid_t st_gid)
5481556Srgrimes{
54990113Simp	char *spt = name;
5501556Srgrimes	struct stat sb;
5511556Srgrimes	int retval = -1;
5521556Srgrimes
5531556Srgrimes	/*
5541556Srgrimes	 * watch out for paths with nodes stored directly in / (e.g. /bozo)
5551556Srgrimes	 */
5561556Srgrimes	if (*spt == '/')
5571556Srgrimes		++spt;
5581556Srgrimes
5591556Srgrimes	for(;;) {
5601556Srgrimes		/*
561222177Suqs		 * work forward from the first / and check each part of the path
5621556Srgrimes		 */
5631556Srgrimes		spt = strchr(spt, '/');
5641556Srgrimes		if (spt == NULL)
5651556Srgrimes			break;
5661556Srgrimes		*spt = '\0';
5671556Srgrimes
5681556Srgrimes		/*
5691556Srgrimes		 * if it exists we assume it is a directory, it is not within
5701556Srgrimes		 * the spec (at least it seems to read that way) to alter the
571102230Strhodes		 * file system for nodes NOT EXPLICITLY stored on the archive.
5721556Srgrimes		 * If that assumption is changed, you would test the node here
5731556Srgrimes		 * and figure out how to get rid of it (probably like some
5741556Srgrimes		 * recursive unlink()) or fix up the directory permissions if
5751556Srgrimes		 * required (do an access()).
5761556Srgrimes		 */
5771556Srgrimes		if (lstat(name, &sb) == 0) {
5781556Srgrimes			*(spt++) = '/';
5791556Srgrimes			continue;
5801556Srgrimes		}
5811556Srgrimes
5821556Srgrimes		/*
5831556Srgrimes		 * the path fails at this point, see if we can create the
5841556Srgrimes		 * needed directory and continue on
5851556Srgrimes		 */
5861556Srgrimes		if (mkdir(name, S_IRWXU | S_IRWXG | S_IRWXO) < 0) {
5871556Srgrimes			*spt = '/';
5881556Srgrimes			retval = -1;
5891556Srgrimes			break;
5901556Srgrimes		}
5911556Srgrimes
5921556Srgrimes		/*
5931556Srgrimes		 * we were able to create the directory. We will tell the
5941556Srgrimes		 * caller that we found something to fix, and it is ok to try
5951556Srgrimes		 * and create the node again.
5961556Srgrimes		 */
5971556Srgrimes		retval = 0;
5981556Srgrimes		if (pids)
5991556Srgrimes			(void)set_ids(name, st_uid, st_gid);
6001556Srgrimes
6011556Srgrimes		/*
602222177Suqs		 * make sure the user doesn't have some strange umask that
6031556Srgrimes		 * causes this newly created directory to be unusable. We fix
6041556Srgrimes		 * the modes and restore them back to the creation default at
6051556Srgrimes		 * the end of pax
6061556Srgrimes		 */
6071556Srgrimes		if ((access(name, R_OK | W_OK | X_OK) < 0) &&
6081556Srgrimes		    (lstat(name, &sb) == 0)) {
6091556Srgrimes			set_pmode(name, ((sb.st_mode & FILEBITS) | S_IRWXU));
6101556Srgrimes			add_dir(name, spt - name, &sb, 1);
6111556Srgrimes		}
6121556Srgrimes		*(spt++) = '/';
6131556Srgrimes		continue;
6141556Srgrimes	}
6151556Srgrimes	return(retval);
6161556Srgrimes}
6171556Srgrimes
6181556Srgrimes/*
6191556Srgrimes * set_ftime()
6201556Srgrimes *	Set the access time and modification time for a named file. If frc is
62176017Skris *	non-zero we force these times to be set even if the user did not
6221556Srgrimes *	request access and/or modification time preservation (this is also
6231556Srgrimes *	used by -t to reset access times).
6241556Srgrimes *	When ign is zero, only those times the user has asked for are set, the
6251556Srgrimes *	other ones are left alone. We do not assume the un-documented feature
626187976Skientzle *	of many lutimes() implementations that consider a 0 time value as a do
6271556Srgrimes *	not set request.
6281556Srgrimes */
6291556Srgrimes
6301556Srgrimesvoid
6311556Srgrimesset_ftime(char *fnm, time_t mtime, time_t atime, int frc)
6321556Srgrimes{
6331556Srgrimes	static struct timeval tv[2] = {{0L, 0L}, {0L, 0L}};
6341556Srgrimes	struct stat sb;
6351556Srgrimes
63685616Sdillon	tv[0].tv_sec = atime;
63785616Sdillon	tv[1].tv_sec = mtime;
6381556Srgrimes	if (!frc && (!patime || !pmtime)) {
6391556Srgrimes		/*
6401556Srgrimes		 * if we are not forcing, only set those times the user wants
6411556Srgrimes		 * set. We get the current values of the times if we need them.
6421556Srgrimes		 */
6431556Srgrimes		if (lstat(fnm, &sb) == 0) {
6441556Srgrimes			if (!patime)
64585616Sdillon				tv[0].tv_sec = sb.st_atime;
6461556Srgrimes			if (!pmtime)
64785616Sdillon				tv[1].tv_sec = sb.st_mtime;
6481556Srgrimes		} else
64976017Skris			syswarn(0,errno,"Unable to obtain file stats %s", fnm);
6501556Srgrimes	}
6511556Srgrimes
6521556Srgrimes	/*
6531556Srgrimes	 * set the times
6541556Srgrimes	 */
655187976Skientzle	if (lutimes(fnm, tv) < 0)
65676017Skris		syswarn(1, errno, "Access/modification time set failed on: %s",
6571556Srgrimes		    fnm);
6581556Srgrimes	return;
6591556Srgrimes}
6601556Srgrimes
6611556Srgrimes/*
6621556Srgrimes * set_ids()
663102230Strhodes *	set the uid and gid of a file system node
6641556Srgrimes * Return:
6651556Srgrimes *	0 when set, -1 on failure
6661556Srgrimes */
6671556Srgrimes
6681556Srgrimesint
6691556Srgrimesset_ids(char *fnm, uid_t uid, gid_t gid)
6701556Srgrimes{
67176351Skris	if (lchown(fnm, uid, gid) < 0) {
67276351Skris		/*
67376351Skris		 * ignore EPERM unless in verbose mode or being run by root.
67476351Skris		 * if running as pax, POSIX requires a warning.
67576351Skris		 */
67676351Skris		if (strcmp(NM_PAX, argv0) == 0 || errno != EPERM || vflag ||
67776351Skris		    geteuid() == 0)
67876351Skris			syswarn(1, errno, "Unable to set file uid/gid of %s",
67976351Skris			    fnm);
68076351Skris		return(-1);
68176351Skris	}
68276351Skris	return(0);
68376351Skris}
68476351Skris
68576351Skris/*
6861556Srgrimes * set_pmode()
6871556Srgrimes *	Set file access mode
6881556Srgrimes */
6891556Srgrimes
6901556Srgrimesvoid
6911556Srgrimesset_pmode(char *fnm, mode_t mode)
6921556Srgrimes{
6931556Srgrimes	mode &= ABITS;
694187976Skientzle	if (lchmod(fnm, mode) < 0)
69576017Skris		syswarn(1, errno, "Could not set permissions on %s", fnm);
6961556Srgrimes	return;
6971556Srgrimes}
6981556Srgrimes
6991556Srgrimes/*
7001556Srgrimes * file_write()
7011556Srgrimes *	Write/copy a file (during copy or archive extract). This routine knows
7021556Srgrimes *	how to copy files with lseek holes in it. (Which are read as file
7031556Srgrimes *	blocks containing all 0's but do not have any file blocks associated
7041556Srgrimes *	with the data). Typical examples of these are files created by dbm
7051556Srgrimes *	variants (.pag files). While the file size of these files are huge, the
7061556Srgrimes *	actual storage is quite small (the files are sparse). The problem is
7071556Srgrimes *	the holes read as all zeros so are probably stored on the archive that
7081556Srgrimes *	way (there is no way to determine if the file block is really a hole,
7091556Srgrimes *	we only know that a file block of all zero's can be a hole).
7101556Srgrimes *	At this writing, no major archive format knows how to archive files
7111556Srgrimes *	with holes. However, on extraction (or during copy, -rw) we have to
7121556Srgrimes *	deal with these files. Without detecting the holes, the files can
7131556Srgrimes *	consume a lot of file space if just written to disk. This replacement
714102230Strhodes *	for write when passed the basic allocation size of a file system block,
7151556Srgrimes *	uses lseek whenever it detects the input data is all 0 within that
7161556Srgrimes *	file block. In more detail, the strategy is as follows:
7171556Srgrimes *	While the input is all zero keep doing an lseek. Keep track of when we
718222177Suqs *	pass over file block boundaries. Only write when we hit a non zero
7191556Srgrimes *	input. once we have written a file block, we continue to write it to
7201556Srgrimes *	the end (we stop looking at the input). When we reach the start of the
7211556Srgrimes *	next file block, start checking for zero blocks again. Working on file
722222177Suqs *	block boundaries significantly reduces the overhead when copying files
7231556Srgrimes *	that are NOT very sparse. This overhead (when compared to a write) is
7241556Srgrimes *	almost below the measurement resolution on many systems. Without it,
7251556Srgrimes *	files with holes cannot be safely copied. It does has a side effect as
7261556Srgrimes *	it can put holes into files that did not have them before, but that is
7271556Srgrimes *	not a problem since the file contents are unchanged (in fact it saves
7281556Srgrimes *	file space). (Except on paging files for diskless clients. But since we
7291556Srgrimes *	cannot determine one of those file from here, we ignore them). If this
7301556Srgrimes *	ever ends up on a system where CTG files are supported and the holes
7311556Srgrimes *	are not desired, just do a conditional test in those routines that
7321556Srgrimes *	call file_write() and have it call write() instead. BEFORE CLOSING THE
7331556Srgrimes *	FILE, make sure to call file_flush() when the last write finishes with
734102230Strhodes *	an empty block. A lot of file systems will not create an lseek hole at
7351556Srgrimes *	the end. In this case we drop a single 0 at the end to force the
7361556Srgrimes *	trailing 0's in the file.
7371556Srgrimes *	---Parameters---
738102230Strhodes *	rem: how many bytes left in this file system block
7391556Srgrimes *	isempt: have we written to the file block yet (is it empty)
7401556Srgrimes *	sz: basic file block allocation size
7411556Srgrimes *	cnt: number of bytes on this write
7421556Srgrimes *	str: buffer to write
7431556Srgrimes * Return:
7441556Srgrimes *	number of bytes written, -1 on write (or lseek) error.
7451556Srgrimes */
7461556Srgrimes
7471556Srgrimesint
74890113Simpfile_write(int fd, char *str, int cnt, int *rem, int *isempt, int sz,
7491556Srgrimes	char *name)
7501556Srgrimes{
75190113Simp	char *pt;
75290113Simp	char *end;
75390113Simp	int wcnt;
75490113Simp	char *st = str;
7558855Srgrimes
7561556Srgrimes	/*
7571556Srgrimes	 * while we have data to process
7581556Srgrimes	 */
7591556Srgrimes	while (cnt) {
7601556Srgrimes		if (!*rem) {
7611556Srgrimes			/*
762102230Strhodes			 * We are now at the start of file system block again
7631556Srgrimes			 * (or what we think one is...). start looking for
7641556Srgrimes			 * empty blocks again
7651556Srgrimes			 */
7661556Srgrimes			*isempt = 1;
7671556Srgrimes			*rem = sz;
7681556Srgrimes		}
7691556Srgrimes
7701556Srgrimes		/*
7711556Srgrimes		 * only examine up to the end of the current file block or
7721556Srgrimes		 * remaining characters to write, whatever is smaller
7731556Srgrimes		 */
7741556Srgrimes		wcnt = MIN(cnt, *rem);
7751556Srgrimes		cnt -= wcnt;
7761556Srgrimes		*rem -= wcnt;
7771556Srgrimes		if (*isempt) {
7781556Srgrimes			/*
7791556Srgrimes			 * have not written to this block yet, so we keep
7801556Srgrimes			 * looking for zero's
7811556Srgrimes			 */
7821556Srgrimes			pt = st;
7831556Srgrimes			end = st + wcnt;
7841556Srgrimes
7851556Srgrimes			/*
7861556Srgrimes			 * look for a zero filled buffer
7871556Srgrimes			 */
7881556Srgrimes			while ((pt < end) && (*pt == '\0'))
7891556Srgrimes				++pt;
7901556Srgrimes
7911556Srgrimes			if (pt == end) {
7921556Srgrimes				/*
7931556Srgrimes				 * skip, buf is empty so far
7941556Srgrimes				 */
7951556Srgrimes				if (lseek(fd, (off_t)wcnt, SEEK_CUR) < 0) {
79676017Skris					syswarn(1,errno,"File seek on %s",
7971556Srgrimes					    name);
7981556Srgrimes					return(-1);
7991556Srgrimes				}
8001556Srgrimes				st = pt;
8011556Srgrimes				continue;
8021556Srgrimes			}
8031556Srgrimes			/*
8041556Srgrimes			 * drat, the buf is not zero filled
8051556Srgrimes			 */
8061556Srgrimes			*isempt = 0;
8071556Srgrimes		}
8081556Srgrimes
8091556Srgrimes		/*
810102230Strhodes		 * have non-zero data in this file system block, have to write
8111556Srgrimes		 */
8121556Srgrimes		if (write(fd, st, wcnt) != wcnt) {
81376017Skris			syswarn(1, errno, "Failed write to file %s", name);
8141556Srgrimes			return(-1);
8151556Srgrimes		}
8161556Srgrimes		st += wcnt;
8171556Srgrimes	}
8181556Srgrimes	return(st - str);
8191556Srgrimes}
8201556Srgrimes
8211556Srgrimes/*
8221556Srgrimes * file_flush()
823102230Strhodes *	when the last file block in a file is zero, many file systems will not
8241556Srgrimes *	let us create a hole at the end. To get the last block with zeros, we
8251556Srgrimes *	write the last BYTE with a zero (back up one byte and write a zero).
8261556Srgrimes */
8271556Srgrimes
8281556Srgrimesvoid
8291556Srgrimesfile_flush(int fd, char *fname, int isempt)
8301556Srgrimes{
8311556Srgrimes	static char blnk[] = "\0";
8321556Srgrimes
8331556Srgrimes	/*
8341556Srgrimes	 * silly test, but make sure we are only called when the last block is
8351556Srgrimes	 * filled with all zeros.
8361556Srgrimes	 */
8371556Srgrimes	if (!isempt)
8381556Srgrimes		return;
8391556Srgrimes
8401556Srgrimes	/*
8411556Srgrimes	 * move back one byte and write a zero
8421556Srgrimes	 */
8431556Srgrimes	if (lseek(fd, (off_t)-1, SEEK_CUR) < 0) {
84476017Skris		syswarn(1, errno, "Failed seek on file %s", fname);
8451556Srgrimes		return;
8461556Srgrimes	}
8471556Srgrimes
8481556Srgrimes	if (write(fd, blnk, 1) < 0)
84976017Skris		syswarn(1, errno, "Failed write to file %s", fname);
8501556Srgrimes	return;
8511556Srgrimes}
8521556Srgrimes
8531556Srgrimes/*
8541556Srgrimes * rdfile_close()
8551556Srgrimes *	close a file we have beed reading (to copy or archive). If we have to
8561556Srgrimes *	reset access time (tflag) do so (the times are stored in arcn).
8571556Srgrimes */
8581556Srgrimes
8591556Srgrimesvoid
86090113Simprdfile_close(ARCHD *arcn, int *fd)
8611556Srgrimes{
8621556Srgrimes	/*
8631556Srgrimes	 * make sure the file is open
8641556Srgrimes	 */
8651556Srgrimes	if (*fd < 0)
8661556Srgrimes		return;
8671556Srgrimes
8681556Srgrimes	(void)close(*fd);
8691556Srgrimes	*fd = -1;
8701556Srgrimes	if (!tflag)
8711556Srgrimes		return;
8721556Srgrimes
8731556Srgrimes	/*
8741556Srgrimes	 * user wants last access time reset
8751556Srgrimes	 */
8761556Srgrimes	set_ftime(arcn->org_name, arcn->sb.st_mtime, arcn->sb.st_atime, 1);
8771556Srgrimes	return;
8781556Srgrimes}
8791556Srgrimes
8801556Srgrimes/*
8811556Srgrimes * set_crc()
8821556Srgrimes *	read a file to calculate its crc. This is a real drag. Archive formats
8831556Srgrimes *	that have this, end up reading the file twice (we have to write the
8841556Srgrimes *	header WITH the crc before writing the file contents. Oh well...
8851556Srgrimes * Return:
8861556Srgrimes *	0 if was able to calculate the crc, -1 otherwise
8871556Srgrimes */
8881556Srgrimes
8891556Srgrimesint
89090113Simpset_crc(ARCHD *arcn, int fd)
8911556Srgrimes{
89290113Simp	int i;
89390113Simp	int res;
8941556Srgrimes	off_t cpcnt = 0L;
8951556Srgrimes	u_long size;
8961556Srgrimes	unsigned long crc = 0L;
8971556Srgrimes	char tbuf[FILEBLK];
8981556Srgrimes	struct stat sb;
8991556Srgrimes
9001556Srgrimes	if (fd < 0) {
9011556Srgrimes		/*
9021556Srgrimes		 * hmm, no fd, should never happen. well no crc then.
9031556Srgrimes		 */
9041556Srgrimes		arcn->crc = 0L;
9051556Srgrimes		return(0);
9061556Srgrimes	}
9071556Srgrimes
9081556Srgrimes	if ((size = (u_long)arcn->sb.st_blksize) > (u_long)sizeof(tbuf))
9091556Srgrimes		size = (u_long)sizeof(tbuf);
9101556Srgrimes
9111556Srgrimes	/*
9121556Srgrimes	 * read all the bytes we think that there are in the file. If the user
9131556Srgrimes	 * is trying to archive an active file, forget this file.
9141556Srgrimes	 */
9151556Srgrimes	for(;;) {
9161556Srgrimes		if ((res = read(fd, tbuf, size)) <= 0)
9171556Srgrimes			break;
9181556Srgrimes		cpcnt += res;
9191556Srgrimes		for (i = 0; i < res; ++i)
9201556Srgrimes			crc += (tbuf[i] & 0xff);
9211556Srgrimes	}
9221556Srgrimes
9231556Srgrimes	/*
9241556Srgrimes	 * safety check. we want to avoid archiving files that are active as
925222177Suqs	 * they can create inconsistent archive copies.
9261556Srgrimes	 */
9271556Srgrimes	if (cpcnt != arcn->sb.st_size)
92876017Skris		paxwarn(1, "File changed size %s", arcn->org_name);
9291556Srgrimes	else if (fstat(fd, &sb) < 0)
93076017Skris		syswarn(1, errno, "Failed stat on %s", arcn->org_name);
9311556Srgrimes	else if (arcn->sb.st_mtime != sb.st_mtime)
93276017Skris		paxwarn(1, "File %s was modified during read", arcn->org_name);
9331556Srgrimes	else if (lseek(fd, (off_t)0L, SEEK_SET) < 0)
93476017Skris		syswarn(1, errno, "File rewind failed on: %s", arcn->org_name);
9351556Srgrimes	else {
9361556Srgrimes		arcn->crc = crc;
9371556Srgrimes		return(0);
9381556Srgrimes	}
9391556Srgrimes	return(-1);
9401556Srgrimes}
941