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