1 ///////////////////////////////////////////////////////////////////////////////
4 /// \brief File opening, unlinking, and closing
6 // Author: Lasse Collin
8 // This file has been put into the public domain.
9 // You can do whatever you want with this file.
11 ///////////////////////////////////////////////////////////////////////////////
20 static bool warn_fchown;
23 #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
24 # include <sys/time.h>
25 #elif defined(HAVE_UTIME)
29 #include "tuklib_open_stdxxx.h"
40 /// If true, try to create sparse files when decompressing.
41 static bool try_sparse = true;
43 #ifndef TUKLIB_DOSLIKE
44 /// File status flags of standard output. This is used by io_open_dest()
45 /// and io_close_dest().
46 static int stdout_flags = 0;
50 static bool io_write_buf(file_pair *pair, const uint8_t *buf, size_t size);
56 // Make sure that stdin, stdout, and and stderr are connected to
57 // a valid file descriptor. Exit immediatelly with exit code ERROR
58 // if we cannot make the file descriptors valid. Maybe we should
59 // print an error message, but our stderr could be screwed anyway.
60 tuklib_open_stdxxx(E_ERROR);
62 #ifndef TUKLIB_DOSLIKE
63 // If fchown() fails setting the owner, we warn about it only if
65 warn_fchown = geteuid() == 0;
69 // Avoid doing useless things when statting files.
70 // This isn't important but doesn't hurt.
71 _djstat_flags = _STAT_INODE | _STAT_EXEC_EXT
72 | _STAT_EXEC_MAGIC | _STAT_DIRSIZE;
87 /// \brief Unlink a file
89 /// This tries to verify that the file being unlinked really is the file that
90 /// we want to unlink by verifying device and inode numbers. There's still
91 /// a small unavoidable race, but this is much better than nothing (the file
92 /// could have been moved/replaced even hours earlier).
94 io_unlink(const char *name, const struct stat *known_st)
96 #if defined(TUKLIB_DOSLIKE)
97 // On DOS-like systems, st_ino is meaningless, so don't bother
98 // testing it. Just silence a compiler warning.
103 if (lstat(name, &new_st)
105 // st_ino is an array, and we don't want to
106 // compare st_dev at all.
107 || memcmp(&new_st.st_ino, &known_st->st_ino,
108 sizeof(new_st.st_ino)) != 0
110 // Typical POSIX-like system
111 || new_st.st_dev != known_st->st_dev
112 || new_st.st_ino != known_st->st_ino
115 // TRANSLATORS: When compression or decompression finishes,
116 // and xz is going to remove the source file, xz first checks
117 // if the source file still exists, and if it does, does its
118 // device and inode numbers match what xz saw when it opened
119 // the source file. If these checks fail, this message is
120 // shown, %s being the filename, and the file is not deleted.
121 // The check for device and inode numbers is there, because
122 // it is possible that the user has put a new file in place
123 // of the original file, and in that case it obviously
124 // shouldn't be removed.
125 message_error(_("%s: File seems to have been moved, "
126 "not removing"), name);
129 // There's a race condition between lstat() and unlink()
130 // but at least we have tried to avoid removing wrong file.
132 message_error(_("%s: Cannot remove: %s"),
133 name, strerror(errno));
139 /// \brief Copies owner/group and permissions
141 /// \todo ACL and EA support
144 io_copy_attrs(const file_pair *pair)
146 // Skip chown and chmod on Windows.
147 #ifndef TUKLIB_DOSLIKE
148 // This function is more tricky than you may think at first.
149 // Blindly copying permissions may permit users to access the
150 // destination file who didn't have permission to access the
153 // Try changing the owner of the file. If we aren't root or the owner
154 // isn't already us, fchown() probably doesn't succeed. We warn
155 // about failing fchown() only if we are root.
156 if (fchown(pair->dest_fd, pair->src_st.st_uid, -1) && warn_fchown)
157 message_warning(_("%s: Cannot set the file owner: %s"),
158 pair->dest_name, strerror(errno));
162 if (fchown(pair->dest_fd, -1, pair->src_st.st_gid)) {
163 message_warning(_("%s: Cannot set the file group: %s"),
164 pair->dest_name, strerror(errno));
165 // We can still safely copy some additional permissions:
166 // `group' must be at least as strict as `other' and
169 // NOTE: After this, the owner of the source file may
170 // get additional permissions. This shouldn't be too bad,
171 // because the owner would have had permission to chmod
172 // the original file anyway.
173 mode = ((pair->src_st.st_mode & 0070) >> 3)
174 & (pair->src_st.st_mode & 0007);
175 mode = (pair->src_st.st_mode & 0700) | (mode << 3) | mode;
177 // Drop the setuid, setgid, and sticky bits.
178 mode = pair->src_st.st_mode & 0777;
181 if (fchmod(pair->dest_fd, mode))
182 message_warning(_("%s: Cannot set the file permissions: %s"),
183 pair->dest_name, strerror(errno));
186 // Copy the timestamps. We have several possible ways to do this, of
187 // which some are better in both security and precision.
189 // First, get the nanosecond part of the timestamps. As of writing,
190 // it's not standardized by POSIX, and there are several names for
191 // the same thing in struct stat.
195 # if defined(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
197 atime_nsec = pair->src_st.st_atim.tv_nsec;
198 mtime_nsec = pair->src_st.st_mtim.tv_nsec;
200 # elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
202 atime_nsec = pair->src_st.st_atimespec.tv_nsec;
203 mtime_nsec = pair->src_st.st_mtimespec.tv_nsec;
205 # elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC)
206 // GNU and BSD without extensions
207 atime_nsec = pair->src_st.st_atimensec;
208 mtime_nsec = pair->src_st.st_mtimensec;
210 # elif defined(HAVE_STRUCT_STAT_ST_UATIME)
212 atime_nsec = pair->src_st.st_uatime * 1000;
213 mtime_nsec = pair->src_st.st_umtime * 1000;
215 # elif defined(HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC)
217 atime_nsec = pair->src_st.st_atim.st__tim.tv_nsec;
218 mtime_nsec = pair->src_st.st_mtim.st__tim.tv_nsec;
226 // Construct a structure to hold the timestamps and call appropriate
227 // function to set the timestamps.
228 #if defined(HAVE_FUTIMENS)
229 // Use nanosecond precision.
230 struct timespec tv[2];
231 tv[0].tv_sec = pair->src_st.st_atime;
232 tv[0].tv_nsec = atime_nsec;
233 tv[1].tv_sec = pair->src_st.st_mtime;
234 tv[1].tv_nsec = mtime_nsec;
236 (void)futimens(pair->dest_fd, tv);
238 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
239 // Use microsecond precision.
240 struct timeval tv[2];
241 tv[0].tv_sec = pair->src_st.st_atime;
242 tv[0].tv_usec = atime_nsec / 1000;
243 tv[1].tv_sec = pair->src_st.st_mtime;
244 tv[1].tv_usec = mtime_nsec / 1000;
246 # if defined(HAVE_FUTIMES)
247 (void)futimes(pair->dest_fd, tv);
248 # elif defined(HAVE_FUTIMESAT)
249 (void)futimesat(pair->dest_fd, NULL, tv);
251 // Argh, no function to use a file descriptor to set the timestamp.
252 (void)utimes(pair->dest_name, tv);
255 #elif defined(HAVE_UTIME)
256 // Use one-second precision. utime() doesn't support using file
257 // descriptor either. Some systems have broken utime() prototype
258 // so don't make this const.
259 struct utimbuf buf = {
260 .actime = pair->src_st.st_atime,
261 .modtime = pair->src_st.st_mtime,
268 (void)utime(pair->dest_name, &buf);
275 /// Opens the source file. Returns false on success, true on error.
277 io_open_src(file_pair *pair)
279 // There's nothing to open when reading from stdin.
280 if (pair->src_name == stdin_filename) {
281 pair->src_fd = STDIN_FILENO;
282 #ifdef TUKLIB_DOSLIKE
283 setmode(STDIN_FILENO, O_BINARY);
288 // Symlinks are not followed unless writing to stdout or --force
290 const bool follow_symlinks = opt_stdout || opt_force;
292 // We accept only regular files if we are writing the output
293 // to disk too. bzip2 allows overriding this with --force but
294 // gzip and xz don't.
295 const bool reg_files_only = !opt_stdout;
298 int flags = O_RDONLY | O_BINARY | O_NOCTTY;
300 #ifndef TUKLIB_DOSLIKE
301 // If we accept only regular files, we need to be careful to avoid
302 // problems with special files like devices and FIFOs. O_NONBLOCK
303 // prevents blocking when opening such files. When we want to accept
304 // special files, we must not use O_NONBLOCK, or otherwise we won't
305 // block waiting e.g. FIFOs to become readable.
310 #if defined(O_NOFOLLOW)
311 if (!follow_symlinks)
313 #elif !defined(TUKLIB_DOSLIKE)
314 // Some POSIX-like systems lack O_NOFOLLOW (it's not required
315 // by POSIX). Check for symlinks with a separate lstat() on
317 if (!follow_symlinks) {
319 if (lstat(pair->src_name, &st)) {
320 message_error("%s: %s", pair->src_name,
324 } else if (S_ISLNK(st.st_mode)) {
325 message_warning(_("%s: Is a symbolic link, "
326 "skipping"), pair->src_name);
332 (void)follow_symlinks;
335 // Try to open the file. If we are accepting non-regular files,
336 // unblock the caught signals so that open() can be interrupted
337 // if it blocks e.g. due to a FIFO file.
341 // Maybe this wouldn't need a loop, since all the signal handlers for
342 // which we don't use SA_RESTART set user_abort to true. But it
343 // doesn't hurt to have it just in case.
345 pair->src_fd = open(pair->src_name, flags);
346 } while (pair->src_fd == -1 && errno == EINTR && !user_abort);
351 if (pair->src_fd == -1) {
352 // If we were interrupted, don't display any error message.
353 if (errno == EINTR) {
354 // All the signals that don't have SA_RESTART
361 // Give an understandable error message in if reason
362 // for failing was that the file was a symbolic link.
364 // Note that at least Linux, OpenBSD, Solaris, and Darwin
365 // use ELOOP to indicate if O_NOFOLLOW was the reason
366 // that open() failed. Because there may be
367 // directories in the pathname, ELOOP may occur also
368 // because of a symlink loop in the directory part.
369 // So ELOOP doesn't tell us what actually went wrong.
371 // FreeBSD associates EMLINK with O_NOFOLLOW and
372 // Tru64 uses ENOTSUP. We use these directly here
373 // and skip the lstat() call and the associated race.
374 // I want to hear if there are other kernels that
375 // fail with something else than ELOOP with O_NOFOLLOW.
376 bool was_symlink = false;
378 # if defined(__FreeBSD__) || defined(__DragonFly__)
382 # elif defined(__digital__) && defined(__unix__)
383 if (errno == ENOTSUP)
386 # elif defined(__NetBSD__)
387 // FIXME? As of 2008-11-20, NetBSD doesn't document what
388 // errno is used with O_NOFOLLOW. It seems to be EFTYPE,
389 // but since it isn't documented, it may be wrong to rely
395 if (errno == ELOOP && !follow_symlinks) {
396 const int saved_errno = errno;
398 if (lstat(pair->src_name, &st) == 0
399 && S_ISLNK(st.st_mode))
407 message_warning(_("%s: Is a symbolic link, "
408 "skipping"), pair->src_name);
411 // Something else than O_NOFOLLOW failing
412 // (assuming that the race conditions didn't
414 message_error("%s: %s", pair->src_name,
420 #ifndef TUKLIB_DOSLIKE
421 // Drop O_NONBLOCK, which is used only when we are accepting only
422 // regular files. After the open() call, we want things to block
423 // instead of giving EAGAIN.
424 if (reg_files_only) {
425 flags = fcntl(pair->src_fd, F_GETFL);
429 flags &= ~O_NONBLOCK;
431 if (fcntl(pair->src_fd, F_SETFL, flags))
436 // Stat the source file. We need the result also when we copy
437 // the permissions, and when unlinking.
438 if (fstat(pair->src_fd, &pair->src_st))
441 if (S_ISDIR(pair->src_st.st_mode)) {
442 message_warning(_("%s: Is a directory, skipping"),
447 if (reg_files_only) {
448 if (!S_ISREG(pair->src_st.st_mode)) {
449 message_warning(_("%s: Not a regular file, "
450 "skipping"), pair->src_name);
454 // These are meaningless on Windows.
455 #ifndef TUKLIB_DOSLIKE
456 if (pair->src_st.st_mode & (S_ISUID | S_ISGID)) {
457 // gzip rejects setuid and setgid files even
458 // when --force was used. bzip2 doesn't check
459 // for them, but calls fchown() after fchmod(),
460 // and many systems automatically drop setuid
461 // and setgid bits there.
463 // We accept setuid and setgid files if
464 // --force was used. We drop these bits
465 // explicitly in io_copy_attr().
466 message_warning(_("%s: File has setuid or "
467 "setgid bit set, skipping"),
472 if (pair->src_st.st_mode & S_ISVTX) {
473 message_warning(_("%s: File has sticky bit "
479 if (pair->src_st.st_nlink > 1) {
480 message_warning(_("%s: Input file has more "
481 "than one hard link, "
482 "skipping"), pair->src_name);
491 message_error("%s: %s", pair->src_name, strerror(errno));
493 (void)close(pair->src_fd);
498 /// \brief Closes source file of the file_pair structure
500 /// \param pair File whose src_fd should be closed
501 /// \param success If true, the file will be removed from the disk if
502 /// closing succeeds and --keep hasn't been used.
504 io_close_src(file_pair *pair, bool success)
506 if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) {
507 #ifdef TUKLIB_DOSLIKE
508 (void)close(pair->src_fd);
511 // If we are going to unlink(), do it before closing the file.
512 // This way there's no risk that someone replaces the file and
513 // happens to get same inode number, which would make us
514 // unlink() wrong file.
516 // NOTE: DOS-like systems are an exception to this, because
517 // they don't allow unlinking files that are open. *sigh*
518 if (success && !opt_keep_original)
519 io_unlink(pair->src_name, &pair->src_st);
521 #ifndef TUKLIB_DOSLIKE
522 (void)close(pair->src_fd);
531 io_open_dest(file_pair *pair)
533 if (opt_stdout || pair->src_fd == STDIN_FILENO) {
534 // We don't modify or free() this.
535 pair->dest_name = (char *)"(stdout)";
536 pair->dest_fd = STDOUT_FILENO;
537 #ifdef TUKLIB_DOSLIKE
538 setmode(STDOUT_FILENO, O_BINARY);
541 pair->dest_name = suffix_get_dest_name(pair->src_name);
542 if (pair->dest_name == NULL)
545 // If --force was used, unlink the target file first.
546 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
547 message_error(_("%s: Cannot remove: %s"),
548 pair->dest_name, strerror(errno));
549 free(pair->dest_name);
554 const int flags = O_WRONLY | O_BINARY | O_NOCTTY
556 const mode_t mode = S_IRUSR | S_IWUSR;
557 pair->dest_fd = open(pair->dest_name, flags, mode);
559 if (pair->dest_fd == -1) {
560 // Don't bother with error message if user requested
561 // us to exit anyway.
563 message_error("%s: %s", pair->dest_name,
566 free(pair->dest_name);
571 // If this really fails... well, we have a safe fallback.
572 if (fstat(pair->dest_fd, &pair->dest_st)) {
574 pair->dest_st.st_ino[0] = 0;
575 pair->dest_st.st_ino[1] = 0;
576 pair->dest_st.st_ino[2] = 0;
577 #elif !defined(TUKLIB_DOSLIKE)
578 pair->dest_st.st_dev = 0;
579 pair->dest_st.st_ino = 0;
581 #ifndef TUKLIB_DOSLIKE
582 } else if (try_sparse && opt_mode == MODE_DECOMPRESS) {
583 // When writing to standard output, we need to be extra
585 // - It may be connected to something else than
587 // - We aren't necessarily writing to a new empty file
588 // or to the end of an existing file.
589 // - O_APPEND may be active.
591 // TODO: I'm keeping this disabled for DOS-like systems
592 // for now. FAT doesn't support sparse files, but NTFS
593 // does, so maybe this should be enabled on Windows after
595 if (pair->dest_fd == STDOUT_FILENO) {
596 if (!S_ISREG(pair->dest_st.st_mode))
599 const int flags = fcntl(STDOUT_FILENO, F_GETFL);
603 if (flags & O_APPEND) {
604 // Creating a sparse file is not possible
605 // when O_APPEND is active (it's used by
606 // shell's >> redirection). As I understand
607 // it, it is safe to temporarily disable
608 // O_APPEND in xz, because if someone
609 // happened to write to the same file at the
610 // same time, results would be bad anyway
611 // (users shouldn't assume that xz uses any
612 // specific block size when writing data).
614 // The write position may be something else
615 // than the end of the file, so we must fix
616 // it to start writing at the end of the file
617 // to imitate O_APPEND.
618 if (lseek(STDOUT_FILENO, 0, SEEK_END) == -1)
621 if (fcntl(STDOUT_FILENO, F_SETFL,
622 stdout_flags & ~O_APPEND))
625 // Remember the flags so that io_close_dest()
627 stdout_flags = flags;
629 } else if (lseek(STDOUT_FILENO, 0, SEEK_CUR)
630 != pair->dest_st.st_size) {
631 // Writing won't start exactly at the end
632 // of the file. We cannot use sparse output,
633 // because it would probably corrupt the file.
638 pair->dest_try_sparse = true;
646 /// \brief Closes destination file of the file_pair structure
648 /// \param pair File whose dest_fd should be closed
649 /// \param success If false, the file will be removed from the disk.
651 /// \return Zero if closing succeeds. On error, -1 is returned and
652 /// error message printed.
654 io_close_dest(file_pair *pair, bool success)
656 #ifndef TUKLIB_DOSLIKE
657 // If io_open_dest() has disabled O_APPEND, restore it here.
658 if (stdout_flags != 0) {
659 assert(pair->dest_fd == STDOUT_FILENO);
661 const int fail = fcntl(STDOUT_FILENO, F_SETFL, stdout_flags);
665 message_error(_("Error restoring the O_APPEND flag "
666 "to standard output: %s"),
673 if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
676 if (close(pair->dest_fd)) {
677 message_error(_("%s: Closing the file failed: %s"),
678 pair->dest_name, strerror(errno));
680 // Closing destination file failed, so we cannot trust its
681 // contents. Get rid of junk:
682 io_unlink(pair->dest_name, &pair->dest_st);
683 free(pair->dest_name);
687 // If the operation using this file wasn't successful, we git rid
690 io_unlink(pair->dest_name, &pair->dest_st);
692 free(pair->dest_name);
699 io_open(const char *src_name)
701 if (is_empty_filename(src_name))
704 // Since we have only one file open at a time, we can use
705 // a statically allocated structure.
706 static file_pair pair;
709 .src_name = src_name,
714 .dest_try_sparse = false,
715 .dest_pending_sparse = 0,
718 // Block the signals, for which we have a custom signal handler, so
719 // that we don't need to worry about EINTR.
722 file_pair *ret = NULL;
723 if (!io_open_src(&pair)) {
724 // io_open_src() may have unblocked the signals temporarily,
725 // and thus user_abort may have got set even if open()
727 if (user_abort || io_open_dest(&pair))
728 io_close_src(&pair, false);
740 io_close(file_pair *pair, bool success)
742 // Take care of sparseness at the end of the output file.
743 if (success && pair->dest_try_sparse
744 && pair->dest_pending_sparse > 0) {
745 // Seek forward one byte less than the size of the pending
746 // hole, then write one zero-byte. This way the file grows
747 // to its correct size. An alternative would be to use
748 // ftruncate() but that isn't portable enough (e.g. it
749 // doesn't work with FAT on Linux; FAT isn't that important
750 // since it doesn't support sparse files anyway, but we don't
751 // want to create corrupt files on it).
752 if (lseek(pair->dest_fd, pair->dest_pending_sparse - 1,
754 message_error(_("%s: Seeking failed when trying "
755 "to create a sparse file: %s"),
756 pair->dest_name, strerror(errno));
759 const uint8_t zero[1] = { '\0' };
760 if (io_write_buf(pair, zero, 1))
767 if (success && pair->dest_fd != STDOUT_FILENO)
770 // Close the destination first. If it fails, we must not remove
772 if (io_close_dest(pair, success))
775 // Close the source file, and unlink it if the operation using this
776 // file pair was successful and we haven't requested to keep the
778 io_close_src(pair, success);
787 io_read(file_pair *pair, io_buf *buf_union, size_t size)
789 // We use small buffers here.
790 assert(size < SSIZE_MAX);
792 uint8_t *buf = buf_union->u8;
796 const ssize_t amount = read(pair->src_fd, buf, left);
799 pair->src_eof = true;
804 if (errno == EINTR) {
811 message_error(_("%s: Read error: %s"),
812 pair->src_name, strerror(errno));
814 // FIXME Is this needed?
815 pair->src_eof = true;
820 buf += (size_t)(amount);
821 left -= (size_t)(amount);
829 io_pread(file_pair *pair, io_buf *buf, size_t size, off_t pos)
831 // Using lseek() and read() is more portable than pread() and
832 // for us it is as good as real pread().
833 if (lseek(pair->src_fd, pos, SEEK_SET) != pos) {
834 message_error(_("%s: Error seeking the file: %s"),
835 pair->src_name, strerror(errno));
839 const size_t amount = io_read(pair, buf, size);
840 if (amount == SIZE_MAX)
843 if (amount != size) {
844 message_error(_("%s: Unexpected end of file"),
854 is_sparse(const io_buf *buf)
856 assert(IO_BUFFER_SIZE % sizeof(uint64_t) == 0);
858 for (size_t i = 0; i < ARRAY_SIZE(buf->u64); ++i)
859 if (buf->u64[i] != 0)
867 io_write_buf(file_pair *pair, const uint8_t *buf, size_t size)
869 assert(size < SSIZE_MAX);
872 const ssize_t amount = write(pair->dest_fd, buf, size);
874 if (errno == EINTR) {
881 // Handle broken pipe specially. gzip and bzip2
882 // don't print anything on SIGPIPE. In addition,
883 // gzip --quiet uses exit status 2 (warning) on
884 // broken pipe instead of whatever raise(SIGPIPE)
885 // would make it return. It is there to hide "Broken
886 // pipe" message on some old shells (probably old
889 // We don't do anything special with --quiet, which
890 // is what bzip2 does too. If we get SIGPIPE, we
891 // will handle it like other signals by setting
892 // user_abort, and get EPIPE here.
894 message_error(_("%s: Write error: %s"),
895 pair->dest_name, strerror(errno));
900 buf += (size_t)(amount);
901 size -= (size_t)(amount);
909 io_write(file_pair *pair, const io_buf *buf, size_t size)
911 assert(size <= IO_BUFFER_SIZE);
913 if (pair->dest_try_sparse) {
914 // Check if the block is sparse (contains only zeros). If it
915 // sparse, we just store the amount and return. We will take
916 // care of actually skipping over the hole when we hit the
917 // next data block or close the file.
919 // Since io_close() requires that dest_pending_sparse > 0
920 // if the file ends with sparse block, we must also return
921 // if size == 0 to avoid doing the lseek().
922 if (size == IO_BUFFER_SIZE) {
923 if (is_sparse(buf)) {
924 pair->dest_pending_sparse += size;
927 } else if (size == 0) {
931 // This is not a sparse block. If we have a pending hole,
933 if (pair->dest_pending_sparse > 0) {
934 if (lseek(pair->dest_fd, pair->dest_pending_sparse,
936 message_error(_("%s: Seeking failed when "
937 "trying to create a sparse "
938 "file: %s"), pair->dest_name,
943 pair->dest_pending_sparse = 0;
947 return io_write_buf(pair, buf->u8, size);