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