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