1 /////////////////////////////////////////////////////////////////////////////// 2 // 3 /// \file file_io.c 4 /// \brief File opening, unlinking, and closing 5 // 6 // Author: Lasse Collin 7 // 8 // This file has been put into the public domain. 9 // You can do whatever you want with this file. 10 // 11 /////////////////////////////////////////////////////////////////////////////// 12 13 #include "private.h" 14 15 #include <fcntl.h> 16 17 #ifdef TUKLIB_DOSLIKE 18 # include <io.h> 19 #else 20 # include <poll.h> 21 static bool warn_fchown; 22 #endif 23 24 #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES) 25 # include <sys/time.h> 26 #elif defined(HAVE__FUTIME) 27 # include <sys/utime.h> 28 #elif defined(HAVE_UTIME) 29 # include <utime.h> 30 #endif 31 32 #ifdef HAVE_CAPSICUM 33 # ifdef HAVE_SYS_CAPSICUM_H 34 # include <sys/capsicum.h> 35 # else 36 # include <sys/capability.h> 37 # endif 38 #endif 39 40 #include "tuklib_open_stdxxx.h" 41 42 #ifndef O_BINARY 43 # define O_BINARY 0 44 #endif 45 46 #ifndef O_NOCTTY 47 # define O_NOCTTY 0 48 #endif 49 50 // Using this macro to silence a warning from gcc -Wlogical-op. 51 #if EAGAIN == EWOULDBLOCK 52 # define IS_EAGAIN_OR_EWOULDBLOCK(e) ((e) == EAGAIN) 53 #else 54 # define IS_EAGAIN_OR_EWOULDBLOCK(e) \ 55 ((e) == EAGAIN || (e) == EWOULDBLOCK) 56 #endif 57 58 59 typedef enum { 60 IO_WAIT_MORE, // Reading or writing is possible. 61 IO_WAIT_ERROR, // Error or user_abort 62 IO_WAIT_TIMEOUT, // poll() timed out 63 } io_wait_ret; 64 65 66 /// If true, try to create sparse files when decompressing. 67 static bool try_sparse = true; 68 69 #ifdef ENABLE_SANDBOX 70 /// True if the conditions for sandboxing (described in main()) have been met. 71 static bool sandbox_allowed = false; 72 #endif 73 74 #ifndef TUKLIB_DOSLIKE 75 /// File status flags of standard input. This is used by io_open_src() 76 /// and io_close_src(). 77 static int stdin_flags; 78 static bool restore_stdin_flags = false; 79 80 /// Original file status flags of standard output. This is used by 81 /// io_open_dest() and io_close_dest() to save and restore the flags. 82 static int stdout_flags; 83 static bool restore_stdout_flags = false; 84 85 /// Self-pipe used together with the user_abort variable to avoid 86 /// race conditions with signal handling. 87 static int user_abort_pipe[2]; 88 #endif 89 90 91 static bool io_write_buf(file_pair *pair, const uint8_t *buf, size_t size); 92 93 94 extern void 95 io_init(void) 96 { 97 // Make sure that stdin, stdout, and stderr are connected to 98 // a valid file descriptor. Exit immediately with exit code ERROR 99 // if we cannot make the file descriptors valid. Maybe we should 100 // print an error message, but our stderr could be screwed anyway. 101 tuklib_open_stdxxx(E_ERROR); 102 103 #ifndef TUKLIB_DOSLIKE 104 // If fchown() fails setting the owner, we warn about it only if 105 // we are root. 106 warn_fchown = geteuid() == 0; 107 108 // Create a pipe for the self-pipe trick. 109 if (pipe(user_abort_pipe)) 110 message_fatal(_("Error creating a pipe: %s"), 111 strerror(errno)); 112 113 // Make both ends of the pipe non-blocking. 114 for (unsigned i = 0; i < 2; ++i) { 115 int flags = fcntl(user_abort_pipe[i], F_GETFL); 116 if (flags == -1 || fcntl(user_abort_pipe[i], F_SETFL, 117 flags | O_NONBLOCK) == -1) 118 message_fatal(_("Error creating a pipe: %s"), 119 strerror(errno)); 120 } 121 #endif 122 123 #ifdef __DJGPP__ 124 // Avoid doing useless things when statting files. 125 // This isn't important but doesn't hurt. 126 _djstat_flags = _STAT_EXEC_EXT | _STAT_EXEC_MAGIC | _STAT_DIRSIZE; 127 #endif 128 129 return; 130 } 131 132 133 #ifndef TUKLIB_DOSLIKE 134 extern void 135 io_write_to_user_abort_pipe(void) 136 { 137 // If the write() fails, it's probably due to the pipe being full. 138 // Failing in that case is fine. If the reason is something else, 139 // there's not much we can do since this is called in a signal 140 // handler. So ignore the errors and try to avoid warnings with 141 // GCC and glibc when _FORTIFY_SOURCE=2 is used. 142 uint8_t b = '\0'; 143 const int ret = write(user_abort_pipe[1], &b, 1); 144 (void)ret; 145 return; 146 } 147 #endif 148 149 150 extern void 151 io_no_sparse(void) 152 { 153 try_sparse = false; 154 return; 155 } 156 157 158 #ifdef ENABLE_SANDBOX 159 extern void 160 io_allow_sandbox(void) 161 { 162 sandbox_allowed = true; 163 return; 164 } 165 166 167 /// Enables operating-system-specific sandbox if it is possible. 168 /// src_fd is the file descriptor of the input file. 169 static void 170 io_sandbox_enter(int src_fd) 171 { 172 if (!sandbox_allowed) { 173 // This message is more often annoying than useful so 174 // it's commented out. It can be useful when developing 175 // the sandboxing code. 176 //message(V_DEBUG, _("Sandbox is disabled due " 177 // "to incompatible command line arguments")); 178 return; 179 } 180 181 const char dummy_str[] = "x"; 182 183 // Try to ensure that both libc and xz locale files have been 184 // loaded when NLS is enabled. 185 snprintf(NULL, 0, "%s%s", _(dummy_str), strerror(EINVAL)); 186 187 // Try to ensure that iconv data files needed for handling multibyte 188 // characters have been loaded. This is needed at least with glibc. 189 tuklib_mbstr_width(dummy_str, NULL); 190 191 #ifdef HAVE_CAPSICUM 192 // Capsicum needs FreeBSD 10.0 or later. 193 cap_rights_t rights; 194 195 if (cap_rights_limit(src_fd, cap_rights_init(&rights, 196 CAP_EVENT, CAP_FCNTL, CAP_LOOKUP, CAP_READ, CAP_SEEK))) 197 goto error; 198 199 if (cap_rights_limit(STDOUT_FILENO, cap_rights_init(&rights, 200 CAP_EVENT, CAP_FCNTL, CAP_FSTAT, CAP_LOOKUP, 201 CAP_WRITE, CAP_SEEK))) 202 goto error; 203 204 if (cap_rights_limit(user_abort_pipe[0], cap_rights_init(&rights, 205 CAP_EVENT))) 206 goto error; 207 208 if (cap_rights_limit(user_abort_pipe[1], cap_rights_init(&rights, 209 CAP_WRITE))) 210 goto error; 211 212 if (cap_enter()) 213 goto error; 214 215 #elif defined(HAVE_PLEDGE) 216 // pledge() was introduced in OpenBSD 5.9. 217 // 218 // main() unconditionally calls pledge() with fairly relaxed 219 // promises which work in all situations. Here we make the 220 // sandbox more strict. 221 if (pledge("stdio", "")) 222 goto error; 223 224 (void)src_fd; 225 226 #else 227 # error ENABLE_SANDBOX is defined but no sandboxing method was found. 228 #endif 229 230 // This message is annoying in xz -lvv. 231 //message(V_DEBUG, _("Sandbox was successfully enabled")); 232 return; 233 234 error: 235 message_fatal(_("Failed to enable the sandbox")); 236 } 237 #endif // ENABLE_SANDBOX 238 239 240 #ifndef TUKLIB_DOSLIKE 241 /// \brief Waits for input or output to become available or for a signal 242 /// 243 /// This uses the self-pipe trick to avoid a race condition that can occur 244 /// if a signal is caught after user_abort has been checked but before e.g. 245 /// read() has been called. In that situation read() could block unless 246 /// non-blocking I/O is used. With non-blocking I/O something like select() 247 /// or poll() is needed to avoid a busy-wait loop, and the same race condition 248 /// pops up again. There are pselect() (POSIX-1.2001) and ppoll() (not in 249 /// POSIX) but neither is portable enough in 2013. The self-pipe trick is 250 /// old and very portable. 251 static io_wait_ret 252 io_wait(file_pair *pair, int timeout, bool is_reading) 253 { 254 struct pollfd pfd[2]; 255 256 if (is_reading) { 257 pfd[0].fd = pair->src_fd; 258 pfd[0].events = POLLIN; 259 } else { 260 pfd[0].fd = pair->dest_fd; 261 pfd[0].events = POLLOUT; 262 } 263 264 pfd[1].fd = user_abort_pipe[0]; 265 pfd[1].events = POLLIN; 266 267 while (true) { 268 const int ret = poll(pfd, 2, timeout); 269 270 if (user_abort) 271 return IO_WAIT_ERROR; 272 273 if (ret == -1) { 274 if (errno == EINTR || errno == EAGAIN) 275 continue; 276 277 message_error(_("%s: poll() failed: %s"), 278 is_reading ? pair->src_name 279 : pair->dest_name, 280 strerror(errno)); 281 return IO_WAIT_ERROR; 282 } 283 284 if (ret == 0) 285 return IO_WAIT_TIMEOUT; 286 287 if (pfd[0].revents != 0) 288 return IO_WAIT_MORE; 289 } 290 } 291 #endif 292 293 294 /// \brief Unlink a file 295 /// 296 /// This tries to verify that the file being unlinked really is the file that 297 /// we want to unlink by verifying device and inode numbers. There's still 298 /// a small unavoidable race, but this is much better than nothing (the file 299 /// could have been moved/replaced even hours earlier). 300 static void 301 io_unlink(const char *name, const struct stat *known_st) 302 { 303 #if defined(TUKLIB_DOSLIKE) 304 // On DOS-like systems, st_ino is meaningless, so don't bother 305 // testing it. Just silence a compiler warning. 306 (void)known_st; 307 #else 308 struct stat new_st; 309 310 // If --force was used, use stat() instead of lstat(). This way 311 // (de)compressing symlinks works correctly. However, it also means 312 // that xz cannot detect if a regular file foo is renamed to bar 313 // and then a symlink foo -> bar is created. Because of stat() 314 // instead of lstat(), xz will think that foo hasn't been replaced 315 // with another file. Thus, xz will remove foo even though it no 316 // longer is the same file that xz used when it started compressing. 317 // Probably it's not too bad though, so this doesn't need a more 318 // complex fix. 319 const int stat_ret = opt_force 320 ? stat(name, &new_st) : lstat(name, &new_st); 321 322 if (stat_ret 323 # ifdef __VMS 324 // st_ino is an array, and we don't want to 325 // compare st_dev at all. 326 || memcmp(&new_st.st_ino, &known_st->st_ino, 327 sizeof(new_st.st_ino)) != 0 328 # else 329 // Typical POSIX-like system 330 || new_st.st_dev != known_st->st_dev 331 || new_st.st_ino != known_st->st_ino 332 # endif 333 ) 334 // TRANSLATORS: When compression or decompression finishes, 335 // and xz is going to remove the source file, xz first checks 336 // if the source file still exists, and if it does, does its 337 // device and inode numbers match what xz saw when it opened 338 // the source file. If these checks fail, this message is 339 // shown, %s being the filename, and the file is not deleted. 340 // The check for device and inode numbers is there, because 341 // it is possible that the user has put a new file in place 342 // of the original file, and in that case it obviously 343 // shouldn't be removed. 344 message_warning(_("%s: File seems to have been moved, " 345 "not removing"), name); 346 else 347 #endif 348 // There's a race condition between lstat() and unlink() 349 // but at least we have tried to avoid removing wrong file. 350 if (unlink(name)) 351 message_warning(_("%s: Cannot remove: %s"), 352 name, strerror(errno)); 353 354 return; 355 } 356 357 358 /// \brief Copies owner/group and permissions 359 /// 360 /// \todo ACL and EA support 361 /// 362 static void 363 io_copy_attrs(const file_pair *pair) 364 { 365 // Skip chown and chmod on Windows. 366 #ifndef TUKLIB_DOSLIKE 367 // This function is more tricky than you may think at first. 368 // Blindly copying permissions may permit users to access the 369 // destination file who didn't have permission to access the 370 // source file. 371 372 // Try changing the owner of the file. If we aren't root or the owner 373 // isn't already us, fchown() probably doesn't succeed. We warn 374 // about failing fchown() only if we are root. 375 if (fchown(pair->dest_fd, pair->src_st.st_uid, (gid_t)(-1)) 376 && warn_fchown) 377 message_warning(_("%s: Cannot set the file owner: %s"), 378 pair->dest_name, strerror(errno)); 379 380 mode_t mode; 381 382 // With BSD semantics the new dest file may have a group that 383 // does not belong to the user. If the src file has the same gid 384 // nothing has to be done. Nevertheless OpenBSD fchown(2) fails 385 // in this case which seems to be POSIX compliant. As there is 386 // nothing to do, skip the system call. 387 if (pair->dest_st.st_gid != pair->src_st.st_gid 388 && fchown(pair->dest_fd, (uid_t)(-1), 389 pair->src_st.st_gid)) { 390 message_warning(_("%s: Cannot set the file group: %s"), 391 pair->dest_name, strerror(errno)); 392 // We can still safely copy some additional permissions: 393 // `group' must be at least as strict as `other' and 394 // also vice versa. 395 // 396 // NOTE: After this, the owner of the source file may 397 // get additional permissions. This shouldn't be too bad, 398 // because the owner would have had permission to chmod 399 // the original file anyway. 400 mode = ((pair->src_st.st_mode & 0070) >> 3) 401 & (pair->src_st.st_mode & 0007); 402 mode = (pair->src_st.st_mode & 0700) | (mode << 3) | mode; 403 } else { 404 // Drop the setuid, setgid, and sticky bits. 405 mode = pair->src_st.st_mode & 0777; 406 } 407 408 if (fchmod(pair->dest_fd, mode)) 409 message_warning(_("%s: Cannot set the file permissions: %s"), 410 pair->dest_name, strerror(errno)); 411 #endif 412 413 // Copy the timestamps. We have several possible ways to do this, of 414 // which some are better in both security and precision. 415 // 416 // First, get the nanosecond part of the timestamps. As of writing, 417 // it's not standardized by POSIX, and there are several names for 418 // the same thing in struct stat. 419 long atime_nsec; 420 long mtime_nsec; 421 422 # if defined(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC) 423 // GNU and Solaris 424 atime_nsec = pair->src_st.st_atim.tv_nsec; 425 mtime_nsec = pair->src_st.st_mtim.tv_nsec; 426 427 # elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC) 428 // BSD 429 atime_nsec = pair->src_st.st_atimespec.tv_nsec; 430 mtime_nsec = pair->src_st.st_mtimespec.tv_nsec; 431 432 # elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC) 433 // GNU and BSD without extensions 434 atime_nsec = pair->src_st.st_atimensec; 435 mtime_nsec = pair->src_st.st_mtimensec; 436 437 # elif defined(HAVE_STRUCT_STAT_ST_UATIME) 438 // Tru64 439 atime_nsec = pair->src_st.st_uatime * 1000; 440 mtime_nsec = pair->src_st.st_umtime * 1000; 441 442 # elif defined(HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC) 443 // UnixWare 444 atime_nsec = pair->src_st.st_atim.st__tim.tv_nsec; 445 mtime_nsec = pair->src_st.st_mtim.st__tim.tv_nsec; 446 447 # else 448 // Safe fallback 449 atime_nsec = 0; 450 mtime_nsec = 0; 451 # endif 452 453 // Construct a structure to hold the timestamps and call appropriate 454 // function to set the timestamps. 455 #if defined(HAVE_FUTIMENS) 456 // Use nanosecond precision. 457 struct timespec tv[2]; 458 tv[0].tv_sec = pair->src_st.st_atime; 459 tv[0].tv_nsec = atime_nsec; 460 tv[1].tv_sec = pair->src_st.st_mtime; 461 tv[1].tv_nsec = mtime_nsec; 462 463 (void)futimens(pair->dest_fd, tv); 464 465 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES) 466 // Use microsecond precision. 467 struct timeval tv[2]; 468 tv[0].tv_sec = pair->src_st.st_atime; 469 tv[0].tv_usec = atime_nsec / 1000; 470 tv[1].tv_sec = pair->src_st.st_mtime; 471 tv[1].tv_usec = mtime_nsec / 1000; 472 473 # if defined(HAVE_FUTIMES) 474 (void)futimes(pair->dest_fd, tv); 475 # elif defined(HAVE_FUTIMESAT) 476 (void)futimesat(pair->dest_fd, NULL, tv); 477 # else 478 // Argh, no function to use a file descriptor to set the timestamp. 479 (void)utimes(pair->dest_name, tv); 480 # endif 481 482 #elif defined(HAVE__FUTIME) 483 // Use one-second precision with Windows-specific _futime(). 484 // We could use utime() too except that for some reason the 485 // timestamp will get reset at close(). With _futime() it works. 486 // This struct cannot be const as _futime() takes a non-const pointer. 487 struct _utimbuf buf = { 488 .actime = pair->src_st.st_atime, 489 .modtime = pair->src_st.st_mtime, 490 }; 491 492 // Avoid warnings. 493 (void)atime_nsec; 494 (void)mtime_nsec; 495 496 (void)_futime(pair->dest_fd, &buf); 497 498 #elif defined(HAVE_UTIME) 499 // Use one-second precision. utime() doesn't support using file 500 // descriptor either. Some systems have broken utime() prototype 501 // so don't make this const. 502 struct utimbuf buf = { 503 .actime = pair->src_st.st_atime, 504 .modtime = pair->src_st.st_mtime, 505 }; 506 507 // Avoid warnings. 508 (void)atime_nsec; 509 (void)mtime_nsec; 510 511 (void)utime(pair->dest_name, &buf); 512 #endif 513 514 return; 515 } 516 517 518 /// Opens the source file. Returns false on success, true on error. 519 static bool 520 io_open_src_real(file_pair *pair) 521 { 522 // There's nothing to open when reading from stdin. 523 if (pair->src_name == stdin_filename) { 524 pair->src_fd = STDIN_FILENO; 525 #ifdef TUKLIB_DOSLIKE 526 setmode(STDIN_FILENO, O_BINARY); 527 #else 528 // Try to set stdin to non-blocking mode. It won't work 529 // e.g. on OpenBSD if stdout is e.g. /dev/null. In such 530 // case we proceed as if stdin were non-blocking anyway 531 // (in case of /dev/null it will be in practice). The 532 // same applies to stdout in io_open_dest_real(). 533 stdin_flags = fcntl(STDIN_FILENO, F_GETFL); 534 if (stdin_flags == -1) { 535 message_error(_("Error getting the file status flags " 536 "from standard input: %s"), 537 strerror(errno)); 538 return true; 539 } 540 541 if ((stdin_flags & O_NONBLOCK) == 0 542 && fcntl(STDIN_FILENO, F_SETFL, 543 stdin_flags | O_NONBLOCK) != -1) 544 restore_stdin_flags = true; 545 #endif 546 #ifdef HAVE_POSIX_FADVISE 547 // It will fail if stdin is a pipe and that's fine. 548 (void)posix_fadvise(STDIN_FILENO, 0, 0, 549 opt_mode == MODE_LIST 550 ? POSIX_FADV_RANDOM 551 : POSIX_FADV_SEQUENTIAL); 552 #endif 553 return false; 554 } 555 556 // Symlinks are not followed unless writing to stdout or --force 557 // or --keep was used. 558 const bool follow_symlinks 559 = opt_stdout || opt_force || opt_keep_original; 560 561 // We accept only regular files if we are writing the output 562 // to disk too. bzip2 allows overriding this with --force but 563 // gzip and xz don't. 564 const bool reg_files_only = !opt_stdout; 565 566 // Flags for open() 567 int flags = O_RDONLY | O_BINARY | O_NOCTTY; 568 569 #ifndef TUKLIB_DOSLIKE 570 // Use non-blocking I/O: 571 // - It prevents blocking when opening FIFOs and some other 572 // special files, which is good if we want to accept only 573 // regular files. 574 // - It can help avoiding some race conditions with signal handling. 575 flags |= O_NONBLOCK; 576 #endif 577 578 #if defined(O_NOFOLLOW) 579 if (!follow_symlinks) 580 flags |= O_NOFOLLOW; 581 #elif !defined(TUKLIB_DOSLIKE) 582 // Some POSIX-like systems lack O_NOFOLLOW (it's not required 583 // by POSIX). Check for symlinks with a separate lstat() on 584 // these systems. 585 if (!follow_symlinks) { 586 struct stat st; 587 if (lstat(pair->src_name, &st)) { 588 message_error("%s: %s", pair->src_name, 589 strerror(errno)); 590 return true; 591 592 } else if (S_ISLNK(st.st_mode)) { 593 message_warning(_("%s: Is a symbolic link, " 594 "skipping"), pair->src_name); 595 return true; 596 } 597 } 598 #else 599 // Avoid warnings. 600 (void)follow_symlinks; 601 #endif 602 603 // Try to open the file. Signals have been blocked so EINTR shouldn't 604 // be possible. 605 pair->src_fd = open(pair->src_name, flags); 606 607 if (pair->src_fd == -1) { 608 // Signals (that have a signal handler) have been blocked. 609 assert(errno != EINTR); 610 611 #ifdef O_NOFOLLOW 612 // Give an understandable error message if the reason 613 // for failing was that the file was a symbolic link. 614 // 615 // Note that at least Linux, OpenBSD, Solaris, and Darwin 616 // use ELOOP to indicate that O_NOFOLLOW was the reason 617 // that open() failed. Because there may be 618 // directories in the pathname, ELOOP may occur also 619 // because of a symlink loop in the directory part. 620 // So ELOOP doesn't tell us what actually went wrong, 621 // and this stupidity went into POSIX-1.2008 too. 622 // 623 // FreeBSD associates EMLINK with O_NOFOLLOW and 624 // Tru64 uses ENOTSUP. We use these directly here 625 // and skip the lstat() call and the associated race. 626 // I want to hear if there are other kernels that 627 // fail with something else than ELOOP with O_NOFOLLOW. 628 bool was_symlink = false; 629 630 # if defined(__FreeBSD__) || defined(__DragonFly__) 631 if (errno == EMLINK) 632 was_symlink = true; 633 634 # elif defined(__digital__) && defined(__unix__) 635 if (errno == ENOTSUP) 636 was_symlink = true; 637 638 # elif defined(__NetBSD__) 639 if (errno == EFTYPE) 640 was_symlink = true; 641 642 # else 643 if (errno == ELOOP && !follow_symlinks) { 644 const int saved_errno = errno; 645 struct stat st; 646 if (lstat(pair->src_name, &st) == 0 647 && S_ISLNK(st.st_mode)) 648 was_symlink = true; 649 650 errno = saved_errno; 651 } 652 # endif 653 654 if (was_symlink) 655 message_warning(_("%s: Is a symbolic link, " 656 "skipping"), pair->src_name); 657 else 658 #endif 659 // Something else than O_NOFOLLOW failing 660 // (assuming that the race conditions didn't 661 // confuse us). 662 message_error("%s: %s", pair->src_name, 663 strerror(errno)); 664 665 return true; 666 } 667 668 // Stat the source file. We need the result also when we copy 669 // the permissions, and when unlinking. 670 // 671 // NOTE: Use stat() instead of fstat() with DJGPP, because 672 // then we have a better chance to get st_ino value that can 673 // be used in io_open_dest_real() to prevent overwriting the 674 // source file. 675 #ifdef __DJGPP__ 676 if (stat(pair->src_name, &pair->src_st)) 677 goto error_msg; 678 #else 679 if (fstat(pair->src_fd, &pair->src_st)) 680 goto error_msg; 681 #endif 682 683 if (S_ISDIR(pair->src_st.st_mode)) { 684 message_warning(_("%s: Is a directory, skipping"), 685 pair->src_name); 686 goto error; 687 } 688 689 if (reg_files_only && !S_ISREG(pair->src_st.st_mode)) { 690 message_warning(_("%s: Not a regular file, skipping"), 691 pair->src_name); 692 goto error; 693 } 694 695 #ifndef TUKLIB_DOSLIKE 696 if (reg_files_only && !opt_force && !opt_keep_original) { 697 if (pair->src_st.st_mode & (S_ISUID | S_ISGID)) { 698 // gzip rejects setuid and setgid files even 699 // when --force was used. bzip2 doesn't check 700 // for them, but calls fchown() after fchmod(), 701 // and many systems automatically drop setuid 702 // and setgid bits there. 703 // 704 // We accept setuid and setgid files if 705 // --force or --keep was used. We drop these bits 706 // explicitly in io_copy_attr(). 707 message_warning(_("%s: File has setuid or " 708 "setgid bit set, skipping"), 709 pair->src_name); 710 goto error; 711 } 712 713 if (pair->src_st.st_mode & S_ISVTX) { 714 message_warning(_("%s: File has sticky bit " 715 "set, skipping"), 716 pair->src_name); 717 goto error; 718 } 719 720 if (pair->src_st.st_nlink > 1) { 721 message_warning(_("%s: Input file has more " 722 "than one hard link, " 723 "skipping"), pair->src_name); 724 goto error; 725 } 726 } 727 728 // If it is something else than a regular file, wait until 729 // there is input available. This way reading from FIFOs 730 // will work when open() is used with O_NONBLOCK. 731 if (!S_ISREG(pair->src_st.st_mode)) { 732 signals_unblock(); 733 const io_wait_ret ret = io_wait(pair, -1, true); 734 signals_block(); 735 736 if (ret != IO_WAIT_MORE) 737 goto error; 738 } 739 #endif 740 741 #ifdef HAVE_POSIX_FADVISE 742 // It will fail with some special files like FIFOs but that is fine. 743 (void)posix_fadvise(pair->src_fd, 0, 0, 744 opt_mode == MODE_LIST 745 ? POSIX_FADV_RANDOM 746 : POSIX_FADV_SEQUENTIAL); 747 #endif 748 749 return false; 750 751 error_msg: 752 message_error("%s: %s", pair->src_name, strerror(errno)); 753 error: 754 (void)close(pair->src_fd); 755 return true; 756 } 757 758 759 extern file_pair * 760 io_open_src(const char *src_name) 761 { 762 if (src_name[0] == '\0') { 763 message_error(_("Empty filename, skipping")); 764 return NULL; 765 } 766 767 // Since we have only one file open at a time, we can use 768 // a statically allocated structure. 769 static file_pair pair; 770 771 // This implicitly also initializes src_st.st_size to zero 772 // which is expected to be <= 0 by default. fstat() isn't 773 // called when reading from standard input but src_st.st_size 774 // is still read. 775 pair = (file_pair){ 776 .src_name = src_name, 777 .dest_name = NULL, 778 .src_fd = -1, 779 .dest_fd = -1, 780 .src_eof = false, 781 .src_has_seen_input = false, 782 .flush_needed = false, 783 .dest_try_sparse = false, 784 .dest_pending_sparse = 0, 785 }; 786 787 // Block the signals, for which we have a custom signal handler, so 788 // that we don't need to worry about EINTR. 789 signals_block(); 790 const bool error = io_open_src_real(&pair); 791 signals_unblock(); 792 793 #ifdef ENABLE_SANDBOX 794 if (!error) 795 io_sandbox_enter(pair.src_fd); 796 #endif 797 798 return error ? NULL : &pair; 799 } 800 801 802 /// \brief Closes source file of the file_pair structure 803 /// 804 /// \param pair File whose src_fd should be closed 805 /// \param success If true, the file will be removed from the disk if 806 /// closing succeeds and --keep hasn't been used. 807 static void 808 io_close_src(file_pair *pair, bool success) 809 { 810 #ifndef TUKLIB_DOSLIKE 811 if (restore_stdin_flags) { 812 assert(pair->src_fd == STDIN_FILENO); 813 814 restore_stdin_flags = false; 815 816 if (fcntl(STDIN_FILENO, F_SETFL, stdin_flags) == -1) 817 message_error(_("Error restoring the status flags " 818 "to standard input: %s"), 819 strerror(errno)); 820 } 821 #endif 822 823 if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) { 824 // Close the file before possibly unlinking it. On DOS-like 825 // systems this is always required since unlinking will fail 826 // if the file is open. On POSIX systems it usually works 827 // to unlink open files, but in some cases it doesn't and 828 // one gets EBUSY in errno. 829 // 830 // xz 5.2.2 and older unlinked the file before closing it 831 // (except on DOS-like systems). The old code didn't handle 832 // EBUSY and could fail e.g. on some CIFS shares. The 833 // advantage of unlinking before closing is negligible 834 // (avoids a race between close() and stat()/lstat() and 835 // unlink()), so let's keep this simple. 836 (void)close(pair->src_fd); 837 838 if (success && !opt_keep_original) 839 io_unlink(pair->src_name, &pair->src_st); 840 } 841 842 return; 843 } 844 845 846 static bool 847 io_open_dest_real(file_pair *pair) 848 { 849 if (opt_stdout || pair->src_fd == STDIN_FILENO) { 850 // We don't modify or free() this. 851 pair->dest_name = (char *)"(stdout)"; 852 pair->dest_fd = STDOUT_FILENO; 853 #ifdef TUKLIB_DOSLIKE 854 setmode(STDOUT_FILENO, O_BINARY); 855 #else 856 // Try to set O_NONBLOCK if it isn't already set. 857 // If it fails, we assume that stdout is non-blocking 858 // in practice. See the comments in io_open_src_real() 859 // for similar situation with stdin. 860 // 861 // NOTE: O_APPEND may be unset later in this function 862 // and it relies on stdout_flags being set here. 863 stdout_flags = fcntl(STDOUT_FILENO, F_GETFL); 864 if (stdout_flags == -1) { 865 message_error(_("Error getting the file status flags " 866 "from standard output: %s"), 867 strerror(errno)); 868 return true; 869 } 870 871 if ((stdout_flags & O_NONBLOCK) == 0 872 && fcntl(STDOUT_FILENO, F_SETFL, 873 stdout_flags | O_NONBLOCK) != -1) 874 restore_stdout_flags = true; 875 #endif 876 } else { 877 pair->dest_name = suffix_get_dest_name(pair->src_name); 878 if (pair->dest_name == NULL) 879 return true; 880 881 #ifdef __DJGPP__ 882 struct stat st; 883 if (stat(pair->dest_name, &st) == 0) { 884 // Check that it isn't a special file like "prn". 885 if (st.st_dev == -1) { 886 message_error("%s: Refusing to write to " 887 "a DOS special file", 888 pair->dest_name); 889 free(pair->dest_name); 890 return true; 891 } 892 893 // Check that we aren't overwriting the source file. 894 if (st.st_dev == pair->src_st.st_dev 895 && st.st_ino == pair->src_st.st_ino) { 896 message_error("%s: Output file is the same " 897 "as the input file", 898 pair->dest_name); 899 free(pair->dest_name); 900 return true; 901 } 902 } 903 #endif 904 905 // If --force was used, unlink the target file first. 906 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) { 907 message_error(_("%s: Cannot remove: %s"), 908 pair->dest_name, strerror(errno)); 909 free(pair->dest_name); 910 return true; 911 } 912 913 // Open the file. 914 int flags = O_WRONLY | O_BINARY | O_NOCTTY 915 | O_CREAT | O_EXCL; 916 #ifndef TUKLIB_DOSLIKE 917 flags |= O_NONBLOCK; 918 #endif 919 const mode_t mode = S_IRUSR | S_IWUSR; 920 pair->dest_fd = open(pair->dest_name, flags, mode); 921 922 if (pair->dest_fd == -1) { 923 message_error("%s: %s", pair->dest_name, 924 strerror(errno)); 925 free(pair->dest_name); 926 return true; 927 } 928 } 929 930 #ifndef TUKLIB_DOSLIKE 931 // dest_st isn't used on DOS-like systems except as a dummy 932 // argument to io_unlink(), so don't fstat() on such systems. 933 if (fstat(pair->dest_fd, &pair->dest_st)) { 934 // If fstat() really fails, we have a safe fallback here. 935 # if defined(__VMS) 936 pair->dest_st.st_ino[0] = 0; 937 pair->dest_st.st_ino[1] = 0; 938 pair->dest_st.st_ino[2] = 0; 939 # else 940 pair->dest_st.st_dev = 0; 941 pair->dest_st.st_ino = 0; 942 # endif 943 } else if (try_sparse && opt_mode == MODE_DECOMPRESS) { 944 // When writing to standard output, we need to be extra 945 // careful: 946 // - It may be connected to something else than 947 // a regular file. 948 // - We aren't necessarily writing to a new empty file 949 // or to the end of an existing file. 950 // - O_APPEND may be active. 951 // 952 // TODO: I'm keeping this disabled for DOS-like systems 953 // for now. FAT doesn't support sparse files, but NTFS 954 // does, so maybe this should be enabled on Windows after 955 // some testing. 956 if (pair->dest_fd == STDOUT_FILENO) { 957 if (!S_ISREG(pair->dest_st.st_mode)) 958 return false; 959 960 if (stdout_flags & O_APPEND) { 961 // Creating a sparse file is not possible 962 // when O_APPEND is active (it's used by 963 // shell's >> redirection). As I understand 964 // it, it is safe to temporarily disable 965 // O_APPEND in xz, because if someone 966 // happened to write to the same file at the 967 // same time, results would be bad anyway 968 // (users shouldn't assume that xz uses any 969 // specific block size when writing data). 970 // 971 // The write position may be something else 972 // than the end of the file, so we must fix 973 // it to start writing at the end of the file 974 // to imitate O_APPEND. 975 if (lseek(STDOUT_FILENO, 0, SEEK_END) == -1) 976 return false; 977 978 // Construct the new file status flags. 979 // If O_NONBLOCK was set earlier in this 980 // function, it must be kept here too. 981 int flags = stdout_flags & ~O_APPEND; 982 if (restore_stdout_flags) 983 flags |= O_NONBLOCK; 984 985 // If this fcntl() fails, we continue but won't 986 // try to create sparse output. The original 987 // flags will still be restored if needed (to 988 // unset O_NONBLOCK) when the file is finished. 989 if (fcntl(STDOUT_FILENO, F_SETFL, flags) == -1) 990 return false; 991 992 // Disabling O_APPEND succeeded. Mark 993 // that the flags should be restored 994 // in io_close_dest(). (This may have already 995 // been set when enabling O_NONBLOCK.) 996 restore_stdout_flags = true; 997 998 } else if (lseek(STDOUT_FILENO, 0, SEEK_CUR) 999 != pair->dest_st.st_size) { 1000 // Writing won't start exactly at the end 1001 // of the file. We cannot use sparse output, 1002 // because it would probably corrupt the file. 1003 return false; 1004 } 1005 } 1006 1007 pair->dest_try_sparse = true; 1008 } 1009 #endif 1010 1011 return false; 1012 } 1013 1014 1015 extern bool 1016 io_open_dest(file_pair *pair) 1017 { 1018 signals_block(); 1019 const bool ret = io_open_dest_real(pair); 1020 signals_unblock(); 1021 return ret; 1022 } 1023 1024 1025 /// \brief Closes destination file of the file_pair structure 1026 /// 1027 /// \param pair File whose dest_fd should be closed 1028 /// \param success If false, the file will be removed from the disk. 1029 /// 1030 /// \return Zero if closing succeeds. On error, -1 is returned and 1031 /// error message printed. 1032 static bool 1033 io_close_dest(file_pair *pair, bool success) 1034 { 1035 #ifndef TUKLIB_DOSLIKE 1036 // If io_open_dest() has disabled O_APPEND, restore it here. 1037 if (restore_stdout_flags) { 1038 assert(pair->dest_fd == STDOUT_FILENO); 1039 1040 restore_stdout_flags = false; 1041 1042 if (fcntl(STDOUT_FILENO, F_SETFL, stdout_flags) == -1) { 1043 message_error(_("Error restoring the O_APPEND flag " 1044 "to standard output: %s"), 1045 strerror(errno)); 1046 return true; 1047 } 1048 } 1049 #endif 1050 1051 if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO) 1052 return false; 1053 1054 if (close(pair->dest_fd)) { 1055 message_error(_("%s: Closing the file failed: %s"), 1056 pair->dest_name, strerror(errno)); 1057 1058 // Closing destination file failed, so we cannot trust its 1059 // contents. Get rid of junk: 1060 io_unlink(pair->dest_name, &pair->dest_st); 1061 free(pair->dest_name); 1062 return true; 1063 } 1064 1065 // If the operation using this file wasn't successful, we git rid 1066 // of the junk file. 1067 if (!success) 1068 io_unlink(pair->dest_name, &pair->dest_st); 1069 1070 free(pair->dest_name); 1071 1072 return false; 1073 } 1074 1075 1076 extern void 1077 io_close(file_pair *pair, bool success) 1078 { 1079 // Take care of sparseness at the end of the output file. 1080 if (success && pair->dest_try_sparse 1081 && pair->dest_pending_sparse > 0) { 1082 // Seek forward one byte less than the size of the pending 1083 // hole, then write one zero-byte. This way the file grows 1084 // to its correct size. An alternative would be to use 1085 // ftruncate() but that isn't portable enough (e.g. it 1086 // doesn't work with FAT on Linux; FAT isn't that important 1087 // since it doesn't support sparse files anyway, but we don't 1088 // want to create corrupt files on it). 1089 if (lseek(pair->dest_fd, pair->dest_pending_sparse - 1, 1090 SEEK_CUR) == -1) { 1091 message_error(_("%s: Seeking failed when trying " 1092 "to create a sparse file: %s"), 1093 pair->dest_name, strerror(errno)); 1094 success = false; 1095 } else { 1096 const uint8_t zero[1] = { '\0' }; 1097 if (io_write_buf(pair, zero, 1)) 1098 success = false; 1099 } 1100 } 1101 1102 signals_block(); 1103 1104 // Copy the file attributes. We need to skip this if destination 1105 // file isn't open or it is standard output. 1106 if (success && pair->dest_fd != -1 && pair->dest_fd != STDOUT_FILENO) 1107 io_copy_attrs(pair); 1108 1109 // Close the destination first. If it fails, we must not remove 1110 // the source file! 1111 if (io_close_dest(pair, success)) 1112 success = false; 1113 1114 // Close the source file, and unlink it if the operation using this 1115 // file pair was successful and we haven't requested to keep the 1116 // source file. 1117 io_close_src(pair, success); 1118 1119 signals_unblock(); 1120 1121 return; 1122 } 1123 1124 1125 extern void 1126 io_fix_src_pos(file_pair *pair, size_t rewind_size) 1127 { 1128 assert(rewind_size <= IO_BUFFER_SIZE); 1129 1130 if (rewind_size > 0) { 1131 // This doesn't need to work on unseekable file descriptors, 1132 // so just ignore possible errors. 1133 (void)lseek(pair->src_fd, -(off_t)(rewind_size), SEEK_CUR); 1134 } 1135 1136 return; 1137 } 1138 1139 1140 extern size_t 1141 io_read(file_pair *pair, io_buf *buf, size_t size) 1142 { 1143 // We use small buffers here. 1144 assert(size < SSIZE_MAX); 1145 1146 size_t pos = 0; 1147 1148 while (pos < size) { 1149 const ssize_t amount = read( 1150 pair->src_fd, buf->u8 + pos, size - pos); 1151 1152 if (amount == 0) { 1153 pair->src_eof = true; 1154 break; 1155 } 1156 1157 if (amount == -1) { 1158 if (errno == EINTR) { 1159 if (user_abort) 1160 return SIZE_MAX; 1161 1162 continue; 1163 } 1164 1165 #ifndef TUKLIB_DOSLIKE 1166 if (IS_EAGAIN_OR_EWOULDBLOCK(errno)) { 1167 // Disable the flush-timeout if no input has 1168 // been seen since the previous flush and thus 1169 // there would be nothing to flush after the 1170 // timeout expires (avoids busy waiting). 1171 const int timeout = pair->src_has_seen_input 1172 ? mytime_get_flush_timeout() 1173 : -1; 1174 1175 switch (io_wait(pair, timeout, true)) { 1176 case IO_WAIT_MORE: 1177 continue; 1178 1179 case IO_WAIT_ERROR: 1180 return SIZE_MAX; 1181 1182 case IO_WAIT_TIMEOUT: 1183 pair->flush_needed = true; 1184 return pos; 1185 1186 default: 1187 message_bug(); 1188 } 1189 } 1190 #endif 1191 1192 message_error(_("%s: Read error: %s"), 1193 pair->src_name, strerror(errno)); 1194 1195 return SIZE_MAX; 1196 } 1197 1198 pos += (size_t)(amount); 1199 1200 if (!pair->src_has_seen_input) { 1201 pair->src_has_seen_input = true; 1202 mytime_set_flush_time(); 1203 } 1204 } 1205 1206 return pos; 1207 } 1208 1209 1210 extern bool 1211 io_seek_src(file_pair *pair, uint64_t pos) 1212 { 1213 // Caller must not attempt to seek past the end of the input file 1214 // (seeking to 100 in a 100-byte file is seeking to the end of 1215 // the file, not past the end of the file, and thus that is allowed). 1216 // 1217 // This also validates that pos can be safely cast to off_t. 1218 if (pos > (uint64_t)(pair->src_st.st_size)) 1219 message_bug(); 1220 1221 if (lseek(pair->src_fd, (off_t)(pos), SEEK_SET) == -1) { 1222 message_error(_("%s: Error seeking the file: %s"), 1223 pair->src_name, strerror(errno)); 1224 return true; 1225 } 1226 1227 pair->src_eof = false; 1228 1229 return false; 1230 } 1231 1232 1233 extern bool 1234 io_pread(file_pair *pair, io_buf *buf, size_t size, uint64_t pos) 1235 { 1236 // Using lseek() and read() is more portable than pread() and 1237 // for us it is as good as real pread(). 1238 if (io_seek_src(pair, pos)) 1239 return true; 1240 1241 const size_t amount = io_read(pair, buf, size); 1242 if (amount == SIZE_MAX) 1243 return true; 1244 1245 if (amount != size) { 1246 message_error(_("%s: Unexpected end of file"), 1247 pair->src_name); 1248 return true; 1249 } 1250 1251 return false; 1252 } 1253 1254 1255 static bool 1256 is_sparse(const io_buf *buf) 1257 { 1258 assert(IO_BUFFER_SIZE % sizeof(uint64_t) == 0); 1259 1260 for (size_t i = 0; i < ARRAY_SIZE(buf->u64); ++i) 1261 if (buf->u64[i] != 0) 1262 return false; 1263 1264 return true; 1265 } 1266 1267 1268 static bool 1269 io_write_buf(file_pair *pair, const uint8_t *buf, size_t size) 1270 { 1271 assert(size < SSIZE_MAX); 1272 1273 while (size > 0) { 1274 const ssize_t amount = write(pair->dest_fd, buf, size); 1275 if (amount == -1) { 1276 if (errno == EINTR) { 1277 if (user_abort) 1278 return true; 1279 1280 continue; 1281 } 1282 1283 #ifndef TUKLIB_DOSLIKE 1284 if (IS_EAGAIN_OR_EWOULDBLOCK(errno)) { 1285 if (io_wait(pair, -1, false) == IO_WAIT_MORE) 1286 continue; 1287 1288 return true; 1289 } 1290 #endif 1291 1292 // Handle broken pipe specially. gzip and bzip2 1293 // don't print anything on SIGPIPE. In addition, 1294 // gzip --quiet uses exit status 2 (warning) on 1295 // broken pipe instead of whatever raise(SIGPIPE) 1296 // would make it return. It is there to hide "Broken 1297 // pipe" message on some old shells (probably old 1298 // GNU bash). 1299 // 1300 // We don't do anything special with --quiet, which 1301 // is what bzip2 does too. If we get SIGPIPE, we 1302 // will handle it like other signals by setting 1303 // user_abort, and get EPIPE here. 1304 if (errno != EPIPE) 1305 message_error(_("%s: Write error: %s"), 1306 pair->dest_name, strerror(errno)); 1307 1308 return true; 1309 } 1310 1311 buf += (size_t)(amount); 1312 size -= (size_t)(amount); 1313 } 1314 1315 return false; 1316 } 1317 1318 1319 extern bool 1320 io_write(file_pair *pair, const io_buf *buf, size_t size) 1321 { 1322 assert(size <= IO_BUFFER_SIZE); 1323 1324 if (pair->dest_try_sparse) { 1325 // Check if the block is sparse (contains only zeros). If it 1326 // sparse, we just store the amount and return. We will take 1327 // care of actually skipping over the hole when we hit the 1328 // next data block or close the file. 1329 // 1330 // Since io_close() requires that dest_pending_sparse > 0 1331 // if the file ends with sparse block, we must also return 1332 // if size == 0 to avoid doing the lseek(). 1333 if (size == IO_BUFFER_SIZE) { 1334 // Even if the block was sparse, treat it as non-sparse 1335 // if the pending sparse amount is large compared to 1336 // the size of off_t. In practice this only matters 1337 // on 32-bit systems where off_t isn't always 64 bits. 1338 const off_t pending_max 1339 = (off_t)(1) << (sizeof(off_t) * CHAR_BIT - 2); 1340 if (is_sparse(buf) && pair->dest_pending_sparse 1341 < pending_max) { 1342 pair->dest_pending_sparse += (off_t)(size); 1343 return false; 1344 } 1345 } else if (size == 0) { 1346 return false; 1347 } 1348 1349 // This is not a sparse block. If we have a pending hole, 1350 // skip it now. 1351 if (pair->dest_pending_sparse > 0) { 1352 if (lseek(pair->dest_fd, pair->dest_pending_sparse, 1353 SEEK_CUR) == -1) { 1354 message_error(_("%s: Seeking failed when " 1355 "trying to create a sparse " 1356 "file: %s"), pair->dest_name, 1357 strerror(errno)); 1358 return true; 1359 } 1360 1361 pair->dest_pending_sparse = 0; 1362 } 1363 } 1364 1365 return io_write_buf(pair, buf->u8, size); 1366 } 1367