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