1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
|
/* $OpenBSD: file_subs.c,v 1.53 2017/01/21 08:17:06 krw Exp $ */
/* $NetBSD: file_subs.c,v 1.4 1995/03/21 09:07:18 cgd Exp $ */
/*-
* Copyright (c) 2007, 2008, 2009, 2012, 2014, 2016, 2018, 2019, 2024
* mirabilos <m@mirbsd.org>
* Copyright (c) 2018
* Jonathan de Boyne Pollard <J.deBoynePollard-newsgroups@NTLWorld.COM>
* mirabilos <t.glaser@tarent.de>
* Copyright (c) 2011
* Svante Signell <svante.signell@telia.com>
* Copyright (c) 1992 Keith Muller.
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Keith Muller of the University of California, San Diego.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/stat.h>
#if HAVE_BOTH_TIME_H
#include <sys/time.h>
#include <time.h>
#elif HAVE_SYS_TIME_H
#include <sys/time.h>
#elif HAVE_TIME_H
#include <time.h>
#endif
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if HAVE_STRINGS_H
#include <strings.h>
#endif
#include <unistd.h>
#if HAVE_UTIME_H
#include <utime.h>
#endif
#include "pax.h"
#define EXTERN
#include "ftimes.h"
#undef EXTERN
#include "extern.h"
__RCSID("$MirOS: src/bin/pax/file_subs.c,v 1.33 2024/08/17 23:33:51 tg Exp $");
/*
* routines that deal with file operations such as: creating, removing;
* and setting access modes, uid/gid and times of files
*/
#if HAVE_FUTIMENS || HAVE_FUTIMES
#define PAX_FSET_FTIME
#endif
static int mk_link(char *, struct stat *, char *, int);
#ifdef PAX_FSET_FTIME
static void fset_ftime(const char *, int, const struct stat *, int);
#endif
/*
* file_creat()
* Create and open a file.
* Return:
* file descriptor or -1 for failure
*/
int
file_creat(ARCHD *arcn)
{
int fd = -1;
mode_t file_mode;
int oerrno;
/*
* Assume file doesn't exist, so just try to create it, most times this
* works. We have to take special handling when the file does exist. To
* detect this, we use O_EXCL. For example when trying to create a
* file and a character device or FIFO exists with the same name, we
* can accidently open the device by mistake (or block waiting to open).
* If we find that the open has failed, then spend the effort to
* figure out why. This strategy was found to have better average
* performance in common use than checking the file (and the path)
* first with lstat.
*/
file_mode = arcn->sb.st_mode & FILEBITS;
if ((fd = binopen3(0, arcn->name, O_WRONLY | O_CREAT | O_EXCL,
file_mode)) >= 0)
return (fd);
/*
* the file seems to exist. First we try to get rid of it (found to be
* the second most common failure when traced). If this fails, only
* then we go to the expense to check and create the path to the file
*/
if (unlnk_exist(arcn->name, arcn->type) != 0)
return(-1);
for (;;) {
/*
* try to open it again, if this fails, check all the nodes in
* the path and give it a final try. if chk_path() finds that
* it cannot fix anything, we will skip the last attempt
*/
if ((fd = binopen3(0, arcn->name, O_WRONLY | O_CREAT | O_TRUNC,
file_mode)) >= 0)
break;
oerrno = errno;
if (nodirs || chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
syswarn(1, oerrno, "Unable to create %s", arcn->name);
return(-1);
}
}
return(fd);
}
/*
* file_close()
* Close file descriptor to a file just created by pax. Sets modes,
* ownership and times as required.
* Return:
* 0 for success, -1 for failure
*/
void
file_close(ARCHD *arcn, int fd)
{
int res = 0;
if (fd < 0)
return;
/*
* set owner/groups first as this may strip off mode bits we want
* then set file permission modes. Then set file access and
* modification times.
*/
if (pids)
res = fset_ids(arcn->name, fd, arcn->sb.st_uid,
arcn->sb.st_gid);
/*
* IMPORTANT SECURITY NOTE:
* if not preserving mode or we cannot set uid/gid, then PROHIBIT
* set uid/gid bits
*/
if (!pmode || res)
arcn->sb.st_mode &= ~(SETBITS);
if (pmode)
fset_pmode(arcn->name, fd, arcn->sb.st_mode);
#ifdef PAX_FSET_FTIME
if (patime || pmtime)
fset_ftime(arcn->name, fd, &arcn->sb, 0);
#endif
if (close(fd) < 0)
syswarn(0, errno, "Unable to close file descriptor on %s",
arcn->name);
}
/*
* lnk_creat()
* Create a hard link to arcn->ln_name from arcn->name. arcn->ln_name
* must exist;
* Return:
* fd+2 if data should be extracted,
* 0 if ok, 1 if we could not make the link, -1 otherwise
*/
int
lnk_creat(ARCHD *arcn, int *fdp)
{
struct stat sb;
int res;
/*
* we may be running as root, so we have to be sure that link target
* is not a directory, so we lstat and check
*/
if (lstat(arcn->ln_name, &sb) < 0) {
syswarn(1, errno, "Unable to link to %s from %s",
arcn->ln_name, arcn->name);
return (-1);
}
if (S_ISDIR(sb.st_mode)) {
paxwarn(1, "A hard link to the directory %s is not allowed",
arcn->ln_name);
return(-1);
}
res = mk_link(arcn->ln_name, &sb, arcn->name, 0);
if (res == 0) {
/* check for a hardlink to a placeholder symlink */
res = sltab_add_link(arcn->name, &sb);
if (res < 0) {
/* arrgh, it failed, clean up */
unlink(arcn->name);
}
}
if (fdp != NULL && res == 0 && sb.st_size == 0 && arcn->skip > 0) {
/* request to write out file data late (broken archive) */
if (pmode)
set_pmode(arcn->name, 0600, /*XXX I think */ 0);
if ((*fdp = binopen2(0, arcn->name, O_WRONLY | O_TRUNC)) == -1) {
res = errno;
syswarn(1, res, "Unable to re-open %s", arcn->name);
if (pmode)
set_pmode(arcn->name, sb.st_mode, 0);
}
res = 0;
} else if (fdp != NULL)
*fdp = -1;
return (res);
}
/*
* cross_lnk()
* Create a hard link to arcn->org_name from arcn->name. Only used in copy
* with the -l flag. No warning or error if this does not succeed (we will
* then just create the file)
* Return:
* 1 if copy() should try to create this file node
* 0 if cross_lnk() ok, -1 for fatal flaw (like linking to self).
*/
int
cross_lnk(ARCHD *arcn)
{
/*
* try to make a link to original file (-l flag in copy mode). make
* sure we do not try to link to directories in case we are running as
* root (and it might succeed).
*/
if (arcn->type == PAX_DIR)
return(1);
return(mk_link(arcn->org_name, &(arcn->sb), arcn->name, 1));
}
/*
* chk_same()
* In copy mode if we are not trying to make hard links between the src
* and destinations, make sure we are not going to overwrite ourselves by
* accident. This slows things down a little, but we have to protect all
* those people who make typing errors.
* Return:
* 1 the target does not exist, go ahead and copy
* 0 skip it file exists (-k) or may be the same as source file
*/
int
chk_same(ARCHD *arcn)
{
struct stat sb;
/*
* if file does not exist, return. if file exists and -k, skip it
* quietly
*/
if (lstat(arcn->name, &sb) < 0)
return(1);
if (kflag)
return(0);
/*
* better make sure the user does not have src == dest by mistake
*/
if ((arcn->sb.st_dev == sb.st_dev) && (arcn->sb.st_ino == sb.st_ino)) {
paxwarn(1, "Unable to copy %s, file would overwrite itself",
arcn->name);
return(0);
}
return(1);
}
/*
* helper function to copy a symbolic link
*/
static int
mk_link_symlink(const char *to, const char *from)
{
int cnt;
char buf[PAXPATHLEN + 1];
if ((cnt = readlink(to, buf, PAXPATHLEN)) < 0)
return (-1);
/* cf. comment in ftree.c:next_file() */
buf[cnt] = '\0';
return (symlink(buf, from));
}
/*
* mk_link()
* try to make a hard link between two files. if ign set, we do not
* complain.
* Return:
* 0 if successful (or we are done with this file but no error, such as
* finding the from file exists and the user has set -k).
* 1 when ign was set to indicates we could not make the link but we
* should try to copy/extract the file as that might work (and is an
* allowed option). -1 an error occurred.
*/
static int
mk_link(char *to, struct stat *to_sb, char *from, int ign)
{
struct stat sb;
int oerrno;
/*
* if from file exists, it has to be unlinked to make the link. If the
* file exists and -k is set, skip it quietly
*/
if (lstat(from, &sb) == 0) {
if (kflag)
return(0);
/*
* make sure it is not the same file, protect the user
*/
if ((to_sb->st_dev==sb.st_dev)&&(to_sb->st_ino == sb.st_ino)) {
paxwarn(1, "Unable to link file %s to itself", to);
return(-1);
}
/*
* try to get rid of the file, based on the type
*/
if (S_ISDIR(sb.st_mode)) {
if (rmdir(from) < 0) {
syswarn(1, errno, "Unable to remove %s", from);
return(-1);
}
delete_dir(sb.st_dev, sb.st_ino);
} else if (unlink(from) < 0) {
if (!ign) {
syswarn(1, errno, "Unable to remove %s", from);
return(-1);
}
return(1);
}
}
/*
* from file is gone (or did not exist), try to make the hard link.
* if it fails, check the path and try it again (if chk_path() says to
* try again)
*/
for (;;) {
#if HAVE_LINKAT
if (linkat(AT_FDCWD, to, AT_FDCWD, from, 0) == 0)
#else
if (link(to, from) == 0)
#endif
break;
oerrno = errno;
if (S_ISLNK(to_sb->st_mode)) {
/* just copy the symlink */
if (mk_link_symlink(to, from) == 0)
break;
}
if (!nodirs && chk_path(from, to_sb->st_uid, to_sb->st_gid) == 0)
continue;
/*-
* non-standard (via -M lncp) cross-device link handling:
* copy if hard link fails (but what if there are several
* links for the same file mixed between several devices?
* this code copies for all non-original devices, instead
* of tracking them and linking between them on their re-
* spective target device)
*/
if (oerrno == EXDEV && (anonarch & ANON_LNCP)) {
int fdsrc, fddest;
ARCHD tarcn;
if ((fdsrc = binopen3(0, to, O_RDONLY, 0)) < 0) {
if (!ign)
syswarn(1, errno,
"Unable to open %s to read", to);
goto lncp_failed;
}
strlcpy(tarcn.name, from, sizeof(tarcn.name));
memcpy(&tarcn.sb, to_sb, sizeof(struct stat));
tarcn.type = PAX_REG; /* XXX */
tarcn.org_name = to;
if ((fddest = file_creat(&tarcn)) < 0) {
rdfile_close(&tarcn, &fdsrc);
goto lncp_failed;
}
cp_file(&tarcn, fdsrc, fddest);
file_close(&tarcn, fddest);
rdfile_close(&tarcn, &fdsrc);
/* file copied successfully, continue on */
break;
}
if (!ign) {
lncp_failed:
syswarn(1, oerrno, "Unable to link to %s from %s",
to, from);
return (-1);
}
return (1);
}
/*
* all right the link was made
*/
return (0);
}
/*
* node_creat()
* create an entry in the filesystem (other than a file or hard link).
* If successful, sets uid/gid modes and times as required.
* Return:
* 0 if ok, -1 otherwise
*/
int
node_creat(ARCHD *arcn)
{
int res;
int ign = 0;
int oerrno;
int pass = 0;
mode_t file_mode;
struct stat sb;
char *allocd = NULL;
char *nm = arcn->name;
int len, defer_pmode = 0;
/*
* create node based on type, if that fails try to unlink the node and
* try again. finally check the path and try again. As noted in the
* file and link creation routines, this method seems to exhibit the
* best performance in general use workloads.
*/
file_mode = arcn->sb.st_mode & FILEBITS;
for (;;) {
switch (arcn->type) {
case PAX_DIR:
/*
* If -h (or -L) was given in tar-mode, follow the
* potential symlink chain before trying to create the
* directory.
*/
if (op_mode == OP_TAR && Lflag) {
while (lstat(nm, &sb) == 0 &&
S_ISLNK(sb.st_mode)) {
char *target = malloc(sb.st_size + 1);
if (target == NULL) {
free(allocd);
oerrno = ENOMEM;
syswarn(1, oerrno,
"Out of memory");
return (-1);
}
len = readlink(nm, target,
sb.st_size + 1);
if (len == -1) {
syswarn(0, errno,
"cannot follow symlink %s in chain for %s",
nm, arcn->name);
res = -1;
goto badlink;
}
target[len] = '\0';
nm = target;
free(allocd);
allocd = target;
}
}
res = mkdir(nm, file_mode);
badlink:
if (ign)
res = 0;
break;
case PAX_CHR:
file_mode |= S_IFCHR;
res = mknod(nm, file_mode, arcn->sb.st_rdev);
break;
case PAX_BLK:
file_mode |= S_IFBLK;
res = mknod(nm, file_mode, arcn->sb.st_rdev);
break;
case PAX_FIF:
res = mkfifo(nm, file_mode);
break;
case PAX_SCK:
/*
* Skip sockets, operation has no meaning under BSD
*/
paxwarn(0,
"%s skipped. Sockets cannot be copied or extracted",
nm);
free(allocd);
return (-1);
case PAX_SLK:
if (arcn->ln_name[0] != '/' &&
!has_dotdot(arcn->ln_name))
res = symlink(arcn->ln_name, nm);
else {
/*
* absolute symlinks and symlinks with ".."
* have to be deferred to prevent the archive
* from bootstrapping itself to outside the
* working directory.
*/
res = sltab_add_sym(nm, arcn->ln_name,
arcn->sb.st_mode);
if (res == 0)
defer_pmode = 1;
}
break;
case PAX_CTG:
case PAX_HLK:
case PAX_HRG:
case PAX_REG:
default:
/*
* we should never get here
*/
paxwarn(0, "%s has an unknown file type, skipping",
nm);
free(allocd);
return (-1);
}
/*
* if we were able to create the node break out of the loop,
* otherwise try to unlink the node and try again. if that
* fails check the full path and try a final time.
*/
if (res == 0)
break;
/*
* we failed to make the node
*/
oerrno = errno;
if ((ign = unlnk_exist(nm, arcn->type)) < 0) {
free(allocd);
return (-1);
}
if (++pass <= 1)
continue;
if (nodirs || chk_path(nm,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
syswarn(1, oerrno, "Unable to create %s", nm);
free(allocd);
return (-1);
}
}
/*
* we were able to create the node. set uid/gid, modes and times
*/
if (pids)
res = set_ids(nm, arcn->sb.st_uid, arcn->sb.st_gid,
arcn->type == PAX_SLK);
else
res = 0;
/*
* IMPORTANT SECURITY NOTE:
* if not preserving mode or we cannot set uid/gid, then PROHIBIT any
* set uid/gid bits
*/
if (!pmode || res)
arcn->sb.st_mode &= ~(SETBITS);
if (pmode && !defer_pmode)
set_pmode(nm, arcn->sb.st_mode, arcn->type == PAX_SLK);
if (arcn->type == PAX_DIR && op_mode != OP_CPIO) {
/*
* Dirs must be processed again at end of extract to set times
* and modes to agree with those stored in the archive. However
* to allow extract to continue, we may have to also set owner
* rights. This allows nodes in the archive that are children
* of this directory to be extracted without failure. Both time
* and modes will be fixed after the entire archive is read and
* before pax exits. To do that safely, we want the dev+ino
* of the directory we created.
*/
if (lstat(nm, &sb) < 0) {
syswarn(0, errno, "Unable to stat %s", nm);
} else if (access(nm, R_OK | W_OK | X_OK) < 0) {
/*
* We have to add rights to the dir, so we make
* sure to restore the mode. The mode must be
* restored AS CREATED and not as stored if
* pmode is not set.
*/
set_pmode(nm,
((sb.st_mode & FILEBITS) | S_IRWXU), 0);
if (!pmode)
arcn->sb.st_mode = sb.st_mode;
/*
* we have to force the mode to what was set
* here, since we changed it from the default
* as created.
*/
arcn->sb.st_dev = sb.st_dev;
arcn->sb.st_ino = sb.st_ino;
add_dir(nm, &(arcn->sb), 1);
} else if (pmode || patime || pmtime) {
arcn->sb.st_dev = sb.st_dev;
arcn->sb.st_ino = sb.st_ino;
add_dir(nm, &(arcn->sb), 0);
}
} else if (patime || pmtime)
set_ftime(nm, &arcn->sb, 0, arcn->type == PAX_SLK);
free(allocd);
return (0);
}
/*
* unlnk_exist()
* Remove node from filesystem with the specified name. We pass the type
* of the node that is going to replace it. When we try to create a
* directory and find that it already exists, we allow processing to
* continue as proper modes etc will always be set for it later on.
* Return:
* 0 is ok to proceed, no file with the specified name exists
* -1 we were unable to remove the node, or we should not remove it (-k)
* 1 we found a directory and we were going to create a directory.
*/
int
unlnk_exist(char *name, int type)
{
struct stat sb;
/*
* the file does not exist, or -k we are done
*/
if (lstat(name, &sb) < 0)
return(0);
if (kflag)
return(-1);
if (S_ISDIR(sb.st_mode)) {
/*
* try to remove a directory, if it fails and we were going to
* create a directory anyway, tell the caller (return a 1)
*/
if (rmdir(name) < 0) {
if (type == PAX_DIR)
return(1);
syswarn(1,errno,"Unable to remove directory %s", name);
return(-1);
}
delete_dir(sb.st_dev, sb.st_ino);
return(0);
}
/*
* try to get rid of all non-directory type nodes
*/
if (unlink(name) < 0) {
syswarn(1, errno, "Unable to remove %s", name);
return(-1);
}
return(0);
}
/*
* chk_path()
* We were trying to create some kind of node in the filesystem and it
* failed. chk_path() makes sure the path up to the node exists and is
* writeable. When we have to create a directory that is missing along the
* path somewhere, the directory we create will be set to the same
* uid/gid as the file has (when uid and gid are being preserved).
* NOTE: this routine is a real performance loss. It is only used as a
* last resort when trying to create entries in the filesystem.
* Return:
* -1 when it could find nothing it is allowed to fix.
* 0 otherwise
*/
int
chk_path(char *name, uid_t st_uid, gid_t st_gid)
{
char *spt = name;
char *next;
struct stat sb;
int retval = -1;
/*
* watch out for paths with nodes stored directly in / (e.g. /bozo)
*/
while (*spt == '/')
++spt;
for (;;) {
/*
* work forward from the first / and check each part of the path
*/
spt = strchr(spt, '/');
if (spt == NULL)
break;
/*
* skip over duplicate slashes; stop if there're only
* trailing slashes left
*/
next = spt + 1;
while (*next == '/')
next++;
if (*next == '\0')
break;
*spt = '\0';
/*
* if it exists we assume it is a directory, it is not within
* the spec (at least it seems to read that way) to alter the
* filesystem for nodes NOT EXPLICITLY stored on the archive.
* If that assumption is changed, you would test the node here
* and figure out how to get rid of it (probably like some
* recursive unlink()) or fix up the directory permissions if
* required (do an access()).
*/
if (lstat(name, &sb) == 0) {
*spt = '/';
spt = next;
continue;
}
/*
* the path fails at this point, see if we can create the
* needed directory and continue on
*/
if (mkdir(name, S_IRWXU | S_IRWXG | S_IRWXO) < 0) {
*spt = '/';
retval = -1;
break;
}
/*
* we were able to create the directory. We will tell the
* caller that we found something to fix, and it is ok to try
* and create the node again.
*/
retval = 0;
if (pids)
(void)set_ids(name, st_uid, st_gid, 0);
/*
* make sure the user doesn't have some strange umask that
* causes this newly created directory to be unusable. We fix
* the modes and restore them back to the creation default at
* the end of pax
*/
if ((access(name, R_OK | W_OK | X_OK) < 0) &&
(lstat(name, &sb) == 0)) {
set_pmode(name, ((sb.st_mode & FILEBITS) | S_IRWXU), 0);
add_dir(name, &sb, 1);
}
*spt = '/';
spt = next;
continue;
}
return(retval);
}
/*
* set_ftime()
* Set the access time and modification time for a named file. If frc
* is non-zero we force these times to be set even if the user did not
* request access and/or modification time preservation (this is also
* used by -t to reset access times).
* When ign is zero, only those times the user has asked for are set, the
* other ones are left alone. We do not assume the un-documented feature
* of many utimes() implementations that consider a 0 time value as a do
* not set request.
*/
void
set_ftime(const char *fnm, const struct stat *sbp, int frc,
int issymlink MKSH_A_UNUSED)
{
#if HAVE_UTIMENSAT
struct timespec ts[2];
#else
struct {
time_t tv_sec;
long tv_nsec;
} ts[2];
#if HAVE_UTIMES
struct timeval tv[2];
#else
struct utimbuf u;
#endif
struct stat sb;
#endif
int rv;
/* pre-initialise values to set */
st_timexp(a, &ts[0], sbp);
st_timexp(m, &ts[1], sbp);
if (!frc && (!patime || !pmtime)) {
/*
* If we are not forcing, only set those times the user
* wants set. We get the current values of the times if
* we need them (utimensat does not).
*/
#if HAVE_UTIMENSAT
if (!patime)
ts[0].tv_nsec = UTIME_OMIT;
if (!pmtime)
ts[1].tv_nsec = UTIME_OMIT;
#else
if (lstat(fnm, &sb) == 0) {
if (!patime)
st_timexp(a, &ts[0], &sb);
if (!pmtime)
st_timexp(m, &ts[1], &sb);
} else
syswarn(0, errno, "Unable to stat %s", fnm);
#endif
}
/* set the times */
#if HAVE_UTIMENSAT
rv = utimensat(AT_FDCWD, fnm, ts, AT_SYMLINK_NOFOLLOW);
#elif HAVE_UTIMES
tv[0].tv_sec = ts[0].tv_sec;
tv[0].tv_usec = ts[0].tv_nsec / 1000;
tv[1].tv_sec = ts[1].tv_sec;
tv[1].tv_usec = ts[1].tv_nsec / 1000;
#if HAVE_LUTIMES
rv = (issymlink ? lutimes : utimes)(fnm, tv);
#else
if (issymlink)
/* no can do */
return;
rv = utimes(fnm, tv);
#endif
if (rv < 0 && issymlink && (errno == ENOSYS || errno == ENOTSUP))
/* might be glibc */
return;
#else
if (issymlink)
/* no can do */
return;
u.actime = ts[0].tv_sec;
u.modtime = ts[1].tv_sec;
rv = utime(fnm, &u);
#endif
if (rv < 0)
syswarn(1, errno, "Access/modification time set failed on: %s",
fnm);
}
#ifdef PAX_FSET_FTIME
static void
fset_ftime(const char *fnm, int fd, const struct stat *sbp, int frc)
{
#if HAVE_FUTIMENS
struct timespec ts[2];
#else
struct {
time_t tv_sec;
long tv_nsec;
} ts[2];
struct timeval tv[2];
struct stat sb;
#endif
int rv;
/* pre-initialise values to set */
st_timexp(a, &ts[0], sbp);
st_timexp(m, &ts[1], sbp);
if (!frc && (!patime || !pmtime)) {
/*
* If we are not forcing, only set those times the user
* wants set. We get the current values of the times if
* we need them (futimens does not).
*/
#if HAVE_FUTIMENS
if (!patime)
ts[0].tv_nsec = UTIME_OMIT;
if (!pmtime)
ts[1].tv_nsec = UTIME_OMIT;
#else
if (fstat(fd, &sb) == 0) {
if (!patime)
st_timexp(a, &ts[0], &sb);
if (!pmtime)
st_timexp(m, &ts[1], &sb);
} else
syswarn(0, errno, "Unable to stat %s", fnm);
#endif
}
/* set the times */
#if HAVE_FUTIMENS
rv = futimens(fd, ts);
#else
tv[0].tv_sec = ts[0].tv_sec;
tv[0].tv_usec = ts[0].tv_nsec / 1000;
tv[1].tv_sec = ts[1].tv_sec;
tv[1].tv_usec = ts[1].tv_nsec / 1000;
rv = futimes(fd, tv);
#endif
if (rv < 0)
syswarn(1, errno, "Access/modification time set failed on: %s",
fnm);
}
#endif
/*
* set_ids()
* set the uid and gid of a filesystem node
* Return:
* 0 when set, -1 on failure
*/
int
set_ids(char *fnm, uid_t uid, gid_t gid, int issymlink MKSH_A_UNUSED)
{
int rv;
#if HAVE_FCHOWNAT
rv = fchownat(AT_FDCWD, fnm, uid, gid, AT_SYMLINK_NOFOLLOW);
#elif HAVE_LCHOWN
rv = (issymlink ? lchown : chown)(fnm, uid, gid);
if (rv < 0 && issymlink && (errno == ENOSYS || errno == ENOTSUP))
/* might be glibc */
return (0);
#else
if (issymlink)
/* no can do */
return (0);
rv = chown(fnm, uid, gid);
#endif
if (rv < 0) {
/*
* ignore EPERM unless in verbose mode or being run by root.
* if running as pax, POSIX requires a warning.
*/
if (/* portability, imake style though */
#ifndef __INTERIX
errno != EPERM || vflag || geteuid() == 0 ||
#endif
op_mode == OP_PAX)
syswarn(1, errno, "Unable to set file uid/gid of %s",
fnm);
return (-1);
}
return (0);
}
int
fset_ids(char *fnm, int fd, uid_t uid, gid_t gid)
{
if (fchown(fd, uid, gid) < 0) {
/*
* ignore EPERM unless in verbose mode or being run by root.
* if running as pax, POSIX requires a warning.
*/
if (/* portability, imake style though */
#ifndef __INTERIX
errno != EPERM || vflag || geteuid() == 0 ||
#endif
op_mode == OP_PAX)
syswarn(1, errno, "Unable to set file uid/gid of %s",
fnm);
return (-1);
}
return (0);
}
/*
* set_pmode()
* Set file access mode
*/
void
set_pmode(char *fnm, mode_t mode, int issymlink MKSH_A_UNUSED)
{
int rv;
mode &= ABITS;
#if HAVE_FCHMODAT
rv = fchmodat(AT_FDCWD, fnm, mode, AT_SYMLINK_NOFOLLOW);
if (rv < 0 && (errno == ENOSYS || errno == ENOTSUP)) {
/* glibc sucks */
if (issymlink)
return;
rv = chmod(fnm, mode);
}
#elif HAVE_LCHMOD
rv = (issymlink ? lchmod : chmod)(fnm, mode);
if (rv < 0 && issymlink && (errno == ENOSYS || errno == ENOTSUP))
/* similarly glibc */
return;
#else
if (issymlink)
/* no can do */
return;
rv = chmod(fnm, mode);
#endif
if (rv < 0)
syswarn(1, errno, "Could not set permissions on %s", fnm);
}
void
fset_pmode(char *fnm, int fd, mode_t mode)
{
mode &= ABITS;
if (fchmod(fd, mode) < 0)
syswarn(1, errno, "Could not set permissions on %s", fnm);
}
/*
* set_attr()
* Given a DIRDATA, restore the mode and times as indicated, but
* only after verifying that it's the directory that we wanted.
*/
int
set_attr(const struct file_times *ft, int force_times, mode_t mode,
int do_mode, int in_sig)
{
struct stat sb;
int fd, r;
if (!do_mode && !force_times && !patime && !pmtime)
return (0);
/*
* We could legitimately go through a symlink here,
* so do *not* use O_NOFOLLOW. The dev+ino check will
* protect us from evil.
*/
fd = binopen2(BO_MAYBE_DIR, ft->ft_name, O_RDONLY);
if (fd == -1) {
if (!in_sig)
syswarn(1, errno, "Unable to restore mode and times"
" for directory %s", ft->ft_name);
return (-1);
}
if (fstat(fd, &sb) == -1) {
if (!in_sig)
syswarn(1, errno, "Unable to stat directory %s",
ft->ft_name);
r = -1;
#ifndef O_DIRECTORY
} else if (!S_ISDIR(sb.st_mode)) {
if (!in_sig)
syswarn(1, ENOTDIR, "Unable to restore mode and times"
" for directory %s", ft->ft_name);
r = -1;
#endif
} else if (ft->ft_ino != sb.st_ino || ft->ft_dev != sb.st_dev) {
if (!in_sig)
paxwarn(1, "Directory vanished before restoring"
" mode and times: %s", ft->ft_name);
r = -1;
} else {
/* Whew, it's a match! Is there anything to change? */
if (do_mode && (mode & ABITS) != (sb.st_mode & ABITS))
fset_pmode(ft->ft_name, fd, mode);
#ifdef PAX_FSET_FTIME
if (((force_times || patime) && st_timecmp(a, &ft->sb, &sb, !=)) ||
((force_times || pmtime) && st_timecmp(m, &ft->sb, &sb, !=)))
fset_ftime(ft->ft_name, fd, &ft->sb, force_times);
#endif
r = 0;
}
close(fd);
return (r);
}
/*
* file_write()
* Write/copy a file (during copy or archive extract). This routine knows
* how to copy files with lseek holes in it. (Which are read as file
* blocks containing all 0's but do not have any file blocks associated
* with the data). Typical examples of these are files created by dbm
* variants (.pag files). While the file size of these files are huge, the
* actual storage is quite small (the files are sparse). The problem is
* the holes read as all zeros so are probably stored on the archive that
* way (there is no way to determine if the file block is really a hole,
* we only know that a file block of all zero's can be a hole).
* At this writing, no major archive format knows how to archive files
* with holes. However, on extraction (or during copy, -rw) we have to
* deal with these files. Without detecting the holes, the files can
* consume a lot of file space if just written to disk. This replacement
* for write when passed the basic allocation size of a filesystem block,
* uses lseek whenever it detects the input data is all 0 within that
* file block. In more detail, the strategy is as follows:
* While the input is all zero keep doing an lseek. Keep track of when we
* pass over file block boundaries. Only write when we hit a non zero
* input. once we have written a file block, we continue to write it to
* the end (we stop looking at the input). When we reach the start of the
* next file block, start checking for zero blocks again. Working on file
* block boundaries significantly reduces the overhead when copying files
* that are NOT very sparse. This overhead (when compared to a write) is
* almost below the measurement resolution on many systems. Without it,
* files with holes cannot be safely copied. It does has a side effect as
* it can put holes into files that did not have them before, but that is
* not a problem since the file contents are unchanged (in fact it saves
* file space). (Except on paging files for diskless clients. But since we
* cannot determine one of those file from here, we ignore them). If this
* ever ends up on a system where CTG files are supported and the holes
* are not desired, just do a conditional test in those routines that
* call file_write() and have it call write() instead. BEFORE CLOSING THE
* FILE, make sure to call file_flush() when the last write finishes with
* an empty block. A lot of filesystems will not create an lseek hole at
* the end. In this case we drop a single 0 at the end to force the
* trailing 0's in the file.
* ---Parameters---
* rem: how many bytes left in this filesystem block
* isempt: have we written to the file block yet (is it empty)
* sz: basic file block allocation size
* cnt: number of bytes on this write
* str: buffer to write
* Return:
* number of bytes written, -1 on write (or lseek) error.
*/
int
file_write(int fd, char *str, int cnt, int *rem, int *isempt, int sz,
char *name)
{
char *pt;
char *end;
int wcnt;
char *st = str;
char **strp;
/*
* while we have data to process
*/
while (cnt) {
if (!*rem) {
/*
* We are now at the start of filesystem block again
* (or what we think one is...). start looking for
* empty blocks again
*/
*isempt = 1;
*rem = sz;
}
/*
* only examine up to the end of the current file block or
* remaining characters to write, whatever is smaller
*/
wcnt = MINIMUM(cnt, *rem);
cnt -= wcnt;
*rem -= wcnt;
if (*isempt) {
/*
* have not written to this block yet, so we keep
* looking for zero's
*/
pt = st;
end = st + wcnt;
/*
* look for a zero filled buffer
*/
while ((pt < end) && (*pt == '\0'))
++pt;
if (pt == end) {
/*
* skip, buf is empty so far
*/
if (fd > -1 &&
lseek(fd, wcnt, SEEK_CUR) < 0) {
if (errno == ESPIPE)
goto isapipe;
syswarn(1, errno,
"Failed seek on file %s", name);
return (-1);
}
st = pt;
continue;
}
isapipe:
/*
* drat, the buf is not zero filled
*/
*isempt = 0;
}
/*
* have non-zero data in this filesystem block, have to write
*/
switch (fd) {
case -1:
strp = &gnu_name_string;
break;
case -2:
strp = &gnu_link_string;
break;
default:
strp = NULL;
break;
}
if (strp) {
if (*strp)
err(1, "WARNING! Major Internal Error! GNU hack Failing!");
*strp = malloc(wcnt + 1);
if (*strp == NULL) {
paxwarn(1, "Out of memory");
return(-1);
}
memcpy(*strp, st, wcnt);
(*strp)[wcnt] = '\0';
break;
} else if (write(fd, st, wcnt) != wcnt) {
syswarn(1, errno, "Failed write to file %s", name);
return(-1);
}
st += wcnt;
}
return(st - str);
}
/*
* file_flush()
* when the last file block in a file is zero, many filesystems will not
* let us create a hole at the end. To get the last block with zeros, we
* write the last BYTE with a zero (back up one byte and write a zero).
*/
void
file_flush(int fd, char *fname, int isempt)
{
static char blnk[] = "\0";
/*
* silly test, but make sure we are only called when the last block is
* filled with all zeros.
*/
if (!isempt)
return;
/*
* move back one byte and write a zero
*/
if (lseek(fd, -1, SEEK_CUR) < 0) {
syswarn(1, errno, "Failed seek on file %s", fname);
return;
}
if (write(fd, blnk, 1) < 0)
syswarn(1, errno, "Failed write to file %s", fname);
}
/*
* rdfile_close()
* close a file we have been reading (to copy or archive). If we have to
* reset access time (tflag) do so (the times are stored in arcn).
*/
void
rdfile_close(ARCHD *arcn MKSH_A_UNUSED, int *fd)
{
/*
* make sure the file is open
*/
if (*fd < 0)
return;
/*
* user wants last access time reset
*/
#ifdef PAX_FSET_FTIME
if (tflag)
fset_ftime(arcn->org_name, *fd, &arcn->sb, 1);
#endif
(void)close(*fd);
*fd = -1;
}
/*
* set_crc()
* read a file to calculate its crc. This is a real drag. Archive formats
* that have this, end up reading the file twice (we have to write the
* header WITH the crc before writing the file contents. Oh well...
* Return:
* 0 if was able to calculate the crc, -1 otherwise
*/
int
set_crc(ARCHD *arcn, int fd)
{
int i;
int res;
off_t cpcnt = 0;
size_t size;
uint32_t crc = 0;
char tbuf[FILEBLK];
struct stat sb;
if (fd < 0) {
/*
* hmm, no fd, should never happen. well no crc then.
*/
arcn->crc = 0;
return(0);
}
if ((size = arcn->sb.st_blksize) > sizeof(tbuf))
size = sizeof(tbuf);
/*
* read all the bytes we think that there are in the file. If the user
* is trying to archive an active file, forget this file.
*/
for (;;) {
if ((res = read(fd, tbuf, size)) <= 0)
break;
cpcnt += res;
for (i = 0; i < res; ++i)
crc += (tbuf[i] & 0xff);
}
/*
* safety check. we want to avoid archiving files that are active as
* they can create inconsistent archive copies.
*/
if (cpcnt != (off_t)arcn->sb.st_size)
paxwarn(1, "File changed size %s", arcn->org_name);
else if (fstat(fd, &sb) < 0)
syswarn(1, errno, "Failed stat on %s", arcn->org_name);
else if (st_timecmp(m, &arcn->sb, &sb, !=))
paxwarn(1, "File %s was modified during read", arcn->org_name);
else if (lseek(fd, 0, SEEK_SET) < 0)
syswarn(1, errno, "File rewind failed on: %s", arcn->org_name);
else {
arcn->crc = crc;
return(0);
}
return(-1);
}
|