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