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