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