1 ///////////////////////////////////////////////////////////////////////////////
4 /// \brief File opening, unlinking, and closing
6 // Copyright (C) 2007 Lasse Collin
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU Lesser General Public
10 // License as published by the Free Software Foundation; either
11 // version 2.1 of the License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // Lesser General Public License for more details.
18 ///////////////////////////////////////////////////////////////////////////////
24 #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
25 # include <sys/time.h>
26 #elif defined(HAVE_UTIME)
39 # include "open_stdxxx.h"
40 static bool warn_fchown;
48 // Make sure that stdin, stdout, and and stderr are connected to
49 // a valid file descriptor. Exit immediatelly with exit code ERROR
50 // if we cannot make the file descriptors valid. Maybe we should
51 // print an error message, but our stderr could be screwed anyway.
54 // If fchown() fails setting the owner, we warn about it only if
56 warn_fchown = geteuid() == 0;
63 /// \brief Unlinks a file
65 /// This tries to verify that the file being unlinked really is the file that
66 /// we want to unlink by verifying device and inode numbers. There's still
67 /// a small unavoidable race, but this is much better than nothing (the file
68 /// could have been moved/replaced even hours earlier).
70 io_unlink(const char *name, const struct stat *known_st)
72 // On Windows, st_ino is meaningless, so don't bother testing it.
76 if (lstat(name, &new_st)
77 || new_st.st_dev != known_st->st_dev
78 || new_st.st_ino != known_st->st_ino)
79 message_error(_("%s: File seems to be moved, not removing"),
83 // There's a race condition between lstat() and unlink()
84 // but at least we have tried to avoid removing wrong file.
86 message_error(_("%s: Cannot remove: %s"),
87 name, strerror(errno));
93 /// \brief Copies owner/group and permissions
95 /// \todo ACL and EA support
98 io_copy_attrs(const file_pair *pair)
100 // Skip chown and chmod on Windows.
102 // This function is more tricky than you may think at first.
103 // Blindly copying permissions may permit users to access the
104 // destination file who didn't have permission to access the
107 // Try changing the owner of the file. If we aren't root or the owner
108 // isn't already us, fchown() probably doesn't succeed. We warn
109 // about failing fchown() only if we are root.
110 if (fchown(pair->dest_fd, pair->src_st.st_uid, -1) && warn_fchown)
111 message_warning(_("%s: Cannot set the file owner: %s"),
112 pair->dest_name, strerror(errno));
116 if (fchown(pair->dest_fd, -1, pair->src_st.st_gid)) {
117 message_warning(_("%s: Cannot set the file group: %s"),
118 pair->dest_name, strerror(errno));
119 // We can still safely copy some additional permissions:
120 // `group' must be at least as strict as `other' and
123 // NOTE: After this, the owner of the source file may
124 // get additional permissions. This shouldn't be too bad,
125 // because the owner would have had permission to chmod
126 // the original file anyway.
127 mode = ((pair->src_st.st_mode & 0070) >> 3)
128 & (pair->src_st.st_mode & 0007);
129 mode = (pair->src_st.st_mode & 0700) | (mode << 3) | mode;
131 // Drop the setuid, setgid, and sticky bits.
132 mode = pair->src_st.st_mode & 0777;
135 if (fchmod(pair->dest_fd, mode))
136 message_warning(_("%s: Cannot set the file permissions: %s"),
137 pair->dest_name, strerror(errno));
140 // Copy the timestamps. We have several possible ways to do this, of
141 // which some are better in both security and precision.
143 // First, get the nanosecond part of the timestamps. As of writing,
144 // it's not standardized by POSIX, and there are several names for
145 // the same thing in struct stat.
149 # if defined(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
151 atime_nsec = pair->src_st.st_atim.tv_nsec;
152 mtime_nsec = pair->src_st.st_mtim.tv_nsec;
154 # elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
156 atime_nsec = pair->src_st.st_atimespec.tv_nsec;
157 mtime_nsec = pair->src_st.st_mtimespec.tv_nsec;
159 # elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC)
160 // GNU and BSD without extensions
161 atime_nsec = pair->src_st.st_atimensec;
162 mtime_nsec = pair->src_st.st_mtimensec;
164 # elif defined(HAVE_STRUCT_STAT_ST_UATIME)
166 atime_nsec = pair->src_st.st_uatime * 1000;
167 mtime_nsec = pair->src_st.st_umtime * 1000;
169 # elif defined(HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC)
171 atime_nsec = pair->src_st.st_atim.st__tim.tv_nsec;
172 mtime_nsec = pair->src_st.st_mtim.st__tim.tv_nsec;
180 // Construct a structure to hold the timestamps and call appropriate
181 // function to set the timestamps.
182 #if defined(HAVE_FUTIMENS)
183 // Use nanosecond precision.
184 struct timespec tv[2];
185 tv[0].tv_sec = pair->src_st.st_atime;
186 tv[0].tv_nsec = atime_nsec;
187 tv[1].tv_sec = pair->src_st.st_mtime;
188 tv[1].tv_nsec = mtime_nsec;
190 (void)futimens(pair->dest_fd, tv);
192 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
193 // Use microsecond precision.
194 struct timeval tv[2];
195 tv[0].tv_sec = pair->src_st.st_atime;
196 tv[0].tv_usec = atime_nsec / 1000;
197 tv[1].tv_sec = pair->src_st.st_mtime;
198 tv[1].tv_usec = mtime_nsec / 1000;
200 # if defined(HAVE_FUTIMES)
201 (void)futimes(pair->dest_fd, tv);
202 # elif defined(HAVE_FUTIMESAT)
203 (void)futimesat(pair->dest_fd, NULL, tv);
205 // Argh, no function to use a file descriptor to set the timestamp.
206 (void)utimes(pair->dest_name, tv);
209 #elif defined(HAVE_UTIME)
210 // Use one-second precision. utime() doesn't support using file
211 // descriptor either. Some systems have broken utime() prototype
212 // so don't make this const.
213 struct utimbuf buf = {
214 .actime = pair->src_st.st_atime,
215 .modtime = pair->src_st.st_mtime,
222 (void)utime(pair->dest_name, &buf);
229 /// Opens the source file. Returns false on success, true on error.
231 io_open_src(file_pair *pair)
233 // There's nothing to open when reading from stdin.
234 if (pair->src_name == stdin_filename) {
235 pair->src_fd = STDIN_FILENO;
237 setmode(STDIN_FILENO, O_BINARY);
242 // We accept only regular files if we are writing the output
243 // to disk too, and if --force was not given.
244 const bool reg_files_only = !opt_stdout && !opt_force;
247 int flags = O_RDONLY | O_BINARY | O_NOCTTY;
250 // If we accept only regular files, we need to be careful to avoid
251 // problems with special files like devices and FIFOs. O_NONBLOCK
252 // prevents blocking when opening such files. When we want to accept
253 // special files, we must not use O_NONBLOCK, or otherwise we won't
254 // block waiting e.g. FIFOs to become readable.
259 #if defined(O_NOFOLLOW)
262 #elif !defined(_WIN32)
263 // Some POSIX-like systems lack O_NOFOLLOW (it's not required
264 // by POSIX). Check for symlinks with a separate lstat() on
266 if (reg_files_only) {
268 if (lstat(pair->src_name, &st)) {
269 message_error("%s: %s", pair->src_name,
273 } else if (S_ISLNK(st.st_mode)) {
274 message_warning(_("%s: Is a symbolic link, "
275 "skipping"), pair->src_name);
281 // Try to open the file. If we are accepting non-regular files,
282 // unblock the caught signals so that open() can be interrupted
283 // if it blocks e.g. due to a FIFO file.
287 // Maybe this wouldn't need a loop, since all the signal handlers for
288 // which we don't use SA_RESTART set user_abort to true. But it
289 // doesn't hurt to have it just in case.
291 pair->src_fd = open(pair->src_name, flags);
292 } while (pair->src_fd == -1 && errno == EINTR && !user_abort);
297 if (pair->src_fd == -1) {
298 // If we were interrupted, don't display any error message.
299 if (errno == EINTR) {
300 // All the signals that don't have SA_RESTART
307 // Give an understandable error message in if reason
308 // for failing was that the file was a symbolic link.
310 // Note that at least Linux, OpenBSD, Solaris, and Darwin
311 // use ELOOP to indicate if O_NOFOLLOW was the reason
312 // that open() failed. Because there may be
313 // directories in the pathname, ELOOP may occur also
314 // because of a symlink loop in the directory part.
315 // So ELOOP doesn't tell us what actually went wrong.
317 // FreeBSD associates EMLINK with O_NOFOLLOW and
318 // Tru64 uses ENOTSUP. We use these directly here
319 // and skip the lstat() call and the associated race.
320 // I want to hear if there are other kernels that
321 // fail with something else than ELOOP with O_NOFOLLOW.
322 bool was_symlink = false;
324 # if defined(__FreeBSD__) || defined(__DragonFly__)
328 # elif defined(__digital__) && defined(__unix__)
329 if (errno == ENOTSUP)
332 # elif defined(__NetBSD__)
333 // FIXME? As of 2008-11-20, NetBSD doesn't document what
334 // errno is used with O_NOFOLLOW. It seems to be EFTYPE,
335 // but since it isn't documented, it may be wrong to rely
341 if (errno == ELOOP && reg_files_only) {
342 const int saved_errno = errno;
344 if (lstat(pair->src_name, &st) == 0
345 && S_ISLNK(st.st_mode))
353 message_warning(_("%s: Is a symbolic link, "
354 "skipping"), pair->src_name);
357 // Something else than O_NOFOLLOW failing
358 // (assuming that the race conditions didn't
360 message_error("%s: %s", pair->src_name,
367 // Drop O_NONBLOCK, which is used only when we are accepting only
368 // regular files. After the open() call, we want things to block
369 // instead of giving EAGAIN.
370 if (reg_files_only) {
371 flags = fcntl(pair->src_fd, F_GETFL);
375 flags &= ~O_NONBLOCK;
377 if (fcntl(pair->src_fd, F_SETFL, flags))
382 // Stat the source file. We need the result also when we copy
383 // the permissions, and when unlinking.
384 if (fstat(pair->src_fd, &pair->src_st))
387 if (S_ISDIR(pair->src_st.st_mode)) {
388 message_warning(_("%s: Is a directory, skipping"),
393 if (reg_files_only) {
394 if (!S_ISREG(pair->src_st.st_mode)) {
395 message_warning(_("%s: Not a regular file, "
396 "skipping"), pair->src_name);
400 // These are meaningless on Windows.
402 if (pair->src_st.st_mode & (S_ISUID | S_ISGID)) {
403 // gzip rejects setuid and setgid files even
404 // when --force was used. bzip2 doesn't check
405 // for them, but calls fchown() after fchmod(),
406 // and many systems automatically drop setuid
407 // and setgid bits there.
409 // We accept setuid and setgid files if
410 // --force was used. We drop these bits
411 // explicitly in io_copy_attr().
412 message_warning(_("%s: File has setuid or "
413 "setgid bit set, skipping"),
418 if (pair->src_st.st_mode & S_ISVTX) {
419 message_warning(_("%s: File has sticky bit "
425 if (pair->src_st.st_nlink > 1) {
426 message_warning(_("%s: Input file has more "
427 "than one hard link, "
428 "skipping"), pair->src_name);
437 message_error("%s: %s", pair->src_name, strerror(errno));
439 (void)close(pair->src_fd);
444 /// \brief Closes source file of the file_pair structure
446 /// \param pair File whose src_fd should be closed
447 /// \param success If true, the file will be removed from the disk if
448 /// closing succeeds and --keep hasn't been used.
450 io_close_src(file_pair *pair, bool success)
452 if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) {
454 (void)close(pair->src_fd);
457 // If we are going to unlink(), do it before closing the file.
458 // This way there's no risk that someone replaces the file and
459 // happens to get same inode number, which would make us
460 // unlink() wrong file.
462 // NOTE: Windows is an exception to this, because it doesn't
463 // allow unlinking files that are open. *sigh*
464 if (success && !opt_keep_original)
465 io_unlink(pair->src_name, &pair->src_st);
468 (void)close(pair->src_fd);
477 io_open_dest(file_pair *pair)
479 if (opt_stdout || pair->src_fd == STDIN_FILENO) {
480 // We don't modify or free() this.
481 pair->dest_name = (char *)"(stdout)";
482 pair->dest_fd = STDOUT_FILENO;
484 setmode(STDOUT_FILENO, O_BINARY);
489 pair->dest_name = suffix_get_dest_name(pair->src_name);
490 if (pair->dest_name == NULL)
493 // If --force was used, unlink the target file first.
494 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
495 message_error("%s: Cannot unlink: %s",
496 pair->dest_name, strerror(errno));
497 free(pair->dest_name);
501 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
502 message_error("%s: Cannot unlink: %s", pair->dest_name,
504 free(pair->dest_name);
509 const int flags = O_WRONLY | O_BINARY | O_NOCTTY | O_CREAT | O_EXCL;
510 const mode_t mode = S_IRUSR | S_IWUSR;
511 pair->dest_fd = open(pair->dest_name, flags, mode);
513 if (pair->dest_fd == -1) {
514 // Don't bother with error message if user requested
515 // us to exit anyway.
517 message_error("%s: %s", pair->dest_name,
520 free(pair->dest_name);
524 // If this really fails... well, we have a safe fallback.
525 if (fstat(pair->dest_fd, &pair->dest_st)) {
526 pair->dest_st.st_dev = 0;
527 pair->dest_st.st_ino = 0;
534 /// \brief Closes destination file of the file_pair structure
536 /// \param pair File whose dest_fd should be closed
537 /// \param success If false, the file will be removed from the disk.
539 /// \return Zero if closing succeeds. On error, -1 is returned and
540 /// error message printed.
542 io_close_dest(file_pair *pair, bool success)
544 if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
547 if (close(pair->dest_fd)) {
548 message_error(_("%s: Closing the file failed: %s"),
549 pair->dest_name, strerror(errno));
551 // Closing destination file failed, so we cannot trust its
552 // contents. Get rid of junk:
553 io_unlink(pair->dest_name, &pair->dest_st);
554 free(pair->dest_name);
558 // If the operation using this file wasn't successful, we git rid
561 io_unlink(pair->dest_name, &pair->dest_st);
563 free(pair->dest_name);
570 io_open(const char *src_name)
572 if (is_empty_filename(src_name))
575 // Since we have only one file open at a time, we can use
576 // a statically allocated structure.
577 static file_pair pair;
580 .src_name = src_name,
587 // Block the signals, for which we have a custom signal handler, so
588 // that we don't need to worry about EINTR.
591 file_pair *ret = NULL;
592 if (!io_open_src(&pair)) {
593 // io_open_src() may have unblocked the signals temporarily,
594 // and thus user_abort may have got set even if open()
596 if (user_abort || io_open_dest(&pair))
597 io_close_src(&pair, false);
609 io_close(file_pair *pair, bool success)
613 if (success && pair->dest_fd != STDOUT_FILENO)
616 // Close the destination first. If it fails, we must not remove
618 if (io_close_dest(pair, success))
621 // Close the source file, and unlink it if the operation using this
622 // file pair was successful and we haven't requested to keep the
624 io_close_src(pair, success);
633 io_read(file_pair *pair, uint8_t *buf, size_t size)
635 // We use small buffers here.
636 assert(size < SSIZE_MAX);
641 const ssize_t amount = read(pair->src_fd, buf, left);
644 pair->src_eof = true;
649 if (errno == EINTR) {
656 message_error(_("%s: Read error: %s"),
657 pair->src_name, strerror(errno));
659 // FIXME Is this needed?
660 pair->src_eof = true;
665 buf += (size_t)(amount);
666 left -= (size_t)(amount);
674 io_write(const file_pair *pair, const uint8_t *buf, size_t size)
676 assert(size < SSIZE_MAX);
679 const ssize_t amount = write(pair->dest_fd, buf, size);
681 if (errno == EINTR) {
688 // Handle broken pipe specially. gzip and bzip2
689 // don't print anything on SIGPIPE. In addition,
690 // gzip --quiet uses exit status 2 (warning) on
691 // broken pipe instead of whatever raise(SIGPIPE)
692 // would make it return. It is there to hide "Broken
693 // pipe" message on some old shells (probably old
696 // We don't do anything special with --quiet, which
697 // is what bzip2 does too. If we get SIGPIPE, we
698 // will handle it like other signals by setting
699 // user_abort, and get EPIPE here.
701 message_error(_("%s: Write error: %s"),
702 pair->dest_name, strerror(errno));
707 buf += (size_t)(amount);
708 size -= (size_t)(amount);