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