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