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