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