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