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