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 /// File status flags of standard output. This is used by io_open_dest()
44 /// and io_close_dest().
45 static int stdout_flags = 0;
48 static bool io_write_buf(file_pair *pair, const uint8_t *buf, size_t size);
54 // Make sure that stdin, stdout, and and stderr are connected to
55 // a valid file descriptor. Exit immediatelly with exit code ERROR
56 // if we cannot make the file descriptors valid. Maybe we should
57 // print an error message, but our stderr could be screwed anyway.
58 tuklib_open_stdxxx(E_ERROR);
60 #ifndef TUKLIB_DOSLIKE
61 // If fchown() fails setting the owner, we warn about it only if
63 warn_fchown = geteuid() == 0;
67 // Avoid doing useless things when statting files.
68 // This isn't important but doesn't hurt.
69 _djstat_flags = _STAT_INODE | _STAT_EXEC_EXT
70 | _STAT_EXEC_MAGIC | _STAT_DIRSIZE;
85 /// \brief Unlink a file
87 /// This tries to verify that the file being unlinked really is the file that
88 /// we want to unlink by verifying device and inode numbers. There's still
89 /// a small unavoidable race, but this is much better than nothing (the file
90 /// could have been moved/replaced even hours earlier).
92 io_unlink(const char *name, const struct stat *known_st)
94 #if defined(TUKLIB_DOSLIKE)
95 // On DOS-like systems, st_ino is meaningless, so don't bother
96 // testing it. Just silence a compiler warning.
101 if (lstat(name, &new_st)
103 // st_ino is an array, and we don't want to
104 // compare st_dev at all.
105 || memcmp(&new_st.st_ino, &known_st->st_ino,
106 sizeof(new_st.st_ino)) != 0
108 // Typical POSIX-like system
109 || new_st.st_dev != known_st->st_dev
110 || new_st.st_ino != known_st->st_ino
113 message_error(_("%s: File seems to be moved, not removing"),
117 // There's a race condition between lstat() and unlink()
118 // but at least we have tried to avoid removing wrong file.
120 message_error(_("%s: Cannot remove: %s"),
121 name, strerror(errno));
127 /// \brief Copies owner/group and permissions
129 /// \todo ACL and EA support
132 io_copy_attrs(const file_pair *pair)
134 // Skip chown and chmod on Windows.
135 #ifndef TUKLIB_DOSLIKE
136 // This function is more tricky than you may think at first.
137 // Blindly copying permissions may permit users to access the
138 // destination file who didn't have permission to access the
141 // Try changing the owner of the file. If we aren't root or the owner
142 // isn't already us, fchown() probably doesn't succeed. We warn
143 // about failing fchown() only if we are root.
144 if (fchown(pair->dest_fd, pair->src_st.st_uid, -1) && warn_fchown)
145 message_warning(_("%s: Cannot set the file owner: %s"),
146 pair->dest_name, strerror(errno));
150 if (fchown(pair->dest_fd, -1, pair->src_st.st_gid)) {
151 message_warning(_("%s: Cannot set the file group: %s"),
152 pair->dest_name, strerror(errno));
153 // We can still safely copy some additional permissions:
154 // `group' must be at least as strict as `other' and
157 // NOTE: After this, the owner of the source file may
158 // get additional permissions. This shouldn't be too bad,
159 // because the owner would have had permission to chmod
160 // the original file anyway.
161 mode = ((pair->src_st.st_mode & 0070) >> 3)
162 & (pair->src_st.st_mode & 0007);
163 mode = (pair->src_st.st_mode & 0700) | (mode << 3) | mode;
165 // Drop the setuid, setgid, and sticky bits.
166 mode = pair->src_st.st_mode & 0777;
169 if (fchmod(pair->dest_fd, mode))
170 message_warning(_("%s: Cannot set the file permissions: %s"),
171 pair->dest_name, strerror(errno));
174 // Copy the timestamps. We have several possible ways to do this, of
175 // which some are better in both security and precision.
177 // First, get the nanosecond part of the timestamps. As of writing,
178 // it's not standardized by POSIX, and there are several names for
179 // the same thing in struct stat.
183 # if defined(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
185 atime_nsec = pair->src_st.st_atim.tv_nsec;
186 mtime_nsec = pair->src_st.st_mtim.tv_nsec;
188 # elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
190 atime_nsec = pair->src_st.st_atimespec.tv_nsec;
191 mtime_nsec = pair->src_st.st_mtimespec.tv_nsec;
193 # elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC)
194 // GNU and BSD without extensions
195 atime_nsec = pair->src_st.st_atimensec;
196 mtime_nsec = pair->src_st.st_mtimensec;
198 # elif defined(HAVE_STRUCT_STAT_ST_UATIME)
200 atime_nsec = pair->src_st.st_uatime * 1000;
201 mtime_nsec = pair->src_st.st_umtime * 1000;
203 # elif defined(HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC)
205 atime_nsec = pair->src_st.st_atim.st__tim.tv_nsec;
206 mtime_nsec = pair->src_st.st_mtim.st__tim.tv_nsec;
214 // Construct a structure to hold the timestamps and call appropriate
215 // function to set the timestamps.
216 #if defined(HAVE_FUTIMENS)
217 // Use nanosecond precision.
218 struct timespec tv[2];
219 tv[0].tv_sec = pair->src_st.st_atime;
220 tv[0].tv_nsec = atime_nsec;
221 tv[1].tv_sec = pair->src_st.st_mtime;
222 tv[1].tv_nsec = mtime_nsec;
224 (void)futimens(pair->dest_fd, tv);
226 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
227 // Use microsecond precision.
228 struct timeval tv[2];
229 tv[0].tv_sec = pair->src_st.st_atime;
230 tv[0].tv_usec = atime_nsec / 1000;
231 tv[1].tv_sec = pair->src_st.st_mtime;
232 tv[1].tv_usec = mtime_nsec / 1000;
234 # if defined(HAVE_FUTIMES)
235 (void)futimes(pair->dest_fd, tv);
236 # elif defined(HAVE_FUTIMESAT)
237 (void)futimesat(pair->dest_fd, NULL, tv);
239 // Argh, no function to use a file descriptor to set the timestamp.
240 (void)utimes(pair->dest_name, tv);
243 #elif defined(HAVE_UTIME)
244 // Use one-second precision. utime() doesn't support using file
245 // descriptor either. Some systems have broken utime() prototype
246 // so don't make this const.
247 struct utimbuf buf = {
248 .actime = pair->src_st.st_atime,
249 .modtime = pair->src_st.st_mtime,
256 (void)utime(pair->dest_name, &buf);
263 /// Opens the source file. Returns false on success, true on error.
265 io_open_src(file_pair *pair)
267 // There's nothing to open when reading from stdin.
268 if (pair->src_name == stdin_filename) {
269 pair->src_fd = STDIN_FILENO;
270 #ifdef TUKLIB_DOSLIKE
271 setmode(STDIN_FILENO, O_BINARY);
276 // We accept only regular files if we are writing the output
277 // to disk too, and if --force was not given.
278 const bool reg_files_only = !opt_stdout && !opt_force;
281 int flags = O_RDONLY | O_BINARY | O_NOCTTY;
283 #ifndef TUKLIB_DOSLIKE
284 // If we accept only regular files, we need to be careful to avoid
285 // problems with special files like devices and FIFOs. O_NONBLOCK
286 // prevents blocking when opening such files. When we want to accept
287 // special files, we must not use O_NONBLOCK, or otherwise we won't
288 // block waiting e.g. FIFOs to become readable.
293 #if defined(O_NOFOLLOW)
296 #elif !defined(TUKLIB_DOSLIKE)
297 // Some POSIX-like systems lack O_NOFOLLOW (it's not required
298 // by POSIX). Check for symlinks with a separate lstat() on
300 if (reg_files_only) {
302 if (lstat(pair->src_name, &st)) {
303 message_error("%s: %s", pair->src_name,
307 } else if (S_ISLNK(st.st_mode)) {
308 message_warning(_("%s: Is a symbolic link, "
309 "skipping"), pair->src_name);
315 // Try to open the file. If we are accepting non-regular files,
316 // unblock the caught signals so that open() can be interrupted
317 // if it blocks e.g. due to a FIFO file.
321 // Maybe this wouldn't need a loop, since all the signal handlers for
322 // which we don't use SA_RESTART set user_abort to true. But it
323 // doesn't hurt to have it just in case.
325 pair->src_fd = open(pair->src_name, flags);
326 } while (pair->src_fd == -1 && errno == EINTR && !user_abort);
331 if (pair->src_fd == -1) {
332 // If we were interrupted, don't display any error message.
333 if (errno == EINTR) {
334 // All the signals that don't have SA_RESTART
341 // Give an understandable error message in if reason
342 // for failing was that the file was a symbolic link.
344 // Note that at least Linux, OpenBSD, Solaris, and Darwin
345 // use ELOOP to indicate if O_NOFOLLOW was the reason
346 // that open() failed. Because there may be
347 // directories in the pathname, ELOOP may occur also
348 // because of a symlink loop in the directory part.
349 // So ELOOP doesn't tell us what actually went wrong.
351 // FreeBSD associates EMLINK with O_NOFOLLOW and
352 // Tru64 uses ENOTSUP. We use these directly here
353 // and skip the lstat() call and the associated race.
354 // I want to hear if there are other kernels that
355 // fail with something else than ELOOP with O_NOFOLLOW.
356 bool was_symlink = false;
358 # if defined(__FreeBSD__) || defined(__DragonFly__)
362 # elif defined(__digital__) && defined(__unix__)
363 if (errno == ENOTSUP)
366 # elif defined(__NetBSD__)
367 // FIXME? As of 2008-11-20, NetBSD doesn't document what
368 // errno is used with O_NOFOLLOW. It seems to be EFTYPE,
369 // but since it isn't documented, it may be wrong to rely
375 if (errno == ELOOP && reg_files_only) {
376 const int saved_errno = errno;
378 if (lstat(pair->src_name, &st) == 0
379 && S_ISLNK(st.st_mode))
387 message_warning(_("%s: Is a symbolic link, "
388 "skipping"), pair->src_name);
391 // Something else than O_NOFOLLOW failing
392 // (assuming that the race conditions didn't
394 message_error("%s: %s", pair->src_name,
400 #ifndef TUKLIB_DOSLIKE
401 // Drop O_NONBLOCK, which is used only when we are accepting only
402 // regular files. After the open() call, we want things to block
403 // instead of giving EAGAIN.
404 if (reg_files_only) {
405 flags = fcntl(pair->src_fd, F_GETFL);
409 flags &= ~O_NONBLOCK;
411 if (fcntl(pair->src_fd, F_SETFL, flags))
416 // Stat the source file. We need the result also when we copy
417 // the permissions, and when unlinking.
418 if (fstat(pair->src_fd, &pair->src_st))
421 if (S_ISDIR(pair->src_st.st_mode)) {
422 message_warning(_("%s: Is a directory, skipping"),
427 if (reg_files_only) {
428 if (!S_ISREG(pair->src_st.st_mode)) {
429 message_warning(_("%s: Not a regular file, "
430 "skipping"), pair->src_name);
434 // These are meaningless on Windows.
435 #ifndef TUKLIB_DOSLIKE
436 if (pair->src_st.st_mode & (S_ISUID | S_ISGID)) {
437 // gzip rejects setuid and setgid files even
438 // when --force was used. bzip2 doesn't check
439 // for them, but calls fchown() after fchmod(),
440 // and many systems automatically drop setuid
441 // and setgid bits there.
443 // We accept setuid and setgid files if
444 // --force was used. We drop these bits
445 // explicitly in io_copy_attr().
446 message_warning(_("%s: File has setuid or "
447 "setgid bit set, skipping"),
452 if (pair->src_st.st_mode & S_ISVTX) {
453 message_warning(_("%s: File has sticky bit "
459 if (pair->src_st.st_nlink > 1) {
460 message_warning(_("%s: Input file has more "
461 "than one hard link, "
462 "skipping"), pair->src_name);
471 message_error("%s: %s", pair->src_name, strerror(errno));
473 (void)close(pair->src_fd);
478 /// \brief Closes source file of the file_pair structure
480 /// \param pair File whose src_fd should be closed
481 /// \param success If true, the file will be removed from the disk if
482 /// closing succeeds and --keep hasn't been used.
484 io_close_src(file_pair *pair, bool success)
486 if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) {
487 #ifdef TUKLIB_DOSLIKE
488 (void)close(pair->src_fd);
491 // If we are going to unlink(), do it before closing the file.
492 // This way there's no risk that someone replaces the file and
493 // happens to get same inode number, which would make us
494 // unlink() wrong file.
496 // NOTE: DOS-like systems are an exception to this, because
497 // they don't allow unlinking files that are open. *sigh*
498 if (success && !opt_keep_original)
499 io_unlink(pair->src_name, &pair->src_st);
501 #ifndef TUKLIB_DOSLIKE
502 (void)close(pair->src_fd);
511 io_open_dest(file_pair *pair)
513 if (opt_stdout || pair->src_fd == STDIN_FILENO) {
514 // We don't modify or free() this.
515 pair->dest_name = (char *)"(stdout)";
516 pair->dest_fd = STDOUT_FILENO;
517 #ifdef TUKLIB_DOSLIKE
518 setmode(STDOUT_FILENO, O_BINARY);
521 pair->dest_name = suffix_get_dest_name(pair->src_name);
522 if (pair->dest_name == NULL)
525 // If --force was used, unlink the target file first.
526 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
527 message_error(_("%s: Cannot remove: %s"),
528 pair->dest_name, strerror(errno));
529 free(pair->dest_name);
534 const int flags = O_WRONLY | O_BINARY | O_NOCTTY
536 const mode_t mode = S_IRUSR | S_IWUSR;
537 pair->dest_fd = open(pair->dest_name, flags, mode);
539 if (pair->dest_fd == -1) {
540 // Don't bother with error message if user requested
541 // us to exit anyway.
543 message_error("%s: %s", pair->dest_name,
546 free(pair->dest_name);
551 // If this really fails... well, we have a safe fallback.
552 if (fstat(pair->dest_fd, &pair->dest_st)) {
554 pair->dest_st.st_ino[0] = 0;
555 pair->dest_st.st_ino[1] = 0;
556 pair->dest_st.st_ino[2] = 0;
557 #elif !defined(TUKLIB_DOSLIKE)
558 pair->dest_st.st_dev = 0;
559 pair->dest_st.st_ino = 0;
561 #ifndef TUKLIB_DOSLIKE
562 } else if (try_sparse && opt_mode == MODE_DECOMPRESS) {
563 // When writing to standard output, we need to be extra
565 // - It may be connected to something else than
567 // - We aren't necessarily writing to a new empty file
568 // or to the end of an existing file.
569 // - O_APPEND may be active.
571 // TODO: I'm keeping this disabled for DOS-like systems
572 // for now. FAT doesn't support sparse files, but NTFS
573 // does, so maybe this should be enabled on Windows after
575 if (pair->dest_fd == STDOUT_FILENO) {
576 if (!S_ISREG(pair->dest_st.st_mode))
579 const int flags = fcntl(STDOUT_FILENO, F_GETFL);
583 if (flags & O_APPEND) {
584 // Creating a sparse file is not possible
585 // when O_APPEND is active (it's used by
586 // shell's >> redirection). As I understand
587 // it, it is safe to temporarily disable
588 // O_APPEND in xz, because if someone
589 // happened to write to the same file at the
590 // same time, results would be bad anyway
591 // (users shouldn't assume that xz uses any
592 // specific block size when writing data).
594 // The write position may be something else
595 // than the end of the file, so we must fix
596 // it to start writing at the end of the file
597 // to imitate O_APPEND.
598 if (lseek(STDOUT_FILENO, 0, SEEK_END) == -1)
601 if (fcntl(STDOUT_FILENO, F_SETFL,
602 stdout_flags & ~O_APPEND))
605 // Remember the flags so that io_close_dest()
607 stdout_flags = flags;
609 } else if (lseek(STDOUT_FILENO, 0, SEEK_CUR)
610 != pair->dest_st.st_size) {
611 // Writing won't start exactly at the end
612 // of the file. We cannot use sparse output,
613 // because it would probably corrupt the file.
618 pair->dest_try_sparse = true;
626 /// \brief Closes destination file of the file_pair structure
628 /// \param pair File whose dest_fd should be closed
629 /// \param success If false, the file will be removed from the disk.
631 /// \return Zero if closing succeeds. On error, -1 is returned and
632 /// error message printed.
634 io_close_dest(file_pair *pair, bool success)
636 // If io_open_dest() has disabled O_APPEND, restore it here.
637 if (stdout_flags != 0) {
638 assert(pair->dest_fd == STDOUT_FILENO);
640 const int fail = fcntl(STDOUT_FILENO, F_SETFL, stdout_flags);
644 message_error(_("Error restoring the O_APPEND flag "
645 "to standard output: %s"),
651 if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
654 if (close(pair->dest_fd)) {
655 message_error(_("%s: Closing the file failed: %s"),
656 pair->dest_name, strerror(errno));
658 // Closing destination file failed, so we cannot trust its
659 // contents. Get rid of junk:
660 io_unlink(pair->dest_name, &pair->dest_st);
661 free(pair->dest_name);
665 // If the operation using this file wasn't successful, we git rid
668 io_unlink(pair->dest_name, &pair->dest_st);
670 free(pair->dest_name);
677 io_open(const char *src_name)
679 if (is_empty_filename(src_name))
682 // Since we have only one file open at a time, we can use
683 // a statically allocated structure.
684 static file_pair pair;
687 .src_name = src_name,
692 .dest_try_sparse = false,
693 .dest_pending_sparse = 0,
696 // Block the signals, for which we have a custom signal handler, so
697 // that we don't need to worry about EINTR.
700 file_pair *ret = NULL;
701 if (!io_open_src(&pair)) {
702 // io_open_src() may have unblocked the signals temporarily,
703 // and thus user_abort may have got set even if open()
705 if (user_abort || io_open_dest(&pair))
706 io_close_src(&pair, false);
718 io_close(file_pair *pair, bool success)
720 // Take care of sparseness at the end of the output file.
721 if (success && pair->dest_try_sparse
722 && pair->dest_pending_sparse > 0) {
723 // Seek forward one byte less than the size of the pending
724 // hole, then write one zero-byte. This way the file grows
725 // to its correct size. An alternative would be to use
726 // ftruncate() but that isn't portable enough (e.g. it
727 // doesn't work with FAT on Linux; FAT isn't that important
728 // since it doesn't support sparse files anyway, but we don't
729 // want to create corrupt files on it).
730 if (lseek(pair->dest_fd, pair->dest_pending_sparse - 1,
732 message_error(_("%s: Seeking failed when trying "
733 "to create a sparse file: %s"),
734 pair->dest_name, strerror(errno));
737 const uint8_t zero[1] = { '\0' };
738 if (io_write_buf(pair, zero, 1))
745 if (success && pair->dest_fd != STDOUT_FILENO)
748 // Close the destination first. If it fails, we must not remove
750 if (io_close_dest(pair, success))
753 // Close the source file, and unlink it if the operation using this
754 // file pair was successful and we haven't requested to keep the
756 io_close_src(pair, success);
765 io_read(file_pair *pair, io_buf *buf_union, size_t size)
767 // We use small buffers here.
768 assert(size < SSIZE_MAX);
770 uint8_t *buf = buf_union->u8;
774 const ssize_t amount = read(pair->src_fd, buf, left);
777 pair->src_eof = true;
782 if (errno == EINTR) {
789 message_error(_("%s: Read error: %s"),
790 pair->src_name, strerror(errno));
792 // FIXME Is this needed?
793 pair->src_eof = true;
798 buf += (size_t)(amount);
799 left -= (size_t)(amount);
807 is_sparse(const io_buf *buf)
809 assert(IO_BUFFER_SIZE % sizeof(uint64_t) == 0);
811 for (size_t i = 0; i < ARRAY_SIZE(buf->u64); ++i)
812 if (buf->u64[i] != 0)
820 io_write_buf(file_pair *pair, const uint8_t *buf, size_t size)
822 assert(size < SSIZE_MAX);
825 const ssize_t amount = write(pair->dest_fd, buf, size);
827 if (errno == EINTR) {
834 // Handle broken pipe specially. gzip and bzip2
835 // don't print anything on SIGPIPE. In addition,
836 // gzip --quiet uses exit status 2 (warning) on
837 // broken pipe instead of whatever raise(SIGPIPE)
838 // would make it return. It is there to hide "Broken
839 // pipe" message on some old shells (probably old
842 // We don't do anything special with --quiet, which
843 // is what bzip2 does too. If we get SIGPIPE, we
844 // will handle it like other signals by setting
845 // user_abort, and get EPIPE here.
847 message_error(_("%s: Write error: %s"),
848 pair->dest_name, strerror(errno));
853 buf += (size_t)(amount);
854 size -= (size_t)(amount);
862 io_write(file_pair *pair, const io_buf *buf, size_t size)
864 assert(size <= IO_BUFFER_SIZE);
866 if (pair->dest_try_sparse) {
867 // Check if the block is sparse (contains only zeros). If it
868 // sparse, we just store the amount and return. We will take
869 // care of actually skipping over the hole when we hit the
870 // next data block or close the file.
872 // Since io_close() requires that dest_pending_sparse > 0
873 // if the file ends with sparse block, we must also return
874 // if size == 0 to avoid doing the lseek().
875 if (size == IO_BUFFER_SIZE) {
876 if (is_sparse(buf)) {
877 pair->dest_pending_sparse += size;
880 } else if (size == 0) {
884 // This is not a sparse block. If we have a pending hole,
886 if (pair->dest_pending_sparse > 0) {
887 if (lseek(pair->dest_fd, pair->dest_pending_sparse,
889 message_error(_("%s: Seeking failed when "
890 "trying to create a sparse "
891 "file: %s"), pair->dest_name,
896 pair->dest_pending_sparse = 0;
900 return io_write_buf(pair, buf->u8, size);