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