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->dest_name, tv);
186 #elif defined(HAVE_UTIME)
187 // Use one-second precision. utime() doesn't support using file
188 // descriptor either. Some systems have broken utime() prototype
189 // so don't make this const.
190 struct utimbuf buf = {
191 .actime = pair->src_st.st_atime,
192 .modtime = pair->src_st.st_mtime,
199 (void)utime(pair->dest_name, &buf);
206 /// Opens the source file. Returns false on success, true on error.
208 io_open_src(file_pair *pair)
210 // There's nothing to open when reading from stdin.
211 if (pair->src_name == stdin_filename) {
212 pair->src_fd = STDIN_FILENO;
216 // We accept only regular files if we are writing the output
217 // to disk too, and if --force was not given.
218 const bool reg_files_only = !opt_stdout && !opt_force;
221 int flags = O_RDONLY | O_NOCTTY;
223 // If we accept only regular files, we need to be careful to avoid
224 // problems with special files like devices and FIFOs. O_NONBLOCK
225 // prevents blocking when opening such files. When we want to accept
226 // special files, we must not use O_NONBLOCK, or otherwise we won't
227 // block waiting e.g. FIFOs to become readable.
235 // Some POSIX-like systems lack O_NOFOLLOW (it's not required
236 // by POSIX). Check for symlinks with a separate lstat() on
238 if (reg_files_only) {
240 if (lstat(pair->src_name, &st)) {
241 message_error("%s: %s", pair->src_name,
245 } else if (S_ISLNK(st.st_mode)) {
246 message_warning(_("%s: Is a symbolic link, "
247 "skipping"), pair->src_name);
253 // Try to open the file. If we are accepting non-regular files,
254 // unblock the caught signals so that open() can be interrupted
255 // if it blocks e.g. due to a FIFO file.
259 // Maybe this wouldn't need a loop, since all the signal handlers for
260 // which we don't use SA_RESTART set user_abort to true. But it
261 // doesn't hurt to have it just in case.
263 pair->src_fd = open(pair->src_name, flags);
264 } while (pair->src_fd == -1 && errno == EINTR && !user_abort);
269 if (pair->src_fd == -1) {
270 // If we were interrupted, don't display any error message.
271 if (errno == EINTR) {
272 // All the signals that don't have SA_RESTART
279 // Give an understandable error message in if reason
280 // for failing was that the file was a symbolic link.
282 // Note that at least Linux, OpenBSD, Solaris, and Darwin
283 // use ELOOP to indicate if O_NOFOLLOW was the reason
284 // that open() failed. Because there may be
285 // directories in the pathname, ELOOP may occur also
286 // because of a symlink loop in the directory part.
287 // So ELOOP doesn't tell us what actually went wrong.
289 // FreeBSD associates EMLINK with O_NOFOLLOW and
290 // Tru64 uses ENOTSUP. We use these directly here
291 // and skip the lstat() call and the associated race.
292 // I want to hear if there are other kernels that
293 // fail with something else than ELOOP with O_NOFOLLOW.
294 bool was_symlink = false;
296 # if defined(__FreeBSD__) || defined(__DragonFly__)
300 # elif defined(__digital__) && defined(__unix__)
301 if (errno == ENOTSUP)
304 # elif defined(__NetBSD__)
305 // FIXME? As of 2008-11-20, NetBSD doesn't document what
306 // errno is used with O_NOFOLLOW. It seems to be EFTYPE,
307 // but since it isn't documented, it may be wrong to rely
313 if (errno == ELOOP && reg_files_only) {
314 const int saved_errno = errno;
316 if (lstat(pair->src_name, &st) == 0
317 && S_ISLNK(st.st_mode))
325 message_warning(_("%s: Is a symbolic link, "
326 "skipping"), pair->src_name);
329 // Something else than O_NOFOLLOW failing
330 // (assuming that the race conditions didn't
332 message_error("%s: %s", pair->src_name,
338 // Drop O_NONBLOCK, which is used only when we are accepting only
339 // regular files. After the open() call, we want things to block
340 // instead of giving EAGAIN.
341 if (reg_files_only) {
342 flags = fcntl(pair->src_fd, F_GETFL);
346 flags &= ~O_NONBLOCK;
348 if (fcntl(pair->src_fd, F_SETFL, flags))
352 // Stat the source file. We need the result also when we copy
353 // the permissions, and when unlinking.
354 if (fstat(pair->src_fd, &pair->src_st))
357 if (S_ISDIR(pair->src_st.st_mode)) {
358 message_warning(_("%s: Is a directory, skipping"),
363 if (reg_files_only) {
364 if (!S_ISREG(pair->src_st.st_mode)) {
365 message_warning(_("%s: Not a regular file, "
366 "skipping"), pair->src_name);
370 if (pair->src_st.st_mode & (S_ISUID | S_ISGID)) {
371 // gzip rejects setuid and setgid files even
372 // when --force was used. bzip2 doesn't check
373 // for them, but calls fchown() after fchmod(),
374 // and many systems automatically drop setuid
375 // and setgid bits there.
377 // We accept setuid and setgid files if
378 // --force was used. We drop these bits
379 // explicitly in io_copy_attr().
380 message_warning(_("%s: File has setuid or "
381 "setgid bit set, skipping"),
386 if (pair->src_st.st_mode & S_ISVTX) {
387 message_warning(_("%s: File has sticky bit "
393 if (pair->src_st.st_nlink > 1) {
394 message_warning(_("%s: Input file has more "
395 "than one hard link, "
396 "skipping"), pair->src_name);
404 message_error("%s: %s", pair->src_name, strerror(errno));
406 (void)close(pair->src_fd);
411 /// \brief Closes source file of the file_pair structure
413 /// \param pair File whose src_fd should be closed
414 /// \param success If true, the file will be removed from the disk if
415 /// closing succeeds and --keep hasn't been used.
417 io_close_src(file_pair *pair, bool success)
419 if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) {
420 // If we are going to unlink(), do it before closing the file.
421 // This way there's no risk that someone replaces the file and
422 // happens to get same inode number, which would make us
423 // unlink() wrong file.
424 if (success && !opt_keep_original)
425 io_unlink(pair->src_name, &pair->src_st);
427 (void)close(pair->src_fd);
435 io_open_dest(file_pair *pair)
437 if (opt_stdout || pair->src_fd == STDIN_FILENO) {
438 // We don't modify or free() this.
439 pair->dest_name = (char *)"(stdout)";
440 pair->dest_fd = STDOUT_FILENO;
444 pair->dest_name = suffix_get_dest_name(pair->src_name);
445 if (pair->dest_name == NULL)
448 // If --force was used, unlink the target file first.
449 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
450 message_error("%s: Cannot unlink: %s",
451 pair->dest_name, strerror(errno));
452 free(pair->dest_name);
456 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
457 message_error("%s: Cannot unlink: %s", pair->dest_name,
459 free(pair->dest_name);
464 const int flags = O_WRONLY | O_NOCTTY | O_CREAT | O_EXCL;
465 const mode_t mode = S_IRUSR | S_IWUSR;
466 pair->dest_fd = open(pair->dest_name, flags, mode);
468 if (pair->dest_fd == -1) {
469 // Don't bother with error message if user requested
470 // us to exit anyway.
472 message_error("%s: %s", pair->dest_name,
475 free(pair->dest_name);
479 // If this really fails... well, we have a safe fallback.
480 if (fstat(pair->dest_fd, &pair->dest_st)) {
481 pair->dest_st.st_dev = 0;
482 pair->dest_st.st_ino = 0;
489 /// \brief Closes destination file of the file_pair structure
491 /// \param pair File whose dest_fd should be closed
492 /// \param success If false, the file will be removed from the disk.
494 /// \return Zero if closing succeeds. On error, -1 is returned and
495 /// error message printed.
497 io_close_dest(file_pair *pair, bool success)
499 if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
502 if (close(pair->dest_fd)) {
503 message_error(_("%s: Closing the file failed: %s"),
504 pair->dest_name, strerror(errno));
506 // Closing destination file failed, so we cannot trust its
507 // contents. Get rid of junk:
508 io_unlink(pair->dest_name, &pair->dest_st);
509 free(pair->dest_name);
513 // If the operation using this file wasn't successful, we git rid
516 io_unlink(pair->dest_name, &pair->dest_st);
518 free(pair->dest_name);
525 io_open(const char *src_name)
527 if (is_empty_filename(src_name))
530 // Since we have only one file open at a time, we can use
531 // a statically allocated structure.
532 static file_pair pair;
535 .src_name = src_name,
542 // Block the signals, for which we have a custom signal handler, so
543 // that we don't need to worry about EINTR.
546 file_pair *ret = NULL;
547 if (!io_open_src(&pair)) {
548 // io_open_src() may have unblocked the signals temporarily,
549 // and thus user_abort may have got set even if open()
551 if (user_abort || io_open_dest(&pair))
552 io_close_src(&pair, false);
564 io_close(file_pair *pair, bool success)
568 if (success && pair->dest_fd != STDOUT_FILENO)
571 // Close the destination first. If it fails, we must not remove
573 if (io_close_dest(pair, success))
576 // Close the source file, and unlink it if the operation using this
577 // file pair was successful and we haven't requested to keep the
579 io_close_src(pair, success);
588 io_read(file_pair *pair, uint8_t *buf, size_t size)
590 // We use small buffers here.
591 assert(size < SSIZE_MAX);
596 const ssize_t amount = read(pair->src_fd, buf, left);
599 pair->src_eof = true;
604 if (errno == EINTR) {
611 message_error(_("%s: Read error: %s"),
612 pair->src_name, strerror(errno));
614 // FIXME Is this needed?
615 pair->src_eof = true;
620 buf += (size_t)(amount);
621 left -= (size_t)(amount);
629 io_write(const file_pair *pair, const uint8_t *buf, size_t size)
631 assert(size < SSIZE_MAX);
634 const ssize_t amount = write(pair->dest_fd, buf, size);
636 if (errno == EINTR) {
643 // Handle broken pipe specially. gzip and bzip2
644 // don't print anything on SIGPIPE. In addition,
645 // gzip --quiet uses exit status 2 (warning) on
646 // broken pipe instead of whatever raise(SIGPIPE)
647 // would make it return. It is there to hide "Broken
648 // pipe" message on some old shells (probably old
651 // We don't do anything special with --quiet, which
652 // is what bzip2 does too. If we get SIGPIPE, we
653 // will handle it like other signals by setting
654 // user_abort, and get EPIPE here.
656 message_error(_("%s: Write error: %s"),
657 pair->dest_name, strerror(errno));
662 buf += (size_t)(amount);
663 size -= (size_t)(amount);