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 // Try to open the file. If we are accepting non-regular files,
333 // unblock the caught signals so that open() can be interrupted
334 // if it blocks e.g. due to a FIFO file.
338 // Maybe this wouldn't need a loop, since all the signal handlers for
339 // which we don't use SA_RESTART set user_abort to true. But it
340 // doesn't hurt to have it just in case.
342 pair->src_fd = open(pair->src_name, flags);
343 } while (pair->src_fd == -1 && errno == EINTR && !user_abort);
348 if (pair->src_fd == -1) {
349 // If we were interrupted, don't display any error message.
350 if (errno == EINTR) {
351 // All the signals that don't have SA_RESTART
358 // Give an understandable error message in if reason
359 // for failing was that the file was a symbolic link.
361 // Note that at least Linux, OpenBSD, Solaris, and Darwin
362 // use ELOOP to indicate if O_NOFOLLOW was the reason
363 // that open() failed. Because there may be
364 // directories in the pathname, ELOOP may occur also
365 // because of a symlink loop in the directory part.
366 // So ELOOP doesn't tell us what actually went wrong.
368 // FreeBSD associates EMLINK with O_NOFOLLOW and
369 // Tru64 uses ENOTSUP. We use these directly here
370 // and skip the lstat() call and the associated race.
371 // I want to hear if there are other kernels that
372 // fail with something else than ELOOP with O_NOFOLLOW.
373 bool was_symlink = false;
375 # if defined(__FreeBSD__) || defined(__DragonFly__)
379 # elif defined(__digital__) && defined(__unix__)
380 if (errno == ENOTSUP)
383 # elif defined(__NetBSD__)
384 // FIXME? As of 2008-11-20, NetBSD doesn't document what
385 // errno is used with O_NOFOLLOW. It seems to be EFTYPE,
386 // but since it isn't documented, it may be wrong to rely
392 if (errno == ELOOP && !follow_symlinks) {
393 const int saved_errno = errno;
395 if (lstat(pair->src_name, &st) == 0
396 && S_ISLNK(st.st_mode))
404 message_warning(_("%s: Is a symbolic link, "
405 "skipping"), pair->src_name);
408 // Something else than O_NOFOLLOW failing
409 // (assuming that the race conditions didn't
411 message_error("%s: %s", pair->src_name,
417 #ifndef TUKLIB_DOSLIKE
418 // Drop O_NONBLOCK, which is used only when we are accepting only
419 // regular files. After the open() call, we want things to block
420 // instead of giving EAGAIN.
421 if (reg_files_only) {
422 flags = fcntl(pair->src_fd, F_GETFL);
426 flags &= ~O_NONBLOCK;
428 if (fcntl(pair->src_fd, F_SETFL, flags))
433 // Stat the source file. We need the result also when we copy
434 // the permissions, and when unlinking.
435 if (fstat(pair->src_fd, &pair->src_st))
438 if (S_ISDIR(pair->src_st.st_mode)) {
439 message_warning(_("%s: Is a directory, skipping"),
444 if (reg_files_only) {
445 if (!S_ISREG(pair->src_st.st_mode)) {
446 message_warning(_("%s: Not a regular file, "
447 "skipping"), pair->src_name);
451 // These are meaningless on Windows.
452 #ifndef TUKLIB_DOSLIKE
453 if (pair->src_st.st_mode & (S_ISUID | S_ISGID)) {
454 // gzip rejects setuid and setgid files even
455 // when --force was used. bzip2 doesn't check
456 // for them, but calls fchown() after fchmod(),
457 // and many systems automatically drop setuid
458 // and setgid bits there.
460 // We accept setuid and setgid files if
461 // --force was used. We drop these bits
462 // explicitly in io_copy_attr().
463 message_warning(_("%s: File has setuid or "
464 "setgid bit set, skipping"),
469 if (pair->src_st.st_mode & S_ISVTX) {
470 message_warning(_("%s: File has sticky bit "
476 if (pair->src_st.st_nlink > 1) {
477 message_warning(_("%s: Input file has more "
478 "than one hard link, "
479 "skipping"), pair->src_name);
488 message_error("%s: %s", pair->src_name, strerror(errno));
490 (void)close(pair->src_fd);
495 /// \brief Closes source file of the file_pair structure
497 /// \param pair File whose src_fd should be closed
498 /// \param success If true, the file will be removed from the disk if
499 /// closing succeeds and --keep hasn't been used.
501 io_close_src(file_pair *pair, bool success)
503 if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) {
504 #ifdef TUKLIB_DOSLIKE
505 (void)close(pair->src_fd);
508 // If we are going to unlink(), do it before closing the file.
509 // This way there's no risk that someone replaces the file and
510 // happens to get same inode number, which would make us
511 // unlink() wrong file.
513 // NOTE: DOS-like systems are an exception to this, because
514 // they don't allow unlinking files that are open. *sigh*
515 if (success && !opt_keep_original)
516 io_unlink(pair->src_name, &pair->src_st);
518 #ifndef TUKLIB_DOSLIKE
519 (void)close(pair->src_fd);
528 io_open_dest(file_pair *pair)
530 if (opt_stdout || pair->src_fd == STDIN_FILENO) {
531 // We don't modify or free() this.
532 pair->dest_name = (char *)"(stdout)";
533 pair->dest_fd = STDOUT_FILENO;
534 #ifdef TUKLIB_DOSLIKE
535 setmode(STDOUT_FILENO, O_BINARY);
538 pair->dest_name = suffix_get_dest_name(pair->src_name);
539 if (pair->dest_name == NULL)
542 // If --force was used, unlink the target file first.
543 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
544 message_error(_("%s: Cannot remove: %s"),
545 pair->dest_name, strerror(errno));
546 free(pair->dest_name);
551 const int flags = O_WRONLY | O_BINARY | O_NOCTTY
553 const mode_t mode = S_IRUSR | S_IWUSR;
554 pair->dest_fd = open(pair->dest_name, flags, mode);
556 if (pair->dest_fd == -1) {
557 // Don't bother with error message if user requested
558 // us to exit anyway.
560 message_error("%s: %s", pair->dest_name,
563 free(pair->dest_name);
568 // If this really fails... well, we have a safe fallback.
569 if (fstat(pair->dest_fd, &pair->dest_st)) {
571 pair->dest_st.st_ino[0] = 0;
572 pair->dest_st.st_ino[1] = 0;
573 pair->dest_st.st_ino[2] = 0;
574 #elif !defined(TUKLIB_DOSLIKE)
575 pair->dest_st.st_dev = 0;
576 pair->dest_st.st_ino = 0;
578 #ifndef TUKLIB_DOSLIKE
579 } else if (try_sparse && opt_mode == MODE_DECOMPRESS) {
580 // When writing to standard output, we need to be extra
582 // - It may be connected to something else than
584 // - We aren't necessarily writing to a new empty file
585 // or to the end of an existing file.
586 // - O_APPEND may be active.
588 // TODO: I'm keeping this disabled for DOS-like systems
589 // for now. FAT doesn't support sparse files, but NTFS
590 // does, so maybe this should be enabled on Windows after
592 if (pair->dest_fd == STDOUT_FILENO) {
593 if (!S_ISREG(pair->dest_st.st_mode))
596 const int flags = fcntl(STDOUT_FILENO, F_GETFL);
600 if (flags & O_APPEND) {
601 // Creating a sparse file is not possible
602 // when O_APPEND is active (it's used by
603 // shell's >> redirection). As I understand
604 // it, it is safe to temporarily disable
605 // O_APPEND in xz, because if someone
606 // happened to write to the same file at the
607 // same time, results would be bad anyway
608 // (users shouldn't assume that xz uses any
609 // specific block size when writing data).
611 // The write position may be something else
612 // than the end of the file, so we must fix
613 // it to start writing at the end of the file
614 // to imitate O_APPEND.
615 if (lseek(STDOUT_FILENO, 0, SEEK_END) == -1)
618 if (fcntl(STDOUT_FILENO, F_SETFL,
619 stdout_flags & ~O_APPEND))
622 // Remember the flags so that io_close_dest()
624 stdout_flags = flags;
626 } else if (lseek(STDOUT_FILENO, 0, SEEK_CUR)
627 != pair->dest_st.st_size) {
628 // Writing won't start exactly at the end
629 // of the file. We cannot use sparse output,
630 // because it would probably corrupt the file.
635 pair->dest_try_sparse = true;
643 /// \brief Closes destination file of the file_pair structure
645 /// \param pair File whose dest_fd should be closed
646 /// \param success If false, the file will be removed from the disk.
648 /// \return Zero if closing succeeds. On error, -1 is returned and
649 /// error message printed.
651 io_close_dest(file_pair *pair, bool success)
653 #ifndef TUKLIB_DOSLIKE
654 // If io_open_dest() has disabled O_APPEND, restore it here.
655 if (stdout_flags != 0) {
656 assert(pair->dest_fd == STDOUT_FILENO);
658 const int fail = fcntl(STDOUT_FILENO, F_SETFL, stdout_flags);
662 message_error(_("Error restoring the O_APPEND flag "
663 "to standard output: %s"),
670 if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
673 if (close(pair->dest_fd)) {
674 message_error(_("%s: Closing the file failed: %s"),
675 pair->dest_name, strerror(errno));
677 // Closing destination file failed, so we cannot trust its
678 // contents. Get rid of junk:
679 io_unlink(pair->dest_name, &pair->dest_st);
680 free(pair->dest_name);
684 // If the operation using this file wasn't successful, we git rid
687 io_unlink(pair->dest_name, &pair->dest_st);
689 free(pair->dest_name);
696 io_open(const char *src_name)
698 if (is_empty_filename(src_name))
701 // Since we have only one file open at a time, we can use
702 // a statically allocated structure.
703 static file_pair pair;
706 .src_name = src_name,
711 .dest_try_sparse = false,
712 .dest_pending_sparse = 0,
715 // Block the signals, for which we have a custom signal handler, so
716 // that we don't need to worry about EINTR.
719 file_pair *ret = NULL;
720 if (!io_open_src(&pair)) {
721 // io_open_src() may have unblocked the signals temporarily,
722 // and thus user_abort may have got set even if open()
724 if (user_abort || io_open_dest(&pair))
725 io_close_src(&pair, false);
737 io_close(file_pair *pair, bool success)
739 // Take care of sparseness at the end of the output file.
740 if (success && pair->dest_try_sparse
741 && pair->dest_pending_sparse > 0) {
742 // Seek forward one byte less than the size of the pending
743 // hole, then write one zero-byte. This way the file grows
744 // to its correct size. An alternative would be to use
745 // ftruncate() but that isn't portable enough (e.g. it
746 // doesn't work with FAT on Linux; FAT isn't that important
747 // since it doesn't support sparse files anyway, but we don't
748 // want to create corrupt files on it).
749 if (lseek(pair->dest_fd, pair->dest_pending_sparse - 1,
751 message_error(_("%s: Seeking failed when trying "
752 "to create a sparse file: %s"),
753 pair->dest_name, strerror(errno));
756 const uint8_t zero[1] = { '\0' };
757 if (io_write_buf(pair, zero, 1))
764 if (success && pair->dest_fd != STDOUT_FILENO)
767 // Close the destination first. If it fails, we must not remove
769 if (io_close_dest(pair, success))
772 // Close the source file, and unlink it if the operation using this
773 // file pair was successful and we haven't requested to keep the
775 io_close_src(pair, success);
784 io_read(file_pair *pair, io_buf *buf_union, size_t size)
786 // We use small buffers here.
787 assert(size < SSIZE_MAX);
789 uint8_t *buf = buf_union->u8;
793 const ssize_t amount = read(pair->src_fd, buf, left);
796 pair->src_eof = true;
801 if (errno == EINTR) {
808 message_error(_("%s: Read error: %s"),
809 pair->src_name, strerror(errno));
811 // FIXME Is this needed?
812 pair->src_eof = true;
817 buf += (size_t)(amount);
818 left -= (size_t)(amount);
826 io_pread(file_pair *pair, io_buf *buf, size_t size, off_t pos)
828 // Using lseek() and read() is more portable than pread() and
829 // for us it is as good as real pread().
830 if (lseek(pair->src_fd, pos, SEEK_SET) != pos) {
831 message_error(_("%s: Error seeking the file: %s"),
832 pair->src_name, strerror(errno));
836 const size_t amount = io_read(pair, buf, size);
837 if (amount == SIZE_MAX)
840 if (amount != size) {
841 message_error(_("%s: Unexpected end of file"),
851 is_sparse(const io_buf *buf)
853 assert(IO_BUFFER_SIZE % sizeof(uint64_t) == 0);
855 for (size_t i = 0; i < ARRAY_SIZE(buf->u64); ++i)
856 if (buf->u64[i] != 0)
864 io_write_buf(file_pair *pair, const uint8_t *buf, size_t size)
866 assert(size < SSIZE_MAX);
869 const ssize_t amount = write(pair->dest_fd, buf, size);
871 if (errno == EINTR) {
878 // Handle broken pipe specially. gzip and bzip2
879 // don't print anything on SIGPIPE. In addition,
880 // gzip --quiet uses exit status 2 (warning) on
881 // broken pipe instead of whatever raise(SIGPIPE)
882 // would make it return. It is there to hide "Broken
883 // pipe" message on some old shells (probably old
886 // We don't do anything special with --quiet, which
887 // is what bzip2 does too. If we get SIGPIPE, we
888 // will handle it like other signals by setting
889 // user_abort, and get EPIPE here.
891 message_error(_("%s: Write error: %s"),
892 pair->dest_name, strerror(errno));
897 buf += (size_t)(amount);
898 size -= (size_t)(amount);
906 io_write(file_pair *pair, const io_buf *buf, size_t size)
908 assert(size <= IO_BUFFER_SIZE);
910 if (pair->dest_try_sparse) {
911 // Check if the block is sparse (contains only zeros). If it
912 // sparse, we just store the amount and return. We will take
913 // care of actually skipping over the hole when we hit the
914 // next data block or close the file.
916 // Since io_close() requires that dest_pending_sparse > 0
917 // if the file ends with sparse block, we must also return
918 // if size == 0 to avoid doing the lseek().
919 if (size == IO_BUFFER_SIZE) {
920 if (is_sparse(buf)) {
921 pair->dest_pending_sparse += size;
924 } else if (size == 0) {
928 // This is not a sparse block. If we have a pending hole,
930 if (pair->dest_pending_sparse > 0) {
931 if (lseek(pair->dest_fd, pair->dest_pending_sparse,
933 message_error(_("%s: Seeking failed when "
934 "trying to create a sparse "
935 "file: %s"), pair->dest_name,
940 pair->dest_pending_sparse = 0;
944 return io_write_buf(pair, buf->u8, size);