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