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)
31 /// \brief Unlinks a file
33 /// This tries to verify that the file being unlinked really is the file that
34 /// we want to unlink by verifying device and inode numbers. There's still
35 /// a small unavoidable race, but this is much better than nothing (the file
36 /// could have been moved/replaced even hours earlier).
38 io_unlink(const char *name, const struct stat *known_st)
42 if (lstat(name, &new_st)
43 || new_st.st_dev != known_st->st_dev
44 || new_st.st_ino != known_st->st_ino) {
45 message_error(_("%s: File seems to be moved, not removing"),
48 // There's a race condition between lstat() and unlink()
49 // but at least we have tried to avoid removing wrong file.
51 message_error(_("%s: Cannot remove: %s"),
52 name, strerror(errno));
59 /// \brief Copies owner/group and permissions
61 /// \todo ACL and EA support
64 io_copy_attrs(const file_pair *pair)
66 // This function is more tricky than you may think at first.
67 // Blindly copying permissions may permit users to access the
68 // destination file who didn't have permission to access the
71 // Simple cache to avoid repeated calls to geteuid().
76 } warn_fchown = WARN_FCHOWN_UNKNOWN;
78 // Try changing the owner of the file. If we aren't root or the owner
79 // isn't already us, fchown() probably doesn't succeed. We warn
80 // about failing fchown() only if we are root.
81 if (fchown(pair->dest_fd, pair->src_st.st_uid, -1)
82 && warn_fchown != WARN_FCHOWN_NO) {
83 if (warn_fchown == WARN_FCHOWN_UNKNOWN)
84 warn_fchown = geteuid() == 0
85 ? WARN_FCHOWN_YES : WARN_FCHOWN_NO;
87 if (warn_fchown == WARN_FCHOWN_YES)
88 message_warning(_("%s: Cannot set the file owner: %s"),
89 pair->dest_name, strerror(errno));
94 if (fchown(pair->dest_fd, -1, pair->src_st.st_gid)) {
95 message_warning(_("%s: Cannot set the file group: %s"),
96 pair->dest_name, strerror(errno));
97 // We can still safely copy some additional permissions:
98 // `group' must be at least as strict as `other' and
101 // NOTE: After this, the owner of the source file may
102 // get additional permissions. This shouldn't be too bad,
103 // because the owner would have had permission to chmod
104 // the original file anyway.
105 mode = ((pair->src_st.st_mode & 0070) >> 3)
106 & (pair->src_st.st_mode & 0007);
107 mode = (pair->src_st.st_mode & 0700) | (mode << 3) | mode;
109 // Drop the setuid, setgid, and sticky bits.
110 mode = pair->src_st.st_mode & 0777;
113 if (fchmod(pair->dest_fd, mode))
114 message_warning(_("%s: Cannot set the file permissions: %s"),
115 pair->dest_name, strerror(errno));
117 // Copy the timestamps. We have several possible ways to do this, of
118 // which some are better in both security and precision.
120 // First, get the nanosecond part of the timestamps. As of writing,
121 // it's not standardized by POSIX, and there are several names for
122 // the same thing in struct stat.
126 # if defined(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
128 atime_nsec = pair->src_st.st_atim.tv_nsec;
129 mtime_nsec = pair->src_st.st_mtim.tv_nsec;
131 # elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
133 atime_nsec = pair->src_st.st_atimespec.tv_nsec;
134 mtime_nsec = pair->src_st.st_mtimespec.tv_nsec;
136 # elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC)
137 // GNU and BSD without extensions
138 atime_nsec = pair->src_st.st_atimensec;
139 mtime_nsec = pair->src_st.st_mtimensec;
141 # elif defined(HAVE_STRUCT_STAT_ST_UATIME)
143 atime_nsec = pair->src_st.st_uatime * 1000;
144 mtime_nsec = pair->src_st.st_umtime * 1000;
146 # elif defined(HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC)
148 atime_nsec = pair->src_st.st_atim.st__tim.tv_nsec;
149 mtime_nsec = pair->src_st.st_mtim.st__tim.tv_nsec;
157 // Construct a structure to hold the timestamps and call appropriate
158 // function to set the timestamps.
159 #if defined(HAVE_FUTIMENS)
160 // Use nanosecond precision.
161 struct timespec tv[2];
162 tv[0].tv_sec = pair->src_st.st_atime;
163 tv[0].tv_nsec = atime_nsec;
164 tv[1].tv_sec = pair->src_st.st_mtime;
165 tv[1].tv_nsec = mtime_nsec;
167 (void)futimens(pair->dest_fd, tv);
169 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
170 // Use microsecond precision.
171 struct timeval tv[2];
172 tv[0].tv_sec = pair->src_st.st_atime;
173 tv[0].tv_usec = atime_nsec / 1000;
174 tv[1].tv_sec = pair->src_st.st_mtime;
175 tv[1].tv_usec = mtime_nsec / 1000;
177 # if defined(HAVE_FUTIMES)
178 (void)futimes(pair->dest_fd, tv);
179 # elif defined(HAVE_FUTIMESAT)
180 (void)futimesat(pair->dest_fd, NULL, tv);
182 // Argh, no function to use a file descriptor to set the timestamp.
183 (void)utimes(pair->src_name, tv);
186 #elif defined(HAVE_UTIME)
187 // Use one-second precision. utime() doesn't support using file
188 // descriptor either.
189 const struct utimbuf buf = {
190 .actime = pair->src_st.st_atime;
191 .modtime = pair->src_st.st_mtime;
198 (void)utime(pair->src_name, &buf);
205 /// Opens the source file. Returns false on success, true on error.
207 io_open_src(file_pair *pair)
209 // There's nothing to open when reading from stdin.
210 if (pair->src_name == stdin_filename) {
211 pair->src_fd = STDIN_FILENO;
215 // We accept only regular files if we are writing the output
216 // to disk too, and if --force was not given.
217 const bool reg_files_only = !opt_stdout && !opt_force;
220 int flags = O_RDONLY | O_NOCTTY;
222 // If we accept only regular files, we need to be careful to avoid
223 // problems with special files like devices and FIFOs. O_NONBLOCK
224 // prevents blocking when opening such files. When we want to accept
225 // special files, we must not use O_NONBLOCK, or otherwise we won't
226 // block waiting e.g. FIFOs to become readable.
234 // Some POSIX-like systems lack O_NOFOLLOW (it's not required
235 // by POSIX). Check for symlinks with a separate lstat() on
237 if (reg_files_only) {
239 if (lstat(pair->src_name, &st)) {
240 message_error("%s: %s", pair->src_name,
244 } else if (S_ISLNK(st.st_mode)) {
245 message_warning(_("%s: Is a symbolic link, "
246 "skipping"), pair->src_name);
252 // Try to open the file. If we are accepting non-regular files,
253 // unblock the caught signals so that open() can be interrupted
254 // if it blocks e.g. due to a FIFO file.
258 // Maybe this wouldn't need a loop, since all the signal handlers for
259 // which we don't use SA_RESTART set user_abort to true. But it
260 // doesn't hurt to have it just in case.
262 pair->src_fd = open(pair->src_name, flags);
263 } while (pair->src_fd == -1 && errno == EINTR && !user_abort);
268 if (pair->src_fd == -1) {
269 // If we were interrupted, don't display any error message.
270 if (errno == EINTR) {
271 // All the signals that don't have SA_RESTART
278 // Give an understandable error message in if reason
279 // for failing was that the file was a symbolic link.
281 // Note that at least Linux, OpenBSD, Solaris, and Darwin
282 // use ELOOP to indicate if O_NOFOLLOW was the reason
283 // that open() failed. Because there may be
284 // directories in the pathname, ELOOP may occur also
285 // because of a symlink loop in the directory part.
286 // So ELOOP doesn't tell us what actually went wrong.
288 // FreeBSD associates EMLINK with O_NOFOLLOW and
289 // Tru64 uses ENOTSUP. We use these directly here
290 // and skip the lstat() call and the associated race.
291 // I want to hear if there are other kernels that
292 // fail with something else than ELOOP with O_NOFOLLOW.
293 bool was_symlink = false;
295 # if defined(__FreeBSD__) || defined(__DragonFly__)
299 # elif defined(__digital__) && defined(__unix__)
300 if (errno == ENOTSUP)
304 if (errno == ELOOP && reg_files_only) {
305 const int saved_errno = errno;
307 if (lstat(pair->src_name, &st) == 0
308 && S_ISLNK(st.st_mode))
316 message_warning(_("%s: Is a symbolic link, "
317 "skipping"), pair->src_name);
320 // Something else than O_NOFOLLOW failing
321 // (assuming that the race conditions didn't
323 message_error("%s: %s", pair->src_name,
329 // Drop O_NONBLOCK, which is used only when we are accepting only
330 // regular files. After the open() call, we want things to block
331 // instead of giving EAGAIN.
332 if (reg_files_only) {
333 flags = fcntl(pair->src_fd, F_GETFL);
337 flags &= ~O_NONBLOCK;
339 if (fcntl(pair->src_fd, F_SETFL, flags))
343 // Stat the source file. We need the result also when we copy
344 // the permissions, and when unlinking.
345 if (fstat(pair->src_fd, &pair->src_st))
348 if (S_ISDIR(pair->src_st.st_mode)) {
349 message_warning(_("%s: Is a directory, skipping"),
354 if (reg_files_only) {
355 if (!S_ISREG(pair->src_st.st_mode)) {
356 message_warning(_("%s: Not a regular file, "
357 "skipping"), pair->src_name);
361 if (pair->src_st.st_mode & (S_ISUID | S_ISGID)) {
362 // gzip rejects setuid and setgid files even
363 // when --force was used. bzip2 doesn't check
364 // for them, but calls fchown() after fchmod(),
365 // and many systems automatically drop setuid
366 // and setgid bits there.
368 // We accept setuid and setgid files if
369 // --force was used. We drop these bits
370 // explicitly in io_copy_attr().
371 message_warning(_("%s: File has setuid or "
372 "setgid bit set, skipping"),
377 if (pair->src_st.st_mode & S_ISVTX) {
378 message_warning(_("%s: File has sticky bit "
384 if (pair->src_st.st_nlink > 1) {
385 message_warning(_("%s: Input file has more "
386 "than one hard link, "
387 "skipping"), pair->src_name);
395 message_error("%s: %s", pair->src_name, strerror(errno));
397 (void)close(pair->src_fd);
402 /// \brief Closes source file of the file_pair structure
404 /// \param pair File whose src_fd should be closed
405 /// \param success If true, the file will be removed from the disk if
406 /// closing succeeds and --keep hasn't been used.
408 io_close_src(file_pair *pair, bool success)
410 if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) {
411 // If we are going to unlink(), do it before closing the file.
412 // This way there's no risk that someone replaces the file and
413 // happens to get same inode number, which would make us
414 // unlink() wrong file.
415 if (success && !opt_keep_original)
416 io_unlink(pair->src_name, &pair->src_st);
418 (void)close(pair->src_fd);
426 io_open_dest(file_pair *pair)
428 if (opt_stdout || pair->src_fd == STDIN_FILENO) {
429 // We don't modify or free() this.
430 pair->dest_name = (char *)"(stdout)";
431 pair->dest_fd = STDOUT_FILENO;
435 pair->dest_name = suffix_get_dest_name(pair->src_name);
436 if (pair->dest_name == NULL)
439 // If --force was used, unlink the target file first.
440 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
441 message_error("%s: Cannot unlink: %s",
442 pair->dest_name, strerror(errno));
443 free(pair->dest_name);
447 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
448 message_error("%s: Cannot unlink: %s", pair->dest_name,
450 free(pair->dest_name);
455 const int flags = O_WRONLY | O_NOCTTY | O_CREAT | O_EXCL;
456 const mode_t mode = S_IRUSR | S_IWUSR;
457 pair->dest_fd = open(pair->dest_name, flags, mode);
459 if (pair->dest_fd == -1) {
460 // Don't bother with error message if user requested
461 // us to exit anyway.
463 message_error("%s: %s", pair->dest_name,
466 free(pair->dest_name);
470 // If this really fails... well, we have a safe fallback.
471 if (fstat(pair->dest_fd, &pair->dest_st)) {
472 pair->dest_st.st_dev = 0;
473 pair->dest_st.st_ino = 0;
480 /// \brief Closes destination file of the file_pair structure
482 /// \param pair File whose dest_fd should be closed
483 /// \param success If false, the file will be removed from the disk.
485 /// \return Zero if closing succeeds. On error, -1 is returned and
486 /// error message printed.
488 io_close_dest(file_pair *pair, bool success)
490 if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
493 if (close(pair->dest_fd)) {
494 message_error(_("%s: Closing the file failed: %s"),
495 pair->dest_name, strerror(errno));
497 // Closing destination file failed, so we cannot trust its
498 // contents. Get rid of junk:
499 io_unlink(pair->dest_name, &pair->dest_st);
500 free(pair->dest_name);
504 // If the operation using this file wasn't successful, we git rid
507 io_unlink(pair->dest_name, &pair->dest_st);
509 free(pair->dest_name);
516 io_open(const char *src_name)
518 if (is_empty_filename(src_name))
521 // Since we have only one file open at a time, we can use
522 // a statically allocated structure.
523 static file_pair pair;
526 .src_name = src_name,
533 // Block the signals, for which we have a custom signal handler, so
534 // that we don't need to worry about EINTR.
537 file_pair *ret = NULL;
538 if (!io_open_src(&pair)) {
539 // io_open_src() may have unblocked the signals temporarily,
540 // and thus user_abort may have got set even if open()
542 if (user_abort || io_open_dest(&pair))
543 io_close_src(&pair, false);
555 io_close(file_pair *pair, bool success)
559 if (success && pair->dest_fd != STDOUT_FILENO)
562 // Close the destination first. If it fails, we must not remove
564 if (io_close_dest(pair, success))
567 // Close the source file, and unlink it if the operation using this
568 // file pair was successful and we haven't requested to keep the
570 io_close_src(pair, success);
579 io_read(file_pair *pair, uint8_t *buf, size_t size)
581 // We use small buffers here.
582 assert(size < SSIZE_MAX);
587 const ssize_t amount = read(pair->src_fd, buf, left);
590 pair->src_eof = true;
595 if (errno == EINTR) {
602 message_error(_("%s: Read error: %s"),
603 pair->src_name, strerror(errno));
605 // FIXME Is this needed?
606 pair->src_eof = true;
611 buf += (size_t)(amount);
612 left -= (size_t)(amount);
620 io_write(const file_pair *pair, const uint8_t *buf, size_t size)
622 assert(size < SSIZE_MAX);
625 const ssize_t amount = write(pair->dest_fd, buf, size);
627 if (errno == EINTR) {
634 // Handle broken pipe specially. gzip and bzip2
635 // don't print anything on SIGPIPE. In addition,
636 // gzip --quiet uses exit status 2 (warning) on
637 // broken pipe instead of whatever raise(SIGPIPE)
638 // would make it return. It is there to hide "Broken
639 // pipe" message on some old shells (probably old
642 // We don't do anything special with --quiet, which
643 // is what bzip2 does too. If we get SIGPIPE, we
644 // will handle it like other signals by setting
645 // user_abort, and get EPIPE here.
647 message_error(_("%s: Write error: %s"),
648 pair->dest_name, strerror(errno));
653 buf += (size_t)(amount);
654 size -= (size_t)(amount);