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