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