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