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