don't bother resolving onbld python module deps
[unleashed.git] / bin / pax / file_subs.c
blob9f834bf1748f222e936b8e707a372f092fd6c3b8
1 /* $OpenBSD: file_subs.c,v 1.53 2017/01/21 08:17:06 krw Exp $ */
2 /* $NetBSD: file_subs.c,v 1.4 1995/03/21 09:07:18 cgd Exp $ */
4 /*-
5 * Copyright (c) 1992 Keith Muller.
6 * Copyright (c) 1992, 1993
7 * The Regents of the University of California. All rights reserved.
9 * This code is derived from software contributed to Berkeley by
10 * Keith Muller of the University of California, San Diego.
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.
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.
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"
49 static int
50 mk_link(char *, struct stat *, char *, int);
53 * routines that deal with file operations such as: creating, removing;
54 * and setting access modes, uid/gid and times of files
58 * file_creat()
59 * Create and open a file.
60 * Return:
61 * file descriptor or -1 for failure
64 int
65 file_creat(ARCHD *arcn)
67 int fd = -1;
68 mode_t file_mode;
69 int oerrno;
72 * Assume file doesn't exist, so just try to create it, most times this
73 * works. We have to take special handling when the file does exist. To
74 * detect this, we use O_EXCL. For example when trying to create a
75 * file and a character device or fifo exists with the same name, we
76 * can accidently open the device by mistake (or block waiting to open).
77 * If we find that the open has failed, then spend the effort to
78 * figure out why. This strategy was found to have better average
79 * performance in common use than checking the file (and the path)
80 * first with lstat.
82 file_mode = arcn->sb.st_mode & FILEBITS;
83 if ((fd = open(arcn->name, O_WRONLY | O_CREAT | O_EXCL,
84 file_mode)) >= 0)
85 return(fd);
88 * the file seems to exist. First we try to get rid of it (found to be
89 * the second most common failure when traced). If this fails, only
90 * then we go to the expense to check and create the path to the file
92 if (unlnk_exist(arcn->name, arcn->type) != 0)
93 return(-1);
95 for (;;) {
97 * try to open it again, if this fails, check all the nodes in
98 * the path and give it a final try. if chk_path() finds that
99 * it cannot fix anything, we will skip the last attempt
101 if ((fd = open(arcn->name, O_WRONLY | O_CREAT | O_TRUNC,
102 file_mode)) >= 0)
103 break;
104 oerrno = errno;
105 if (nodirs || chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
106 syswarn(1, oerrno, "Unable to create %s", arcn->name);
107 return(-1);
110 return(fd);
114 * file_close()
115 * Close file descriptor to a file just created by pax. Sets modes,
116 * ownership and times as required.
117 * Return:
118 * 0 for success, -1 for failure
121 void
122 file_close(ARCHD *arcn, int fd)
124 int res = 0;
126 if (fd < 0)
127 return;
130 * set owner/groups first as this may strip off mode bits we want
131 * then set file permission modes. Then set file access and
132 * modification times.
134 if (pids)
135 res = fset_ids(arcn->name, fd, arcn->sb.st_uid,
136 arcn->sb.st_gid);
139 * IMPORTANT SECURITY NOTE:
140 * if not preserving mode or we cannot set uid/gid, then PROHIBIT
141 * set uid/gid bits
143 if (!pmode || res)
144 arcn->sb.st_mode &= ~(SETBITS);
145 if (pmode)
146 fset_pmode(arcn->name, fd, arcn->sb.st_mode);
147 if (patime || pmtime)
148 fset_ftime(arcn->name, fd, &arcn->sb.st_mtim,
149 &arcn->sb.st_atim, 0);
150 if (close(fd) < 0)
151 syswarn(0, errno, "Unable to close file descriptor on %s",
152 arcn->name);
156 * lnk_creat()
157 * Create a hard link to arcn->ln_name from arcn->name. arcn->ln_name
158 * must exist;
159 * Return:
160 * 0 if ok, -1 otherwise
164 lnk_creat(ARCHD *arcn)
166 struct stat sb;
167 int res;
170 * we may be running as root, so we have to be sure that link target
171 * is not a directory, so we lstat and check
173 if (lstat(arcn->ln_name, &sb) < 0) {
174 syswarn(1,errno,"Unable to link to %s from %s", arcn->ln_name,
175 arcn->name);
176 return(-1);
179 if (S_ISDIR(sb.st_mode)) {
180 paxwarn(1, "A hard link to the directory %s is not allowed",
181 arcn->ln_name);
182 return(-1);
185 res = mk_link(arcn->ln_name, &sb, arcn->name, 0);
186 if (res == 0) {
187 /* check for a hardlink to a placeholder symlink */
188 res = sltab_add_link(arcn->name, &sb);
190 if (res < 0) {
191 /* arrgh, it failed, clean up */
192 unlink(arcn->name);
196 return (res);
200 * cross_lnk()
201 * Create a hard link to arcn->org_name from arcn->name. Only used in copy
202 * with the -l flag. No warning or error if this does not succeed (we will
203 * then just create the file)
204 * Return:
205 * 1 if copy() should try to create this file node
206 * 0 if cross_lnk() ok, -1 for fatal flaw (like linking to self).
210 cross_lnk(ARCHD *arcn)
213 * try to make a link to original file (-l flag in copy mode). make
214 * sure we do not try to link to directories in case we are running as
215 * root (and it might succeed).
217 if (arcn->type == PAX_DIR)
218 return(1);
219 return(mk_link(arcn->org_name, &(arcn->sb), arcn->name, 1));
223 * chk_same()
224 * In copy mode if we are not trying to make hard links between the src
225 * and destinations, make sure we are not going to overwrite ourselves by
226 * accident. This slows things down a little, but we have to protect all
227 * those people who make typing errors.
228 * Return:
229 * 1 the target does not exist, go ahead and copy
230 * 0 skip it file exists (-k) or may be the same as source file
234 chk_same(ARCHD *arcn)
236 struct stat sb;
239 * if file does not exist, return. if file exists and -k, skip it
240 * quietly
242 if (lstat(arcn->name, &sb) < 0)
243 return(1);
244 if (kflag)
245 return(0);
248 * better make sure the user does not have src == dest by mistake
250 if ((arcn->sb.st_dev == sb.st_dev) && (arcn->sb.st_ino == sb.st_ino)) {
251 paxwarn(1, "Unable to copy %s, file would overwrite itself",
252 arcn->name);
253 return(0);
255 return(1);
259 * mk_link()
260 * try to make a hard link between two files. if ign set, we do not
261 * complain.
262 * Return:
263 * 0 if successful (or we are done with this file but no error, such as
264 * finding the from file exists and the user has set -k).
265 * 1 when ign was set to indicates we could not make the link but we
266 * should try to copy/extract the file as that might work (and is an
267 * allowed option). -1 an error occurred.
270 static int
271 mk_link(char *to, struct stat *to_sb, char *from, int ign)
273 struct stat sb;
274 int oerrno;
277 * if from file exists, it has to be unlinked to make the link. If the
278 * file exists and -k is set, skip it quietly
280 if (lstat(from, &sb) == 0) {
281 if (kflag)
282 return(0);
285 * make sure it is not the same file, protect the user
287 if ((to_sb->st_dev==sb.st_dev)&&(to_sb->st_ino == sb.st_ino)) {
288 paxwarn(1, "Unable to link file %s to itself", to);
289 return(-1);
293 * try to get rid of the file, based on the type
295 if (S_ISDIR(sb.st_mode)) {
296 if (rmdir(from) < 0) {
297 syswarn(1, errno, "Unable to remove %s", from);
298 return(-1);
300 delete_dir(sb.st_dev, sb.st_ino);
301 } else if (unlink(from) < 0) {
302 if (!ign) {
303 syswarn(1, errno, "Unable to remove %s", from);
304 return(-1);
306 return(1);
311 * from file is gone (or did not exist), try to make the hard link.
312 * if it fails, check the path and try it again (if chk_path() says to
313 * try again)
315 for (;;) {
316 if (linkat(AT_FDCWD, to, AT_FDCWD, from, 0) == 0)
317 break;
318 oerrno = errno;
319 if (!nodirs && chk_path(from, to_sb->st_uid, to_sb->st_gid) == 0)
320 continue;
321 if (!ign) {
322 syswarn(1, oerrno, "Could not link to %s from %s", to,
323 from);
324 return(-1);
326 return(1);
330 * all right the link was made
332 return(0);
336 * node_creat()
337 * create an entry in the file system (other than a file or hard link).
338 * If successful, sets uid/gid modes and times as required.
339 * Return:
340 * 0 if ok, -1 otherwise
344 node_creat(ARCHD *arcn)
346 int res;
347 int ign = 0;
348 int oerrno;
349 int pass = 0;
350 mode_t file_mode;
351 struct stat sb;
352 char target[PATH_MAX];
353 char *nm = arcn->name;
354 int len, defer_pmode = 0;
357 * create node based on type, if that fails try to unlink the node and
358 * try again. finally check the path and try again. As noted in the
359 * file and link creation routines, this method seems to exhibit the
360 * best performance in general use workloads.
362 file_mode = arcn->sb.st_mode & FILEBITS;
364 for (;;) {
365 switch (arcn->type) {
366 case PAX_DIR:
368 * If -h (or -L) was given in tar-mode, follow the
369 * potential symlink chain before trying to create the
370 * directory.
372 if (op_mode == OP_TAR && Lflag) {
373 while (lstat(nm, &sb) == 0 &&
374 S_ISLNK(sb.st_mode)) {
375 len = readlink(nm, target,
376 sizeof target - 1);
377 if (len == -1) {
378 syswarn(0, errno,
379 "cannot follow symlink %s in chain for %s",
380 nm, arcn->name);
381 res = -1;
382 goto badlink;
384 target[len] = '\0';
385 nm = target;
388 res = mkdir(nm, file_mode);
390 badlink:
391 if (ign)
392 res = 0;
393 break;
394 case PAX_CHR:
395 file_mode |= S_IFCHR;
396 res = mknod(nm, file_mode, arcn->sb.st_rdev);
397 break;
398 case PAX_BLK:
399 file_mode |= S_IFBLK;
400 res = mknod(nm, file_mode, arcn->sb.st_rdev);
401 break;
402 case PAX_FIF:
403 res = mkfifo(nm, file_mode);
404 break;
405 case PAX_SCK:
407 * Skip sockets, operation has no meaning under BSD
409 paxwarn(0,
410 "%s skipped. Sockets cannot be copied or extracted",
411 nm);
412 return(-1);
413 case PAX_SLK:
414 if (arcn->ln_name[0] != '/' &&
415 !has_dotdot(arcn->ln_name))
416 res = symlink(arcn->ln_name, nm);
417 else {
419 * absolute symlinks and symlinks with ".."
420 * have to be deferred to prevent the archive
421 * from bootstrapping itself to outside the
422 * working directory.
424 res = sltab_add_sym(nm, arcn->ln_name,
425 arcn->sb.st_mode);
426 if (res == 0)
427 defer_pmode = 1;
429 break;
430 case PAX_CTG:
431 case PAX_HLK:
432 case PAX_HRG:
433 case PAX_REG:
434 default:
436 * we should never get here
438 paxwarn(0, "%s has an unknown file type, skipping",
439 nm);
440 return(-1);
444 * if we were able to create the node break out of the loop,
445 * otherwise try to unlink the node and try again. if that
446 * fails check the full path and try a final time.
448 if (res == 0)
449 break;
452 * we failed to make the node
454 oerrno = errno;
455 if ((ign = unlnk_exist(nm, arcn->type)) < 0)
456 return(-1);
458 if (++pass <= 1)
459 continue;
461 if (nodirs || chk_path(nm,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
462 syswarn(1, oerrno, "Could not create: %s", nm);
463 return(-1);
468 * we were able to create the node. set uid/gid, modes and times
470 if (pids)
471 res = set_ids(nm, arcn->sb.st_uid, arcn->sb.st_gid);
472 else
473 res = 0;
476 * IMPORTANT SECURITY NOTE:
477 * if not preserving mode or we cannot set uid/gid, then PROHIBIT any
478 * set uid/gid bits
480 if (!pmode || res)
481 arcn->sb.st_mode &= ~(SETBITS);
482 if (pmode && !defer_pmode)
483 set_pmode(nm, arcn->sb.st_mode);
485 if (arcn->type == PAX_DIR && op_mode != OP_CPIO) {
487 * Dirs must be processed again at end of extract to set times
488 * and modes to agree with those stored in the archive. However
489 * to allow extract to continue, we may have to also set owner
490 * rights. This allows nodes in the archive that are children
491 * of this directory to be extracted without failure. Both time
492 * and modes will be fixed after the entire archive is read and
493 * before pax exits. To do that safely, we want the dev+ino
494 * of the directory we created.
496 if (lstat(nm, &sb) < 0) {
497 syswarn(0, errno,"Could not access %s (stat)", nm);
498 } else if (access(nm, R_OK | W_OK | X_OK) < 0) {
500 * We have to add rights to the dir, so we make
501 * sure to restore the mode. The mode must be
502 * restored AS CREATED and not as stored if
503 * pmode is not set.
505 set_pmode(nm,
506 ((sb.st_mode & FILEBITS) | S_IRWXU));
507 if (!pmode)
508 arcn->sb.st_mode = sb.st_mode;
511 * we have to force the mode to what was set
512 * here, since we changed it from the default
513 * as created.
515 arcn->sb.st_dev = sb.st_dev;
516 arcn->sb.st_ino = sb.st_ino;
517 add_dir(nm, &(arcn->sb), 1);
518 } else if (pmode || patime || pmtime) {
519 arcn->sb.st_dev = sb.st_dev;
520 arcn->sb.st_ino = sb.st_ino;
521 add_dir(nm, &(arcn->sb), 0);
523 } else if (patime || pmtime)
524 set_ftime(nm, &arcn->sb.st_mtim, &arcn->sb.st_atim, 0);
525 return(0);
529 * unlnk_exist()
530 * Remove node from file system with the specified name. We pass the type
531 * of the node that is going to replace it. When we try to create a
532 * directory and find that it already exists, we allow processing to
533 * continue as proper modes etc will always be set for it later on.
534 * Return:
535 * 0 is ok to proceed, no file with the specified name exists
536 * -1 we were unable to remove the node, or we should not remove it (-k)
537 * 1 we found a directory and we were going to create a directory.
541 unlnk_exist(char *name, int type)
543 struct stat sb;
546 * the file does not exist, or -k we are done
548 if (lstat(name, &sb) < 0)
549 return(0);
550 if (kflag)
551 return(-1);
553 if (S_ISDIR(sb.st_mode)) {
555 * try to remove a directory, if it fails and we were going to
556 * create a directory anyway, tell the caller (return a 1)
558 if (rmdir(name) < 0) {
559 if (type == PAX_DIR)
560 return(1);
561 syswarn(1,errno,"Unable to remove directory %s", name);
562 return(-1);
564 delete_dir(sb.st_dev, sb.st_ino);
565 return(0);
569 * try to get rid of all non-directory type nodes
571 if (unlink(name) < 0) {
572 syswarn(1, errno, "Could not unlink %s", name);
573 return(-1);
575 return(0);
579 * chk_path()
580 * We were trying to create some kind of node in the file system and it
581 * failed. chk_path() makes sure the path up to the node exists and is
582 * writeable. When we have to create a directory that is missing along the
583 * path somewhere, the directory we create will be set to the same
584 * uid/gid as the file has (when uid and gid are being preserved).
585 * NOTE: this routine is a real performance loss. It is only used as a
586 * last resort when trying to create entries in the file system.
587 * Return:
588 * -1 when it could find nothing it is allowed to fix.
589 * 0 otherwise
593 chk_path(char *name, uid_t st_uid, gid_t st_gid)
595 char *spt = name;
596 char *next;
597 struct stat sb;
598 int retval = -1;
601 * watch out for paths with nodes stored directly in / (e.g. /bozo)
603 while (*spt == '/')
604 ++spt;
606 for (;;) {
608 * work forward from the first / and check each part of the path
610 spt = strchr(spt, '/');
611 if (spt == NULL)
612 break;
615 * skip over duplicate slashes; stop if there're only
616 * trailing slashes left
618 next = spt + 1;
619 while (*next == '/')
620 next++;
621 if (*next == '\0')
622 break;
624 *spt = '\0';
627 * if it exists we assume it is a directory, it is not within
628 * the spec (at least it seems to read that way) to alter the
629 * file system for nodes NOT EXPLICITLY stored on the archive.
630 * If that assumption is changed, you would test the node here
631 * and figure out how to get rid of it (probably like some
632 * recursive unlink()) or fix up the directory permissions if
633 * required (do an access()).
635 if (lstat(name, &sb) == 0) {
636 *spt = '/';
637 spt = next;
638 continue;
642 * the path fails at this point, see if we can create the
643 * needed directory and continue on
645 if (mkdir(name, S_IRWXU | S_IRWXG | S_IRWXO) < 0) {
646 *spt = '/';
647 retval = -1;
648 break;
652 * we were able to create the directory. We will tell the
653 * caller that we found something to fix, and it is ok to try
654 * and create the node again.
656 retval = 0;
657 if (pids)
658 (void)set_ids(name, st_uid, st_gid);
661 * make sure the user doesn't have some strange umask that
662 * causes this newly created directory to be unusable. We fix
663 * the modes and restore them back to the creation default at
664 * the end of pax
666 if ((access(name, R_OK | W_OK | X_OK) < 0) &&
667 (lstat(name, &sb) == 0)) {
668 set_pmode(name, ((sb.st_mode & FILEBITS) | S_IRWXU));
669 add_dir(name, &sb, 1);
671 *spt = '/';
672 spt = next;
673 continue;
675 return(retval);
679 * set_ftime()
680 * Set the access time and modification time for a named file. If frc
681 * is non-zero we force these times to be set even if the user did not
682 * request access and/or modification time preservation (this is also
683 * used by -t to reset access times).
684 * When ign is zero, only those times the user has asked for are set, the
685 * other ones are left alone.
688 void
689 set_ftime(const char *fnm, const struct timespec *mtimp,
690 const struct timespec *atimp, int frc)
692 struct timespec tv[2];
694 tv[0] = *atimp;
695 tv[1] = *mtimp;
697 if (!frc) {
699 * if we are not forcing, only set those times the user wants
700 * set.
702 if (!patime)
703 tv[0].tv_nsec = UTIME_OMIT;
704 if (!pmtime)
705 tv[1].tv_nsec = UTIME_OMIT;
709 * set the times
711 if (utimensat(AT_FDCWD, fnm, tv, AT_SYMLINK_NOFOLLOW) < 0)
712 syswarn(1, errno, "Access/modification time set failed on: %s",
713 fnm);
716 void
717 fset_ftime(const char *fnm, int fd, const struct timespec *mtimp,
718 const struct timespec *atimp, int frc)
720 struct timespec tv[2];
723 tv[0] = *atimp;
724 tv[1] = *mtimp;
726 if (!frc) {
728 * if we are not forcing, only set those times the user wants
729 * set.
731 if (!patime)
732 tv[0].tv_nsec = UTIME_OMIT;
733 if (!pmtime)
734 tv[1].tv_nsec = UTIME_OMIT;
737 * set the times
739 if (futimens(fd, tv) < 0)
740 syswarn(1, errno, "Access/modification time set failed on: %s",
741 fnm);
745 * set_ids()
746 * set the uid and gid of a file system node
747 * Return:
748 * 0 when set, -1 on failure
752 set_ids(char *fnm, uid_t uid, gid_t gid)
754 if (fchownat(AT_FDCWD, fnm, uid, gid, AT_SYMLINK_NOFOLLOW) < 0) {
756 * ignore EPERM unless in verbose mode or being run by root.
757 * if running as pax, POSIX requires a warning.
759 if (op_mode == OP_PAX || errno != EPERM || vflag ||
760 geteuid() == 0)
761 syswarn(1, errno, "Unable to set file uid/gid of %s",
762 fnm);
763 return(-1);
765 return(0);
769 fset_ids(char *fnm, int fd, uid_t uid, gid_t gid)
771 if (fchown(fd, uid, gid) < 0) {
773 * ignore EPERM unless in verbose mode or being run by root.
774 * if running as pax, POSIX requires a warning.
776 if (op_mode == OP_PAX || errno != EPERM || vflag ||
777 geteuid() == 0)
778 syswarn(1, errno, "Unable to set file uid/gid of %s",
779 fnm);
780 return(-1);
782 return(0);
786 * set_pmode()
787 * Set file access mode
790 void
791 set_pmode(char *fnm, mode_t mode)
793 mode &= ABITS;
794 if (fchmodat(AT_FDCWD, fnm, mode, AT_SYMLINK_NOFOLLOW) < 0)
795 syswarn(1, errno, "Could not set permissions on %s", fnm);
798 void
799 fset_pmode(char *fnm, int fd, mode_t mode)
801 mode &= ABITS;
802 if (fchmod(fd, mode) < 0)
803 syswarn(1, errno, "Could not set permissions on %s", fnm);
807 * set_attr()
808 * Given a DIRDATA, restore the mode and times as indicated, but
809 * only after verifying that it's the directory that we wanted.
812 set_attr(const struct file_times *ft, int force_times, mode_t mode,
813 int do_mode, int in_sig)
815 struct stat sb;
816 int fd, r;
818 if (!do_mode && !force_times && !patime && !pmtime)
819 return (0);
822 * We could legitimately go through a symlink here,
823 * so do *not* use O_NOFOLLOW. The dev+ino check will
824 * protect us from evil.
826 fd = open(ft->ft_name, O_RDONLY | O_DIRECTORY);
827 if (fd == -1) {
828 if (!in_sig)
829 syswarn(1, errno, "Unable to restore mode and times"
830 " for directory: %s", ft->ft_name);
831 return (-1);
834 if (fstat(fd, &sb) == -1) {
835 if (!in_sig)
836 syswarn(1, errno, "Unable to stat directory: %s",
837 ft->ft_name);
838 r = -1;
839 } else if (ft->ft_ino != sb.st_ino || ft->ft_dev != sb.st_dev) {
840 if (!in_sig)
841 paxwarn(1, "Directory vanished before restoring"
842 " mode and times: %s", ft->ft_name);
843 r = -1;
844 } else {
845 /* Whew, it's a match! Is there anything to change? */
846 if (do_mode && (mode & ABITS) != (sb.st_mode & ABITS))
847 fset_pmode(ft->ft_name, fd, mode);
848 if (((force_times || patime) &&
849 timespeccmp(&ft->ft_atim, &sb.st_atim, !=)) ||
850 ((force_times || pmtime) &&
851 timespeccmp(&ft->ft_mtim, &sb.st_mtim, !=)))
852 fset_ftime(ft->ft_name, fd, &ft->ft_mtim,
853 &ft->ft_atim, force_times);
854 r = 0;
856 close(fd);
858 return (r);
863 * file_write()
864 * Write/copy a file (during copy or archive extract). This routine knows
865 * how to copy files with lseek holes in it. (Which are read as file
866 * blocks containing all 0's but do not have any file blocks associated
867 * with the data). Typical examples of these are files created by dbm
868 * variants (.pag files). While the file size of these files are huge, the
869 * actual storage is quite small (the files are sparse). The problem is
870 * the holes read as all zeros so are probably stored on the archive that
871 * way (there is no way to determine if the file block is really a hole,
872 * we only know that a file block of all zero's can be a hole).
873 * At this writing, no major archive format knows how to archive files
874 * with holes. However, on extraction (or during copy, -rw) we have to
875 * deal with these files. Without detecting the holes, the files can
876 * consume a lot of file space if just written to disk. This replacement
877 * for write when passed the basic allocation size of a file system block,
878 * uses lseek whenever it detects the input data is all 0 within that
879 * file block. In more detail, the strategy is as follows:
880 * While the input is all zero keep doing an lseek. Keep track of when we
881 * pass over file block boundaries. Only write when we hit a non zero
882 * input. once we have written a file block, we continue to write it to
883 * the end (we stop looking at the input). When we reach the start of the
884 * next file block, start checking for zero blocks again. Working on file
885 * block boundaries significantly reduces the overhead when copying files
886 * that are NOT very sparse. This overhead (when compared to a write) is
887 * almost below the measurement resolution on many systems. Without it,
888 * files with holes cannot be safely copied. It does has a side effect as
889 * it can put holes into files that did not have them before, but that is
890 * not a problem since the file contents are unchanged (in fact it saves
891 * file space). (Except on paging files for diskless clients. But since we
892 * cannot determine one of those file from here, we ignore them). If this
893 * ever ends up on a system where CTG files are supported and the holes
894 * are not desired, just do a conditional test in those routines that
895 * call file_write() and have it call write() instead. BEFORE CLOSING THE
896 * FILE, make sure to call file_flush() when the last write finishes with
897 * an empty block. A lot of file systems will not create an lseek hole at
898 * the end. In this case we drop a single 0 at the end to force the
899 * trailing 0's in the file.
900 * ---Parameters---
901 * rem: how many bytes left in this file system block
902 * isempt: have we written to the file block yet (is it empty)
903 * sz: basic file block allocation size
904 * cnt: number of bytes on this write
905 * str: buffer to write
906 * Return:
907 * number of bytes written, -1 on write (or lseek) error.
911 file_write(int fd, char *str, int cnt, int *rem, int *isempt, int sz,
912 char *name)
914 char *pt;
915 char *end;
916 int wcnt;
917 char *st = str;
918 char **strp;
921 * while we have data to process
923 while (cnt) {
924 if (!*rem) {
926 * We are now at the start of file system block again
927 * (or what we think one is...). start looking for
928 * empty blocks again
930 *isempt = 1;
931 *rem = sz;
935 * only examine up to the end of the current file block or
936 * remaining characters to write, whatever is smaller
938 wcnt = MINIMUM(cnt, *rem);
939 cnt -= wcnt;
940 *rem -= wcnt;
941 if (*isempt) {
943 * have not written to this block yet, so we keep
944 * looking for zero's
946 pt = st;
947 end = st + wcnt;
950 * look for a zero filled buffer
952 while ((pt < end) && (*pt == '\0'))
953 ++pt;
955 if (pt == end) {
957 * skip, buf is empty so far
959 if (fd > -1 &&
960 lseek(fd, wcnt, SEEK_CUR) < 0) {
961 syswarn(1,errno,"File seek on %s",
962 name);
963 return(-1);
965 st = pt;
966 continue;
969 * drat, the buf is not zero filled
971 *isempt = 0;
975 * have non-zero data in this file system block, have to write
977 switch (fd) {
978 case -1:
979 strp = &gnu_name_string;
980 break;
981 case -2:
982 strp = &gnu_link_string;
983 break;
984 default:
985 strp = NULL;
986 break;
988 if (strp) {
989 if (*strp)
990 err(1, "WARNING! Major Internal Error! GNU hack Failing!");
991 *strp = malloc(wcnt + 1);
992 if (*strp == NULL) {
993 paxwarn(1, "Out of memory");
994 return(-1);
996 memcpy(*strp, st, wcnt);
997 (*strp)[wcnt] = '\0';
998 break;
999 } else if (write(fd, st, wcnt) != wcnt) {
1000 syswarn(1, errno, "Failed write to file %s", name);
1001 return(-1);
1003 st += wcnt;
1005 return(st - str);
1009 * file_flush()
1010 * when the last file block in a file is zero, many file systems will not
1011 * let us create a hole at the end. To get the last block with zeros, we
1012 * write the last BYTE with a zero (back up one byte and write a zero).
1015 void
1016 file_flush(int fd, char *fname, int isempt)
1018 static char blnk[] = "\0";
1021 * silly test, but make sure we are only called when the last block is
1022 * filled with all zeros.
1024 if (!isempt)
1025 return;
1028 * move back one byte and write a zero
1030 if (lseek(fd, -1, SEEK_CUR) < 0) {
1031 syswarn(1, errno, "Failed seek on file %s", fname);
1032 return;
1035 if (write(fd, blnk, 1) < 0)
1036 syswarn(1, errno, "Failed write to file %s", fname);
1040 * rdfile_close()
1041 * close a file we have been reading (to copy or archive). If we have to
1042 * reset access time (tflag) do so (the times are stored in arcn).
1045 void
1046 rdfile_close(ARCHD *arcn, int *fd)
1049 * make sure the file is open
1051 if (*fd < 0)
1052 return;
1055 * user wants last access time reset
1057 if (tflag)
1058 fset_ftime(arcn->org_name, *fd, &arcn->sb.st_mtim,
1059 &arcn->sb.st_atim, 1);
1061 (void)close(*fd);
1062 *fd = -1;
1066 * set_crc()
1067 * read a file to calculate its crc. This is a real drag. Archive formats
1068 * that have this, end up reading the file twice (we have to write the
1069 * header WITH the crc before writing the file contents. Oh well...
1070 * Return:
1071 * 0 if was able to calculate the crc, -1 otherwise
1075 set_crc(ARCHD *arcn, int fd)
1077 int i;
1078 int res;
1079 off_t cpcnt = 0;
1080 size_t size;
1081 u_int32_t crc = 0;
1082 char tbuf[FILEBLK];
1083 struct stat sb;
1085 if (fd < 0) {
1087 * hmm, no fd, should never happen. well no crc then.
1089 arcn->crc = 0;
1090 return(0);
1093 if ((size = arcn->sb.st_blksize) > sizeof(tbuf))
1094 size = sizeof(tbuf);
1097 * read all the bytes we think that there are in the file. If the user
1098 * is trying to archive an active file, forget this file.
1100 for (;;) {
1101 if ((res = read(fd, tbuf, size)) <= 0)
1102 break;
1103 cpcnt += res;
1104 for (i = 0; i < res; ++i)
1105 crc += (tbuf[i] & 0xff);
1109 * safety check. we want to avoid archiving files that are active as
1110 * they can create inconsistent archive copies.
1112 if (cpcnt != arcn->sb.st_size)
1113 paxwarn(1, "File changed size %s", arcn->org_name);
1114 else if (fstat(fd, &sb) < 0)
1115 syswarn(1, errno, "Failed stat on %s", arcn->org_name);
1116 else if (timespeccmp(&arcn->sb.st_mtim, &sb.st_mtim, !=))
1117 paxwarn(1, "File %s was modified during read", arcn->org_name);
1118 else if (lseek(fd, 0, SEEK_SET) < 0)
1119 syswarn(1, errno, "File rewind failed on: %s", arcn->org_name);
1120 else {
1121 arcn->crc = crc;
1122 return(0);
1124 return(-1);