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 ///////////////////////////////////////////////////////////////////////////////
21 #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
22 # include <sys/time.h>
23 #elif defined(HAVE_UTIME)
36 # include "open_stdxxx.h"
37 static bool warn_fchown;
45 // Make sure that stdin, stdout, and and stderr are connected to
46 // a valid file descriptor. Exit immediatelly with exit code ERROR
47 // if we cannot make the file descriptors valid. Maybe we should
48 // print an error message, but our stderr could be screwed anyway.
51 // If fchown() fails setting the owner, we warn about it only if
53 warn_fchown = geteuid() == 0;
57 // Avoid doing useless things when statting files.
58 // This isn't important but doesn't hurt.
59 _djstat_flags = _STAT_INODE | _STAT_EXEC_EXT
60 | _STAT_EXEC_MAGIC | _STAT_DIRSIZE;
67 /// \brief Unlinks a file
69 /// This tries to verify that the file being unlinked really is the file that
70 /// we want to unlink by verifying device and inode numbers. There's still
71 /// a small unavoidable race, but this is much better than nothing (the file
72 /// could have been moved/replaced even hours earlier).
74 io_unlink(const char *name, const struct stat *known_st)
76 // On Windows, st_ino is meaningless, so don't bother testing it.
80 if (lstat(name, &new_st)
81 || new_st.st_dev != known_st->st_dev
82 || new_st.st_ino != known_st->st_ino)
83 message_error(_("%s: File seems to be moved, not removing"),
87 // There's a race condition between lstat() and unlink()
88 // but at least we have tried to avoid removing wrong file.
90 message_error(_("%s: Cannot remove: %s"),
91 name, strerror(errno));
97 /// \brief Copies owner/group and permissions
99 /// \todo ACL and EA support
102 io_copy_attrs(const file_pair *pair)
104 // Skip chown and chmod on Windows.
106 // This function is more tricky than you may think at first.
107 // Blindly copying permissions may permit users to access the
108 // destination file who didn't have permission to access the
111 // Try changing the owner of the file. If we aren't root or the owner
112 // isn't already us, fchown() probably doesn't succeed. We warn
113 // about failing fchown() only if we are root.
114 if (fchown(pair->dest_fd, pair->src_st.st_uid, -1) && warn_fchown)
115 message_warning(_("%s: Cannot set the file owner: %s"),
116 pair->dest_name, strerror(errno));
120 if (fchown(pair->dest_fd, -1, pair->src_st.st_gid)) {
121 message_warning(_("%s: Cannot set the file group: %s"),
122 pair->dest_name, strerror(errno));
123 // We can still safely copy some additional permissions:
124 // `group' must be at least as strict as `other' and
127 // NOTE: After this, the owner of the source file may
128 // get additional permissions. This shouldn't be too bad,
129 // because the owner would have had permission to chmod
130 // the original file anyway.
131 mode = ((pair->src_st.st_mode & 0070) >> 3)
132 & (pair->src_st.st_mode & 0007);
133 mode = (pair->src_st.st_mode & 0700) | (mode << 3) | mode;
135 // Drop the setuid, setgid, and sticky bits.
136 mode = pair->src_st.st_mode & 0777;
139 if (fchmod(pair->dest_fd, mode))
140 message_warning(_("%s: Cannot set the file permissions: %s"),
141 pair->dest_name, strerror(errno));
144 // Copy the timestamps. We have several possible ways to do this, of
145 // which some are better in both security and precision.
147 // First, get the nanosecond part of the timestamps. As of writing,
148 // it's not standardized by POSIX, and there are several names for
149 // the same thing in struct stat.
153 # if defined(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
155 atime_nsec = pair->src_st.st_atim.tv_nsec;
156 mtime_nsec = pair->src_st.st_mtim.tv_nsec;
158 # elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
160 atime_nsec = pair->src_st.st_atimespec.tv_nsec;
161 mtime_nsec = pair->src_st.st_mtimespec.tv_nsec;
163 # elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC)
164 // GNU and BSD without extensions
165 atime_nsec = pair->src_st.st_atimensec;
166 mtime_nsec = pair->src_st.st_mtimensec;
168 # elif defined(HAVE_STRUCT_STAT_ST_UATIME)
170 atime_nsec = pair->src_st.st_uatime * 1000;
171 mtime_nsec = pair->src_st.st_umtime * 1000;
173 # elif defined(HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC)
175 atime_nsec = pair->src_st.st_atim.st__tim.tv_nsec;
176 mtime_nsec = pair->src_st.st_mtim.st__tim.tv_nsec;
184 // Construct a structure to hold the timestamps and call appropriate
185 // function to set the timestamps.
186 #if defined(HAVE_FUTIMENS)
187 // Use nanosecond precision.
188 struct timespec tv[2];
189 tv[0].tv_sec = pair->src_st.st_atime;
190 tv[0].tv_nsec = atime_nsec;
191 tv[1].tv_sec = pair->src_st.st_mtime;
192 tv[1].tv_nsec = mtime_nsec;
194 (void)futimens(pair->dest_fd, tv);
196 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
197 // Use microsecond precision.
198 struct timeval tv[2];
199 tv[0].tv_sec = pair->src_st.st_atime;
200 tv[0].tv_usec = atime_nsec / 1000;
201 tv[1].tv_sec = pair->src_st.st_mtime;
202 tv[1].tv_usec = mtime_nsec / 1000;
204 # if defined(HAVE_FUTIMES)
205 (void)futimes(pair->dest_fd, tv);
206 # elif defined(HAVE_FUTIMESAT)
207 (void)futimesat(pair->dest_fd, NULL, tv);
209 // Argh, no function to use a file descriptor to set the timestamp.
210 (void)utimes(pair->dest_name, tv);
213 #elif defined(HAVE_UTIME)
214 // Use one-second precision. utime() doesn't support using file
215 // descriptor either. Some systems have broken utime() prototype
216 // so don't make this const.
217 struct utimbuf buf = {
218 .actime = pair->src_st.st_atime,
219 .modtime = pair->src_st.st_mtime,
226 (void)utime(pair->dest_name, &buf);
233 /// Opens the source file. Returns false on success, true on error.
235 io_open_src(file_pair *pair)
237 // There's nothing to open when reading from stdin.
238 if (pair->src_name == stdin_filename) {
239 pair->src_fd = STDIN_FILENO;
241 setmode(STDIN_FILENO, O_BINARY);
246 // We accept only regular files if we are writing the output
247 // to disk too, and if --force was not given.
248 const bool reg_files_only = !opt_stdout && !opt_force;
251 int flags = O_RDONLY | O_BINARY | O_NOCTTY;
254 // If we accept only regular files, we need to be careful to avoid
255 // problems with special files like devices and FIFOs. O_NONBLOCK
256 // prevents blocking when opening such files. When we want to accept
257 // special files, we must not use O_NONBLOCK, or otherwise we won't
258 // block waiting e.g. FIFOs to become readable.
263 #if defined(O_NOFOLLOW)
266 #elif !defined(DOSLIKE)
267 // Some POSIX-like systems lack O_NOFOLLOW (it's not required
268 // by POSIX). Check for symlinks with a separate lstat() on
270 if (reg_files_only) {
272 if (lstat(pair->src_name, &st)) {
273 message_error("%s: %s", pair->src_name,
277 } else if (S_ISLNK(st.st_mode)) {
278 message_warning(_("%s: Is a symbolic link, "
279 "skipping"), pair->src_name);
285 // Try to open the file. If we are accepting non-regular files,
286 // unblock the caught signals so that open() can be interrupted
287 // if it blocks e.g. due to a FIFO file.
291 // Maybe this wouldn't need a loop, since all the signal handlers for
292 // which we don't use SA_RESTART set user_abort to true. But it
293 // doesn't hurt to have it just in case.
295 pair->src_fd = open(pair->src_name, flags);
296 } while (pair->src_fd == -1 && errno == EINTR && !user_abort);
301 if (pair->src_fd == -1) {
302 // If we were interrupted, don't display any error message.
303 if (errno == EINTR) {
304 // All the signals that don't have SA_RESTART
311 // Give an understandable error message in if reason
312 // for failing was that the file was a symbolic link.
314 // Note that at least Linux, OpenBSD, Solaris, and Darwin
315 // use ELOOP to indicate if O_NOFOLLOW was the reason
316 // that open() failed. Because there may be
317 // directories in the pathname, ELOOP may occur also
318 // because of a symlink loop in the directory part.
319 // So ELOOP doesn't tell us what actually went wrong.
321 // FreeBSD associates EMLINK with O_NOFOLLOW and
322 // Tru64 uses ENOTSUP. We use these directly here
323 // and skip the lstat() call and the associated race.
324 // I want to hear if there are other kernels that
325 // fail with something else than ELOOP with O_NOFOLLOW.
326 bool was_symlink = false;
328 # if defined(__FreeBSD__) || defined(__DragonFly__)
332 # elif defined(__digital__) && defined(__unix__)
333 if (errno == ENOTSUP)
336 # elif defined(__NetBSD__)
337 // FIXME? As of 2008-11-20, NetBSD doesn't document what
338 // errno is used with O_NOFOLLOW. It seems to be EFTYPE,
339 // but since it isn't documented, it may be wrong to rely
345 if (errno == ELOOP && reg_files_only) {
346 const int saved_errno = errno;
348 if (lstat(pair->src_name, &st) == 0
349 && S_ISLNK(st.st_mode))
357 message_warning(_("%s: Is a symbolic link, "
358 "skipping"), pair->src_name);
361 // Something else than O_NOFOLLOW failing
362 // (assuming that the race conditions didn't
364 message_error("%s: %s", pair->src_name,
371 // Drop O_NONBLOCK, which is used only when we are accepting only
372 // regular files. After the open() call, we want things to block
373 // instead of giving EAGAIN.
374 if (reg_files_only) {
375 flags = fcntl(pair->src_fd, F_GETFL);
379 flags &= ~O_NONBLOCK;
381 if (fcntl(pair->src_fd, F_SETFL, flags))
386 // Stat the source file. We need the result also when we copy
387 // the permissions, and when unlinking.
388 if (fstat(pair->src_fd, &pair->src_st))
391 if (S_ISDIR(pair->src_st.st_mode)) {
392 message_warning(_("%s: Is a directory, skipping"),
397 if (reg_files_only) {
398 if (!S_ISREG(pair->src_st.st_mode)) {
399 message_warning(_("%s: Not a regular file, "
400 "skipping"), pair->src_name);
404 // These are meaningless on Windows.
406 if (pair->src_st.st_mode & (S_ISUID | S_ISGID)) {
407 // gzip rejects setuid and setgid files even
408 // when --force was used. bzip2 doesn't check
409 // for them, but calls fchown() after fchmod(),
410 // and many systems automatically drop setuid
411 // and setgid bits there.
413 // We accept setuid and setgid files if
414 // --force was used. We drop these bits
415 // explicitly in io_copy_attr().
416 message_warning(_("%s: File has setuid or "
417 "setgid bit set, skipping"),
422 if (pair->src_st.st_mode & S_ISVTX) {
423 message_warning(_("%s: File has sticky bit "
429 if (pair->src_st.st_nlink > 1) {
430 message_warning(_("%s: Input file has more "
431 "than one hard link, "
432 "skipping"), pair->src_name);
441 message_error("%s: %s", pair->src_name, strerror(errno));
443 (void)close(pair->src_fd);
448 /// \brief Closes source file of the file_pair structure
450 /// \param pair File whose src_fd should be closed
451 /// \param success If true, the file will be removed from the disk if
452 /// closing succeeds and --keep hasn't been used.
454 io_close_src(file_pair *pair, bool success)
456 if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) {
458 (void)close(pair->src_fd);
461 // If we are going to unlink(), do it before closing the file.
462 // This way there's no risk that someone replaces the file and
463 // happens to get same inode number, which would make us
464 // unlink() wrong file.
466 // NOTE: DOS-like systems are an exception to this, because
467 // they don't allow unlinking files that are open. *sigh*
468 if (success && !opt_keep_original)
469 io_unlink(pair->src_name, &pair->src_st);
472 (void)close(pair->src_fd);
481 io_open_dest(file_pair *pair)
483 if (opt_stdout || pair->src_fd == STDIN_FILENO) {
484 // We don't modify or free() this.
485 pair->dest_name = (char *)"(stdout)";
486 pair->dest_fd = STDOUT_FILENO;
488 setmode(STDOUT_FILENO, O_BINARY);
493 pair->dest_name = suffix_get_dest_name(pair->src_name);
494 if (pair->dest_name == NULL)
497 // If --force was used, unlink the target file first.
498 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
499 message_error("%s: Cannot unlink: %s",
500 pair->dest_name, strerror(errno));
501 free(pair->dest_name);
505 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
506 message_error("%s: Cannot unlink: %s", pair->dest_name,
508 free(pair->dest_name);
513 const int flags = O_WRONLY | O_BINARY | O_NOCTTY | O_CREAT | O_EXCL;
514 const mode_t mode = S_IRUSR | S_IWUSR;
515 pair->dest_fd = open(pair->dest_name, flags, mode);
517 if (pair->dest_fd == -1) {
518 // Don't bother with error message if user requested
519 // us to exit anyway.
521 message_error("%s: %s", pair->dest_name,
524 free(pair->dest_name);
528 // If this really fails... well, we have a safe fallback.
529 if (fstat(pair->dest_fd, &pair->dest_st)) {
530 pair->dest_st.st_dev = 0;
531 pair->dest_st.st_ino = 0;
538 /// \brief Closes destination file of the file_pair structure
540 /// \param pair File whose dest_fd should be closed
541 /// \param success If false, the file will be removed from the disk.
543 /// \return Zero if closing succeeds. On error, -1 is returned and
544 /// error message printed.
546 io_close_dest(file_pair *pair, bool success)
548 if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
551 if (close(pair->dest_fd)) {
552 message_error(_("%s: Closing the file failed: %s"),
553 pair->dest_name, strerror(errno));
555 // Closing destination file failed, so we cannot trust its
556 // contents. Get rid of junk:
557 io_unlink(pair->dest_name, &pair->dest_st);
558 free(pair->dest_name);
562 // If the operation using this file wasn't successful, we git rid
565 io_unlink(pair->dest_name, &pair->dest_st);
567 free(pair->dest_name);
574 io_open(const char *src_name)
576 if (is_empty_filename(src_name))
579 // Since we have only one file open at a time, we can use
580 // a statically allocated structure.
581 static file_pair pair;
584 .src_name = src_name,
591 // Block the signals, for which we have a custom signal handler, so
592 // that we don't need to worry about EINTR.
595 file_pair *ret = NULL;
596 if (!io_open_src(&pair)) {
597 // io_open_src() may have unblocked the signals temporarily,
598 // and thus user_abort may have got set even if open()
600 if (user_abort || io_open_dest(&pair))
601 io_close_src(&pair, false);
613 io_close(file_pair *pair, bool success)
617 if (success && pair->dest_fd != STDOUT_FILENO)
620 // Close the destination first. If it fails, we must not remove
622 if (io_close_dest(pair, success))
625 // Close the source file, and unlink it if the operation using this
626 // file pair was successful and we haven't requested to keep the
628 io_close_src(pair, success);
637 io_read(file_pair *pair, uint8_t *buf, size_t size)
639 // We use small buffers here.
640 assert(size < SSIZE_MAX);
645 const ssize_t amount = read(pair->src_fd, buf, left);
648 pair->src_eof = true;
653 if (errno == EINTR) {
660 message_error(_("%s: Read error: %s"),
661 pair->src_name, strerror(errno));
663 // FIXME Is this needed?
664 pair->src_eof = true;
669 buf += (size_t)(amount);
670 left -= (size_t)(amount);
678 io_write(const file_pair *pair, const uint8_t *buf, size_t size)
680 assert(size < SSIZE_MAX);
683 const ssize_t amount = write(pair->dest_fd, buf, size);
685 if (errno == EINTR) {
692 // Handle broken pipe specially. gzip and bzip2
693 // don't print anything on SIGPIPE. In addition,
694 // gzip --quiet uses exit status 2 (warning) on
695 // broken pipe instead of whatever raise(SIGPIPE)
696 // would make it return. It is there to hide "Broken
697 // pipe" message on some old shells (probably old
700 // We don't do anything special with --quiet, which
701 // is what bzip2 does too. If we get SIGPIPE, we
702 // will handle it like other signals by setting
703 // user_abort, and get EPIPE here.
705 message_error(_("%s: Write error: %s"),
706 pair->dest_name, strerror(errno));
711 buf += (size_t)(amount);
712 size -= (size_t)(amount);