opendir change: refinement
[minix.git] / bin / pax / file_subs.c
blobe6ba65e4998b067f675c8f41b62ab02ae7210561
1 /* $NetBSD: file_subs.c,v 1.62 2009/04/07 19:52:35 perry Exp $ */
3 /*-
4 * Copyright (c) 1992 Keith Muller.
5 * Copyright (c) 1992, 1993
6 * The Regents of the University of California. All rights reserved.
8 * This code is derived from software contributed to Berkeley by
9 * Keith Muller of the University of California, San Diego.
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.
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.
36 #if HAVE_NBTOOL_CONFIG_H
37 #include "nbtool_config.h"
38 #endif
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.62 2009/04/07 19:52:35 perry Exp $");
46 #endif
47 #endif /* not lint */
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"
65 #ifdef __minix
66 #include <utime.h>
67 #endif
69 char *xtmp_name;
71 static int
72 mk_link(char *,struct stat *,char *, int);
74 static int warn_broken;
77 * routines that deal with file operations such as: creating, removing;
78 * and setting access modes, uid/gid and times of files
80 #define SET_BITS (S_ISUID | S_ISGID)
81 #define FILE_BITS (S_IRWXU | S_IRWXG | S_IRWXO)
82 #define A_BITS (FILE_BITS | SET_BITS | S_ISVTX)
85 * The S_ISVTX (sticky bit) can be set by non-superuser on directories
86 * but not other kinds of files.
88 #define FILEBITS(dir) ((dir) ? (FILE_BITS | S_ISVTX) : FILE_BITS)
89 #define SETBITS(dir) ((dir) ? SET_BITS : (SET_BITS | S_ISVTX))
91 static mode_t
92 apply_umask(mode_t mode)
94 static mode_t cached_umask;
95 static int cached_umask_valid;
97 if (!cached_umask_valid) {
98 cached_umask = umask(0);
99 umask(cached_umask);
100 cached_umask_valid = 1;
103 return mode & ~cached_umask;
107 * file_creat()
108 * Create and open a file.
109 * Return:
110 * file descriptor or -1 for failure
114 file_creat(ARCHD *arcn, int write_to_hardlink)
116 int fd = -1;
117 int oerrno;
120 * Some horribly busted tar implementations, have directory nodes
121 * that end in a /, but they mark as files. Compensate for that
122 * by not creating a directory node at this point, but a file node,
123 * and not creating the temp file.
125 if (arcn->nlen != 0 && arcn->name[arcn->nlen - 1] == '/') {
126 if (!warn_broken) {
127 tty_warn(0, "Archive was created with a broken tar;"
128 " file `%s' is a directory, but marked as plain.",
129 arcn->name);
130 warn_broken = 1;
132 return -1;
136 * In "cpio" archives it's usually the last record of a set of
137 * hardlinks which includes the contents of the file. We cannot
138 * use a tempory file in that case because we couldn't link it
139 * with the existing other hardlinks after restoring the contents
140 * to it. And it's also useless to create the hardlink under a
141 * temporary name because the other hardlinks would have partial
142 * contents while restoring.
144 if (write_to_hardlink)
145 return (open(arcn->name, O_TRUNC | O_EXCL | O_RDWR, 0));
148 * Create a temporary file name so that the file doesn't have partial
149 * contents while restoring.
151 arcn->tmp_name = malloc(arcn->nlen + 8);
152 if (arcn->tmp_name == NULL) {
153 syswarn(1, errno, "Cannot malloc %d bytes", arcn->nlen + 8);
154 return -1;
156 if (xtmp_name != NULL)
157 abort();
158 xtmp_name = arcn->tmp_name;
160 for (;;) {
162 * try to create the temporary file we use to restore the
163 * contents info. if this fails, keep checking all the nodes
164 * in the path until chk_path() finds that it cannot fix
165 * anything further. if that happens we just give up.
167 #ifdef __minix
169 /* For minix, generate the temporary filename
170 * conservatively - just write Xes into the last component.
171 * There is space because of the malloc().
173 int cc;
174 char *last_slash;
175 strcpy(arcn->tmp_name, arcn->name);
176 if(!(last_slash = strrchr(arcn->tmp_name, '/')))
177 strcpy(arcn->tmp_name, "XXXXXX");
178 else strcpy(last_slash+1, "XXXXXX");
180 #else
181 (void)snprintf(arcn->tmp_name, arcn->nlen + 8, "%s.XXXXXX",
182 arcn->name);
183 #endif
184 fd = mkstemp(arcn->tmp_name);
185 if (fd >= 0)
186 break;
187 oerrno = errno;
188 if (nodirs || chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
189 (void)fflush(listf);
190 syswarn(1, oerrno, "Cannot create %s", arcn->tmp_name);
191 xtmp_name = NULL;
192 free(arcn->tmp_name);
193 arcn->tmp_name = NULL;
194 return -1;
197 return fd;
201 * file_close()
202 * Close file descriptor to a file just created by pax. Sets modes,
203 * ownership and times as required.
204 * Return:
205 * 0 for success, -1 for failure
208 void
209 file_close(ARCHD *arcn, int fd)
211 char *tmp_name;
212 int res;
214 if (fd < 0)
215 return;
217 tmp_name = (arcn->tmp_name != NULL) ? arcn->tmp_name : arcn->name;
219 if (close(fd) < 0)
220 syswarn(0, errno, "Cannot close file descriptor on %s",
221 tmp_name);
224 * set owner/groups first as this may strip off mode bits we want
225 * then set file permission modes. Then set file access and
226 * modification times.
228 if (pids)
229 res = set_ids(tmp_name, arcn->sb.st_uid, arcn->sb.st_gid);
230 else
231 res = 0;
234 * IMPORTANT SECURITY NOTE:
235 * if not preserving mode or we cannot set uid/gid, then PROHIBIT
236 * set uid/gid bits but restore the file modes (since mkstemp doesn't).
238 if (!pmode || res)
239 arcn->sb.st_mode &= ~SETBITS(0);
240 if (pmode)
241 set_pmode(tmp_name, arcn->sb.st_mode);
242 else
243 set_pmode(tmp_name,
244 apply_umask((arcn->sb.st_mode & FILEBITS(0))));
245 if (patime || pmtime)
246 set_ftime(tmp_name, arcn->sb.st_mtime,
247 arcn->sb.st_atime, 0, 0);
249 /* Did we write directly to the target file? */
250 if (arcn->tmp_name == NULL)
251 return;
254 * Finally, now the temp file is fully instantiated rename it to
255 * the desired file name.
257 if (rename(tmp_name, arcn->name) < 0) {
258 syswarn(0, errno, "Cannot rename %s to %s",
259 tmp_name, arcn->name);
260 (void)unlink(tmp_name);
263 #if HAVE_STRUCT_STAT_ST_FLAGS
264 if (pfflags && arcn->type != PAX_SLK)
265 set_chflags(arcn->name, arcn->sb.st_flags);
266 #endif
268 free(arcn->tmp_name);
269 arcn->tmp_name = NULL;
270 xtmp_name = NULL;
274 * lnk_creat()
275 * Create a hard link to arcn->ln_name from arcn->name. arcn->ln_name
276 * must exist;
277 * Return:
278 * 0 if ok, -1 otherwise
282 lnk_creat(ARCHD *arcn, int *payload)
284 struct stat sb;
287 * Check if this hardlink carries the "payload". In "cpio" archives
288 * it's usually the last record of a set of hardlinks which includes
289 * the contents of the file.
292 *payload = S_ISREG(arcn->sb.st_mode) &&
293 (arcn->sb.st_size > 0) && (arcn->sb.st_size <= arcn->skip);
296 * We may be running as root, so we have to be sure that link target
297 * is not a directory, so we lstat and check. XXX: This is still racy.
299 if (lstat(arcn->ln_name, &sb) != -1 && S_ISDIR(sb.st_mode)) {
300 tty_warn(1, "A hard link to the directory %s is not allowed",
301 arcn->ln_name);
302 return -1;
305 return mk_link(arcn->ln_name, &sb, arcn->name, 0);
309 * cross_lnk()
310 * Create a hard link to arcn->org_name from arcn->name. Only used in copy
311 * with the -l flag. No warning or error if this does not succeed (we will
312 * then just create the file)
313 * Return:
314 * 1 if copy() should try to create this file node
315 * 0 if cross_lnk() ok, -1 for fatal flaw (like linking to self).
319 cross_lnk(ARCHD *arcn)
322 * try to make a link to original file (-l flag in copy mode). make
323 * sure we do not try to link to directories in case we are running as
324 * root (and it might succeed).
326 if (arcn->type == PAX_DIR)
327 return 1;
328 return mk_link(arcn->org_name, &(arcn->sb), arcn->name, 1);
332 * chk_same()
333 * In copy mode if we are not trying to make hard links between the src
334 * and destinations, make sure we are not going to overwrite ourselves by
335 * accident. This slows things down a little, but we have to protect all
336 * those people who make typing errors.
337 * Return:
338 * 1 the target does not exist, go ahead and copy
339 * 0 skip it file exists (-k) or may be the same as source file
343 chk_same(ARCHD *arcn)
345 struct stat sb;
348 * if file does not exist, return. if file exists and -k, skip it
349 * quietly
351 if (lstat(arcn->name, &sb) < 0)
352 return 1;
353 if (kflag)
354 return 0;
357 * better make sure the user does not have src == dest by mistake
359 if ((arcn->sb.st_dev == sb.st_dev) && (arcn->sb.st_ino == sb.st_ino)) {
360 tty_warn(1, "Unable to copy %s, file would overwrite itself",
361 arcn->name);
362 return 0;
364 return 1;
368 * mk_link()
369 * try to make a hard link between two files. if ign set, we do not
370 * complain.
371 * Return:
372 * 0 if successful (or we are done with this file but no error, such as
373 * finding the from file exists and the user has set -k).
374 * 1 when ign was set to indicates we could not make the link but we
375 * should try to copy/extract the file as that might work (and is an
376 * allowed option). -1 an error occurred.
379 static int
380 mk_link(char *to, struct stat *to_sb, char *from, int ign)
382 struct stat sb;
383 int oerrno;
386 * if from file exists, it has to be unlinked to make the link. If the
387 * file exists and -k is set, skip it quietly
389 if (lstat(from, &sb) == 0) {
390 if (kflag)
391 return 0;
394 * make sure it is not the same file, protect the user
396 if ((to_sb->st_dev==sb.st_dev)&&(to_sb->st_ino == sb.st_ino)) {
397 tty_warn(1, "Cannot link file %s to itself", to);
398 return -1;
402 * try to get rid of the file, based on the type
404 if (S_ISDIR(sb.st_mode) && strcmp(from, ".") != 0) {
405 if (rmdir(from) < 0) {
406 syswarn(1, errno, "Cannot remove %s", from);
407 return -1;
409 } else if (unlink(from) < 0) {
410 if (!ign) {
411 syswarn(1, errno, "Cannot remove %s", from);
412 return -1;
414 return 1;
419 * from file is gone (or did not exist), try to make the hard link.
420 * if it fails, check the path and try it again (if chk_path() says to
421 * try again)
423 for (;;) {
424 if (link(to, from) == 0)
425 break;
426 oerrno = errno;
427 if (chk_path(from, to_sb->st_uid, to_sb->st_gid) == 0)
428 continue;
429 if (!ign) {
430 syswarn(1, oerrno, "Cannot link to %s from %s", to,
431 from);
432 return -1;
434 return 1;
438 * all right the link was made
440 return 0;
444 * node_creat()
445 * create an entry in the file system (other than a file or hard link).
446 * If successful, sets uid/gid modes and times as required.
447 * Return:
448 * 0 if ok, -1 otherwise
452 node_creat(ARCHD *arcn)
454 int res;
455 int ign = 0;
456 int oerrno;
457 int pass = 0;
458 mode_t file_mode;
459 struct stat sb;
460 char target[MAXPATHLEN];
461 char *nm = arcn->name;
462 int len;
465 * create node based on type, if that fails try to unlink the node and
466 * try again. finally check the path and try again. As noted in the
467 * file and link creation routines, this method seems to exhibit the
468 * best performance in general use workloads.
470 file_mode = arcn->sb.st_mode & FILEBITS(arcn->type == PAX_DIR);
472 for (;;) {
473 switch (arcn->type) {
474 case PAX_DIR:
476 * If -h (or -L) was given in tar-mode, follow the
477 * potential symlink chain before trying to create the
478 * directory.
480 if (strcmp(NM_TAR, argv0) == 0 && Lflag) {
481 while (lstat(nm, &sb) == 0 &&
482 S_ISLNK(sb.st_mode)) {
483 len = readlink(nm, target,
484 sizeof target - 1);
485 if (len == -1) {
486 syswarn(0, errno,
487 "cannot follow symlink %s "
488 "in chain for %s",
489 nm, arcn->name);
490 res = -1;
491 goto badlink;
493 target[len] = '\0';
494 nm = target;
497 res = domkdir(nm, file_mode);
498 badlink:
499 if (ign)
500 res = 0;
501 break;
502 case PAX_CHR:
503 file_mode |= S_IFCHR;
504 res = mknod(nm, file_mode, arcn->sb.st_rdev);
505 break;
506 case PAX_BLK:
507 file_mode |= S_IFBLK;
508 res = mknod(nm, file_mode, arcn->sb.st_rdev);
509 break;
510 case PAX_FIF:
511 res = mkfifo(nm, file_mode);
512 break;
513 case PAX_SCK:
515 * Skip sockets, operation has no meaning under BSD
517 tty_warn(0,
518 "%s skipped. Sockets cannot be copied or extracted",
519 nm);
520 return (-1);
521 case PAX_SLK:
522 res = symlink(arcn->ln_name, nm);
523 break;
524 case PAX_CTG:
525 case PAX_HLK:
526 case PAX_HRG:
527 case PAX_REG:
528 default:
530 * we should never get here
532 tty_warn(0, "%s has an unknown file type, skipping",
533 nm);
534 return (-1);
538 * if we were able to create the node break out of the loop,
539 * otherwise try to unlink the node and try again. if that
540 * fails check the full path and try a final time.
542 if (res == 0)
543 break;
546 * we failed to make the node
548 oerrno = errno;
549 switch (pass++) {
550 case 0:
551 if ((ign = unlnk_exist(nm, arcn->type)) < 0)
552 return (-1);
553 continue;
555 case 1:
556 if (nodirs ||
557 chk_path(nm, arcn->sb.st_uid,
558 arcn->sb.st_gid) < 0) {
559 syswarn(1, oerrno, "Cannot create %s", nm);
560 return (-1);
562 continue;
566 * it must be a file that exists but we can't create or
567 * remove, but we must avoid the infinite loop.
569 break;
573 * we were able to create the node. set uid/gid, modes and times
575 if (pids)
576 res = set_ids(nm, arcn->sb.st_uid, arcn->sb.st_gid);
577 else
578 res = 0;
581 * IMPORTANT SECURITY NOTE:
582 * if not preserving mode or we cannot set uid/gid, then PROHIBIT any
583 * set uid/gid bits
585 if (!pmode || res)
586 arcn->sb.st_mode &= ~SETBITS(arcn->type == PAX_DIR);
587 if (pmode)
588 set_pmode(arcn->name, arcn->sb.st_mode);
590 if (arcn->type == PAX_DIR && strcmp(NM_CPIO, argv0) != 0) {
592 * Dirs must be processed again at end of extract to set times
593 * and modes to agree with those stored in the archive. However
594 * to allow extract to continue, we may have to also set owner
595 * rights. This allows nodes in the archive that are children
596 * of this directory to be extracted without failure. Both time
597 * and modes will be fixed after the entire archive is read and
598 * before pax exits.
600 if (access(nm, R_OK | W_OK | X_OK) < 0) {
601 if (lstat(nm, &sb) < 0) {
602 syswarn(0, errno,"Cannot access %s (stat)",
603 arcn->name);
604 set_pmode(nm,file_mode | S_IRWXU);
605 } else {
607 * We have to add rights to the dir, so we make
608 * sure to restore the mode. The mode must be
609 * restored AS CREATED and not as stored if
610 * pmode is not set.
612 set_pmode(nm, ((sb.st_mode &
613 FILEBITS(arcn->type == PAX_DIR)) |
614 S_IRWXU));
615 if (!pmode)
616 arcn->sb.st_mode = sb.st_mode;
620 * we have to force the mode to what was set here,
621 * since we changed it from the default as created.
623 add_dir(nm, arcn->nlen, &(arcn->sb), 1);
624 } else if (pmode || patime || pmtime)
625 add_dir(nm, arcn->nlen, &(arcn->sb), 0);
628 if (patime || pmtime)
629 set_ftime(arcn->name, arcn->sb.st_mtime,
630 arcn->sb.st_atime, 0, (arcn->type == PAX_SLK) ? 1 : 0);
632 #if HAVE_STRUCT_STAT_ST_FLAGS
633 if (pfflags && arcn->type != PAX_SLK)
634 set_chflags(arcn->name, arcn->sb.st_flags);
635 #endif
636 return 0;
640 * unlnk_exist()
641 * Remove node from file system with the specified name. We pass the type
642 * of the node that is going to replace it. When we try to create a
643 * directory and find that it already exists, we allow processing to
644 * continue as proper modes etc will always be set for it later on.
645 * Return:
646 * 0 is ok to proceed, no file with the specified name exists
647 * -1 we were unable to remove the node, or we should not remove it (-k)
648 * 1 we found a directory and we were going to create a directory.
652 unlnk_exist(char *name, int type)
654 struct stat sb;
657 * the file does not exist, or -k we are done
659 if (lstat(name, &sb) < 0)
660 return 0;
661 if (kflag)
662 return -1;
664 if (S_ISDIR(sb.st_mode)) {
666 * try to remove a directory, if it fails and we were going to
667 * create a directory anyway, tell the caller (return a 1).
669 * don't try to remove the directory if the name is "."
670 * otherwise later file/directory creation fails.
672 if (strcmp(name, ".") == 0)
673 return 1;
674 if (rmdir(name) < 0) {
675 if (type == PAX_DIR)
676 return 1;
677 syswarn(1, errno, "Cannot remove directory %s", name);
678 return -1;
680 return 0;
684 * try to get rid of all non-directory type nodes
686 if (unlink(name) < 0) {
687 (void)fflush(listf);
688 syswarn(1, errno, "Cannot unlink %s", name);
689 return -1;
691 return 0;
695 * chk_path()
696 * We were trying to create some kind of node in the file system and it
697 * failed. chk_path() makes sure the path up to the node exists and is
698 * writable. When we have to create a directory that is missing along the
699 * path somewhere, the directory we create will be set to the same
700 * uid/gid as the file has (when uid and gid are being preserved).
701 * NOTE: this routine is a real performance loss. It is only used as a
702 * last resort when trying to create entries in the file system.
703 * Return:
704 * -1 when it could find nothing it is allowed to fix.
705 * 0 otherwise
709 chk_path(char *name, uid_t st_uid, gid_t st_gid)
711 char *spt = name;
712 struct stat sb;
713 int retval = -1;
716 * watch out for paths with nodes stored directly in / (e.g. /bozo)
718 if (*spt == '/')
719 ++spt;
721 for(;;) {
723 * work forward from the first / and check each part of
724 * the path
726 spt = strchr(spt, '/');
727 if (spt == NULL)
728 break;
729 *spt = '\0';
732 * if it exists we assume it is a directory, it is not within
733 * the spec (at least it seems to read that way) to alter the
734 * file system for nodes NOT EXPLICITLY stored on the archive.
735 * If that assumption is changed, you would test the node here
736 * and figure out how to get rid of it (probably like some
737 * recursive unlink()) or fix up the directory permissions if
738 * required (do an access()).
740 if (lstat(name, &sb) == 0) {
741 *(spt++) = '/';
742 continue;
746 * the path fails at this point, see if we can create the
747 * needed directory and continue on
749 if (domkdir(name, S_IRWXU | S_IRWXG | S_IRWXO) == -1) {
750 *spt = '/';
751 retval = -1;
752 break;
756 * we were able to create the directory. We will tell the
757 * caller that we found something to fix, and it is ok to try
758 * and create the node again.
760 retval = 0;
761 if (pids)
762 (void)set_ids(name, st_uid, st_gid);
765 * make sure the user doesn't have some strange umask that
766 * causes this newly created directory to be unusable. We fix
767 * the modes and restore them back to the creation default at
768 * the end of pax
770 if ((access(name, R_OK | W_OK | X_OK) < 0) &&
771 (lstat(name, &sb) == 0)) {
772 set_pmode(name, ((sb.st_mode & FILEBITS(0)) |
773 S_IRWXU));
774 add_dir(name, spt - name, &sb, 1);
776 *(spt++) = '/';
777 continue;
780 * We perform one final check here, because if someone else
781 * created the directory in parallel with us, we might return
782 * the wrong error code, even if the directory exists now.
784 if (retval == -1 && stat(name, &sb) == 0 && S_ISDIR(sb.st_mode))
785 retval = 0;
786 return retval;
790 * set_ftime()
791 * Set the access time and modification time for a named file. If frc
792 * is non-zero we force these times to be set even if the user did not
793 * request access and/or modification time preservation (this is also
794 * used by -t to reset access times).
795 * When ign is zero, only those times the user has asked for are set, the
796 * other ones are left alone. We do not assume the un-documented feature
797 * of many utimes() implementations that consider a 0 time value as a do
798 * not set request.
800 * Unfortunately, there are systems where lutimes() is present but does
801 * not work on some filesystem types, which cannot be detected at
802 * compile time. This requires passing down symlink knowledge into
803 * this function to obtain correct operation. Linux with XFS is one
804 * example of such a system.
807 void
808 set_ftime(char *fnm, time_t mtime, time_t atime, int frc, int slk)
810 struct timeval tv[2];
811 struct stat sb;
813 tv[0].tv_sec = (long)atime;
814 tv[0].tv_usec = 0;
815 tv[1].tv_sec = (long)mtime;
816 tv[1].tv_usec = 0;
817 if (!frc && (!patime || !pmtime)) {
819 * if we are not forcing, only set those times the user wants
820 * set. We get the current values of the times if we need them.
822 if (lstat(fnm, &sb) == 0) {
823 #if BSD4_4 && !HAVE_NBTOOL_CONFIG_H
824 if (!patime)
825 TIMESPEC_TO_TIMEVAL(&tv[0], &sb.st_atimespec);
826 if (!pmtime)
827 TIMESPEC_TO_TIMEVAL(&tv[1], &sb.st_mtimespec);
828 #else
829 if (!patime)
830 tv[0].tv_sec = sb.st_atime;
831 if (!pmtime)
832 tv[1].tv_sec = sb.st_mtime;
833 #endif
834 } else
835 syswarn(0, errno, "Cannot obtain file stats %s", fnm);
839 * set the times
841 #if HAVE_LUTIMES
842 if (lutimes(fnm, tv) == 0)
843 return;
844 if (errno != ENOSYS) /* XXX linux: lutimes is per-FS */
845 goto bad;
846 #endif
847 if (slk)
848 return;
849 #ifdef __minix
851 struct utimbuf timp;
852 timp.actime = atime;
853 timp.modtime = mtime;
854 if (utime(fnm, &timp) < 0)
855 goto bad;
857 #else
858 if (utimes(fnm, tv) == -1)
859 goto bad;
860 #endif
861 return;
862 bad:
863 syswarn(1, errno, "Access/modification time set failed on: %s", fnm);
867 * set_ids()
868 * set the uid and gid of a file system node
869 * Return:
870 * 0 when set, -1 on failure
874 set_ids(char *fnm, uid_t uid, gid_t gid)
876 if (geteuid() == 0)
877 if (lchown(fnm, uid, gid)) {
878 (void)fflush(listf);
879 syswarn(1, errno, "Cannot set file uid/gid of %s",
880 fnm);
881 return -1;
883 return 0;
887 * set_pmode()
888 * Set file access mode
891 void
892 set_pmode(char *fnm, mode_t mode)
894 mode &= A_BITS;
895 if (lchmod(fnm, mode)) {
896 (void)fflush(listf);
897 syswarn(1, errno, "Cannot set permissions on %s", fnm);
899 return;
903 * set_chflags()
904 * Set 4.4BSD file flags
906 void
907 set_chflags(char *fnm, u_int32_t flags)
910 #if 0
911 if (chflags(fnm, flags) < 0 && errno != EOPNOTSUPP)
912 syswarn(1, errno, "Cannot set file flags on %s", fnm);
913 #endif
914 return;
918 * file_write()
919 * Write/copy a file (during copy or archive extract). This routine knows
920 * how to copy files with lseek holes in it. (Which are read as file
921 * blocks containing all 0's but do not have any file blocks associated
922 * with the data). Typical examples of these are files created by dbm
923 * variants (.pag files). While the file size of these files are huge, the
924 * actual storage is quite small (the files are sparse). The problem is
925 * the holes read as all zeros so are probably stored on the archive that
926 * way (there is no way to determine if the file block is really a hole,
927 * we only know that a file block of all zero's can be a hole).
928 * At this writing, no major archive format knows how to archive files
929 * with holes. However, on extraction (or during copy, -rw) we have to
930 * deal with these files. Without detecting the holes, the files can
931 * consume a lot of file space if just written to disk. This replacement
932 * for write when passed the basic allocation size of a file system block,
933 * uses lseek whenever it detects the input data is all 0 within that
934 * file block. In more detail, the strategy is as follows:
935 * While the input is all zero keep doing an lseek. Keep track of when we
936 * pass over file block boundaries. Only write when we hit a non zero
937 * input. once we have written a file block, we continue to write it to
938 * the end (we stop looking at the input). When we reach the start of the
939 * next file block, start checking for zero blocks again. Working on file
940 * block boundaries significantly reduces the overhead when copying files
941 * that are NOT very sparse. This overhead (when compared to a write) is
942 * almost below the measurement resolution on many systems. Without it,
943 * files with holes cannot be safely copied. It does has a side effect as
944 * it can put holes into files that did not have them before, but that is
945 * not a problem since the file contents are unchanged (in fact it saves
946 * file space). (Except on paging files for diskless clients. But since we
947 * cannot determine one of those file from here, we ignore them). If this
948 * ever ends up on a system where CTG files are supported and the holes
949 * are not desired, just do a conditional test in those routines that
950 * call file_write() and have it call write() instead. BEFORE CLOSING THE
951 * FILE, make sure to call file_flush() when the last write finishes with
952 * an empty block. A lot of file systems will not create an lseek hole at
953 * the end. In this case we drop a single 0 at the end to force the
954 * trailing 0's in the file.
955 * ---Parameters---
956 * rem: how many bytes left in this file system block
957 * isempt: have we written to the file block yet (is it empty)
958 * sz: basic file block allocation size
959 * cnt: number of bytes on this write
960 * str: buffer to write
961 * Return:
962 * number of bytes written, -1 on write (or lseek) error.
966 file_write(int fd, char *str, int cnt, int *rem, int *isempt, int sz,
967 char *name)
969 char *pt;
970 char *end;
971 int wcnt;
972 char *st = str;
973 char **strp;
974 size_t *lenp;
977 * while we have data to process
979 while (cnt) {
980 if (!*rem) {
982 * We are now at the start of file system block again
983 * (or what we think one is...). start looking for
984 * empty blocks again
986 *isempt = 1;
987 *rem = sz;
991 * only examine up to the end of the current file block or
992 * remaining characters to write, whatever is smaller
994 wcnt = MIN(cnt, *rem);
995 cnt -= wcnt;
996 *rem -= wcnt;
997 if (*isempt) {
999 * have not written to this block yet, so we keep
1000 * looking for zero's
1002 pt = st;
1003 end = st + wcnt;
1006 * look for a zero filled buffer
1008 while ((pt < end) && (*pt == '\0'))
1009 ++pt;
1011 if (pt == end) {
1013 * skip, buf is empty so far
1015 if (fd > -1 &&
1016 lseek(fd, (off_t)wcnt, SEEK_CUR) < 0) {
1017 syswarn(1, errno, "File seek on %s",
1018 name);
1019 return -1;
1021 st = pt;
1022 continue;
1025 * drat, the buf is not zero filled
1027 *isempt = 0;
1031 * have non-zero data in this file system block, have to write
1033 switch (fd) {
1034 case -PAX_GLF:
1035 strp = &gnu_name_string;
1036 lenp = &gnu_name_length;
1037 break;
1038 case -PAX_GLL:
1039 strp = &gnu_link_string;
1040 lenp = &gnu_link_length;
1041 break;
1042 default:
1043 strp = NULL;
1044 lenp = NULL;
1045 break;
1047 if (strp) {
1048 char *nstr = *strp ? realloc(*strp, *lenp + wcnt + 1) :
1049 malloc(wcnt + 1);
1050 if (nstr == NULL) {
1051 tty_warn(1, "Out of memory");
1052 return -1;
1054 (void)strlcpy(&nstr[*lenp], st, wcnt + 1);
1055 *strp = nstr;
1056 *lenp += wcnt;
1057 } else if (xwrite(fd, st, wcnt) != wcnt) {
1058 syswarn(1, errno, "Failed write to file %s", name);
1059 return -1;
1061 st += wcnt;
1063 return st - str;
1067 * file_flush()
1068 * when the last file block in a file is zero, many file systems will not
1069 * let us create a hole at the end. To get the last block with zeros, we
1070 * write the last BYTE with a zero (back up one byte and write a zero).
1073 void
1074 file_flush(int fd, char *fname, int isempt)
1076 static char blnk[] = "\0";
1079 * silly test, but make sure we are only called when the last block is
1080 * filled with all zeros.
1082 if (!isempt)
1083 return;
1086 * move back one byte and write a zero
1088 if (lseek(fd, (off_t)-1, SEEK_CUR) < 0) {
1089 syswarn(1, errno, "Failed seek on file %s", fname);
1090 return;
1093 if (write_with_restart(fd, blnk, 1) < 0)
1094 syswarn(1, errno, "Failed write to file %s", fname);
1095 return;
1099 * rdfile_close()
1100 * close a file we have been reading (to copy or archive). If we have to
1101 * reset access time (tflag) do so (the times are stored in arcn).
1104 void
1105 rdfile_close(ARCHD *arcn, int *fd)
1108 * make sure the file is open
1110 if (*fd < 0)
1111 return;
1113 (void)close(*fd);
1114 *fd = -1;
1115 if (!tflag)
1116 return;
1119 * user wants last access time reset
1121 set_ftime(arcn->org_name, arcn->sb.st_mtime, arcn->sb.st_atime, 1, 0);
1122 return;
1126 * set_crc()
1127 * read a file to calculate its crc. This is a real drag. Archive formats
1128 * that have this, end up reading the file twice (we have to write the
1129 * header WITH the crc before writing the file contents. Oh well...
1130 * Return:
1131 * 0 if was able to calculate the crc, -1 otherwise
1135 set_crc(ARCHD *arcn, int fd)
1137 int i;
1138 int res;
1139 off_t cpcnt = 0L;
1140 u_long size;
1141 unsigned long crc = 0L;
1142 char tbuf[FILEBLK];
1143 struct stat sb;
1145 if (fd < 0) {
1147 * hmm, no fd, should never happen. well no crc then.
1149 arcn->crc = 0L;
1150 return 0;
1153 if ((size = (u_long)arcn->sb.st_blksize) > (u_long)sizeof(tbuf))
1154 size = (u_long)sizeof(tbuf);
1157 * read all the bytes we think that there are in the file. If the user
1158 * is trying to archive an active file, forget this file.
1160 for(;;) {
1161 if ((res = read(fd, tbuf, size)) <= 0)
1162 break;
1163 cpcnt += res;
1164 for (i = 0; i < res; ++i)
1165 crc += (tbuf[i] & 0xff);
1169 * safety check. we want to avoid archiving files that are active as
1170 * they can create inconsistent archive copies.
1172 if (cpcnt != arcn->sb.st_size)
1173 tty_warn(1, "File changed size %s", arcn->org_name);
1174 else if (fstat(fd, &sb) < 0)
1175 syswarn(1, errno, "Failed stat on %s", arcn->org_name);
1176 else if (arcn->sb.st_mtime != sb.st_mtime)
1177 tty_warn(1, "File %s was modified during read", arcn->org_name);
1178 else if (lseek(fd, (off_t)0L, SEEK_SET) < 0)
1179 syswarn(1, errno, "File rewind failed on: %s", arcn->org_name);
1180 else {
1181 arcn->crc = crc;
1182 return 0;
1184 return -1;