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