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