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