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"
43 // Make sure that stdin, stdout, and and stderr are connected to
44 // a valid file descriptor. Exit immediatelly with exit code ERROR
45 // if we cannot make the file descriptors valid. Maybe we should
46 // print an error message, but our stderr could be screwed anyway.
47 tuklib_open_stdxxx(E_ERROR);
49 #ifndef TUKLIB_DOSLIKE
50 // If fchown() fails setting the owner, we warn about it only if
52 warn_fchown = geteuid() == 0;
56 // Avoid doing useless things when statting files.
57 // This isn't important but doesn't hurt.
58 _djstat_flags = _STAT_INODE | _STAT_EXEC_EXT
59 | _STAT_EXEC_MAGIC | _STAT_DIRSIZE;
66 /// \brief Unlink a file
68 /// This tries to verify that the file being unlinked really is the file that
69 /// we want to unlink by verifying device and inode numbers. There's still
70 /// a small unavoidable race, but this is much better than nothing (the file
71 /// could have been moved/replaced even hours earlier).
73 io_unlink(const char *name, const struct stat *known_st)
75 #if defined(TUKLIB_DOSLIKE) || defined(__VMS)
76 // On DOS-like systems, st_ino is meaningless, so don't bother
77 // testing it. Just silence a compiler warning.
82 if (lstat(name, &new_st)
83 || new_st.st_dev != known_st->st_dev
84 || new_st.st_ino != known_st->st_ino)
85 message_error(_("%s: File seems to be moved, not removing"),
89 // There's a race condition between lstat() and unlink()
90 // but at least we have tried to avoid removing wrong file.
92 message_error(_("%s: Cannot remove: %s"),
93 name, strerror(errno));
99 /// \brief Copies owner/group and permissions
101 /// \todo ACL and EA support
104 io_copy_attrs(const file_pair *pair)
106 // Skip chown and chmod on Windows.
107 #ifndef TUKLIB_DOSLIKE
108 // This function is more tricky than you may think at first.
109 // Blindly copying permissions may permit users to access the
110 // destination file who didn't have permission to access the
113 // Try changing the owner of the file. If we aren't root or the owner
114 // isn't already us, fchown() probably doesn't succeed. We warn
115 // about failing fchown() only if we are root.
116 if (fchown(pair->dest_fd, pair->src_st.st_uid, -1) && warn_fchown)
117 message_warning(_("%s: Cannot set the file owner: %s"),
118 pair->dest_name, strerror(errno));
122 if (fchown(pair->dest_fd, -1, pair->src_st.st_gid)) {
123 message_warning(_("%s: Cannot set the file group: %s"),
124 pair->dest_name, strerror(errno));
125 // We can still safely copy some additional permissions:
126 // `group' must be at least as strict as `other' and
129 // NOTE: After this, the owner of the source file may
130 // get additional permissions. This shouldn't be too bad,
131 // because the owner would have had permission to chmod
132 // the original file anyway.
133 mode = ((pair->src_st.st_mode & 0070) >> 3)
134 & (pair->src_st.st_mode & 0007);
135 mode = (pair->src_st.st_mode & 0700) | (mode << 3) | mode;
137 // Drop the setuid, setgid, and sticky bits.
138 mode = pair->src_st.st_mode & 0777;
141 if (fchmod(pair->dest_fd, mode))
142 message_warning(_("%s: Cannot set the file permissions: %s"),
143 pair->dest_name, strerror(errno));
146 // Copy the timestamps. We have several possible ways to do this, of
147 // which some are better in both security and precision.
149 // First, get the nanosecond part of the timestamps. As of writing,
150 // it's not standardized by POSIX, and there are several names for
151 // the same thing in struct stat.
155 # if defined(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
157 atime_nsec = pair->src_st.st_atim.tv_nsec;
158 mtime_nsec = pair->src_st.st_mtim.tv_nsec;
160 # elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
162 atime_nsec = pair->src_st.st_atimespec.tv_nsec;
163 mtime_nsec = pair->src_st.st_mtimespec.tv_nsec;
165 # elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC)
166 // GNU and BSD without extensions
167 atime_nsec = pair->src_st.st_atimensec;
168 mtime_nsec = pair->src_st.st_mtimensec;
170 # elif defined(HAVE_STRUCT_STAT_ST_UATIME)
172 atime_nsec = pair->src_st.st_uatime * 1000;
173 mtime_nsec = pair->src_st.st_umtime * 1000;
175 # elif defined(HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC)
177 atime_nsec = pair->src_st.st_atim.st__tim.tv_nsec;
178 mtime_nsec = pair->src_st.st_mtim.st__tim.tv_nsec;
186 // Construct a structure to hold the timestamps and call appropriate
187 // function to set the timestamps.
188 #if defined(HAVE_FUTIMENS)
189 // Use nanosecond precision.
190 struct timespec tv[2];
191 tv[0].tv_sec = pair->src_st.st_atime;
192 tv[0].tv_nsec = atime_nsec;
193 tv[1].tv_sec = pair->src_st.st_mtime;
194 tv[1].tv_nsec = mtime_nsec;
196 (void)futimens(pair->dest_fd, tv);
198 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
199 // Use microsecond precision.
200 struct timeval tv[2];
201 tv[0].tv_sec = pair->src_st.st_atime;
202 tv[0].tv_usec = atime_nsec / 1000;
203 tv[1].tv_sec = pair->src_st.st_mtime;
204 tv[1].tv_usec = mtime_nsec / 1000;
206 # if defined(HAVE_FUTIMES)
207 (void)futimes(pair->dest_fd, tv);
208 # elif defined(HAVE_FUTIMESAT)
209 (void)futimesat(pair->dest_fd, NULL, tv);
211 // Argh, no function to use a file descriptor to set the timestamp.
212 (void)utimes(pair->dest_name, tv);
215 #elif defined(HAVE_UTIME)
216 // Use one-second precision. utime() doesn't support using file
217 // descriptor either. Some systems have broken utime() prototype
218 // so don't make this const.
219 struct utimbuf buf = {
220 .actime = pair->src_st.st_atime,
221 .modtime = pair->src_st.st_mtime,
228 (void)utime(pair->dest_name, &buf);
235 /// Opens the source file. Returns false on success, true on error.
237 io_open_src(file_pair *pair)
239 // There's nothing to open when reading from stdin.
240 if (pair->src_name == stdin_filename) {
241 pair->src_fd = STDIN_FILENO;
242 #ifdef TUKLIB_DOSLIKE
243 setmode(STDIN_FILENO, O_BINARY);
248 // We accept only regular files if we are writing the output
249 // to disk too, and if --force was not given.
250 const bool reg_files_only = !opt_stdout && !opt_force;
253 int flags = O_RDONLY | O_BINARY | O_NOCTTY;
255 #ifndef TUKLIB_DOSLIKE
256 // If we accept only regular files, we need to be careful to avoid
257 // problems with special files like devices and FIFOs. O_NONBLOCK
258 // prevents blocking when opening such files. When we want to accept
259 // special files, we must not use O_NONBLOCK, or otherwise we won't
260 // block waiting e.g. FIFOs to become readable.
265 #if defined(O_NOFOLLOW)
268 #elif !defined(TUKLIB_DOSLIKE)
269 // Some POSIX-like systems lack O_NOFOLLOW (it's not required
270 // by POSIX). Check for symlinks with a separate lstat() on
272 if (reg_files_only) {
274 if (lstat(pair->src_name, &st)) {
275 message_error("%s: %s", pair->src_name,
279 } else if (S_ISLNK(st.st_mode)) {
280 message_warning(_("%s: Is a symbolic link, "
281 "skipping"), pair->src_name);
287 // Try to open the file. If we are accepting non-regular files,
288 // unblock the caught signals so that open() can be interrupted
289 // if it blocks e.g. due to a FIFO file.
293 // Maybe this wouldn't need a loop, since all the signal handlers for
294 // which we don't use SA_RESTART set user_abort to true. But it
295 // doesn't hurt to have it just in case.
297 pair->src_fd = open(pair->src_name, flags);
298 } while (pair->src_fd == -1 && errno == EINTR && !user_abort);
303 if (pair->src_fd == -1) {
304 // If we were interrupted, don't display any error message.
305 if (errno == EINTR) {
306 // All the signals that don't have SA_RESTART
313 // Give an understandable error message in if reason
314 // for failing was that the file was a symbolic link.
316 // Note that at least Linux, OpenBSD, Solaris, and Darwin
317 // use ELOOP to indicate if O_NOFOLLOW was the reason
318 // that open() failed. Because there may be
319 // directories in the pathname, ELOOP may occur also
320 // because of a symlink loop in the directory part.
321 // So ELOOP doesn't tell us what actually went wrong.
323 // FreeBSD associates EMLINK with O_NOFOLLOW and
324 // Tru64 uses ENOTSUP. We use these directly here
325 // and skip the lstat() call and the associated race.
326 // I want to hear if there are other kernels that
327 // fail with something else than ELOOP with O_NOFOLLOW.
328 bool was_symlink = false;
330 # if defined(__FreeBSD__) || defined(__DragonFly__)
334 # elif defined(__digital__) && defined(__unix__)
335 if (errno == ENOTSUP)
338 # elif defined(__NetBSD__)
339 // FIXME? As of 2008-11-20, NetBSD doesn't document what
340 // errno is used with O_NOFOLLOW. It seems to be EFTYPE,
341 // but since it isn't documented, it may be wrong to rely
347 if (errno == ELOOP && reg_files_only) {
348 const int saved_errno = errno;
350 if (lstat(pair->src_name, &st) == 0
351 && S_ISLNK(st.st_mode))
359 message_warning(_("%s: Is a symbolic link, "
360 "skipping"), pair->src_name);
363 // Something else than O_NOFOLLOW failing
364 // (assuming that the race conditions didn't
366 message_error("%s: %s", pair->src_name,
372 #ifndef TUKLIB_DOSLIKE
373 // Drop O_NONBLOCK, which is used only when we are accepting only
374 // regular files. After the open() call, we want things to block
375 // instead of giving EAGAIN.
376 if (reg_files_only) {
377 flags = fcntl(pair->src_fd, F_GETFL);
381 flags &= ~O_NONBLOCK;
383 if (fcntl(pair->src_fd, F_SETFL, flags))
388 // Stat the source file. We need the result also when we copy
389 // the permissions, and when unlinking.
390 if (fstat(pair->src_fd, &pair->src_st))
393 if (S_ISDIR(pair->src_st.st_mode)) {
394 message_warning(_("%s: Is a directory, skipping"),
399 if (reg_files_only) {
400 if (!S_ISREG(pair->src_st.st_mode)) {
401 message_warning(_("%s: Not a regular file, "
402 "skipping"), pair->src_name);
406 // These are meaningless on Windows.
407 #ifndef TUKLIB_DOSLIKE
408 if (pair->src_st.st_mode & (S_ISUID | S_ISGID)) {
409 // gzip rejects setuid and setgid files even
410 // when --force was used. bzip2 doesn't check
411 // for them, but calls fchown() after fchmod(),
412 // and many systems automatically drop setuid
413 // and setgid bits there.
415 // We accept setuid and setgid files if
416 // --force was used. We drop these bits
417 // explicitly in io_copy_attr().
418 message_warning(_("%s: File has setuid or "
419 "setgid bit set, skipping"),
424 if (pair->src_st.st_mode & S_ISVTX) {
425 message_warning(_("%s: File has sticky bit "
431 if (pair->src_st.st_nlink > 1) {
432 message_warning(_("%s: Input file has more "
433 "than one hard link, "
434 "skipping"), pair->src_name);
443 message_error("%s: %s", pair->src_name, strerror(errno));
445 (void)close(pair->src_fd);
450 /// \brief Closes source file of the file_pair structure
452 /// \param pair File whose src_fd should be closed
453 /// \param success If true, the file will be removed from the disk if
454 /// closing succeeds and --keep hasn't been used.
456 io_close_src(file_pair *pair, bool success)
458 if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) {
459 #ifdef TUKLIB_DOSLIKE
460 (void)close(pair->src_fd);
463 // If we are going to unlink(), do it before closing the file.
464 // This way there's no risk that someone replaces the file and
465 // happens to get same inode number, which would make us
466 // unlink() wrong file.
468 // NOTE: DOS-like systems are an exception to this, because
469 // they don't allow unlinking files that are open. *sigh*
470 if (success && !opt_keep_original)
471 io_unlink(pair->src_name, &pair->src_st);
473 #ifndef TUKLIB_DOSLIKE
474 (void)close(pair->src_fd);
483 io_open_dest(file_pair *pair)
485 if (opt_stdout || pair->src_fd == STDIN_FILENO) {
486 // We don't modify or free() this.
487 pair->dest_name = (char *)"(stdout)";
488 pair->dest_fd = STDOUT_FILENO;
489 #ifdef TUKLIB_DOSLIKE
490 setmode(STDOUT_FILENO, O_BINARY);
495 pair->dest_name = suffix_get_dest_name(pair->src_name);
496 if (pair->dest_name == NULL)
499 // If --force was used, unlink the target file first.
500 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
501 message_error("%s: Cannot unlink: %s",
502 pair->dest_name, strerror(errno));
503 free(pair->dest_name);
507 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
508 message_error("%s: Cannot unlink: %s", pair->dest_name,
510 free(pair->dest_name);
515 const int flags = O_WRONLY | O_BINARY | O_NOCTTY | O_CREAT | O_EXCL;
516 const mode_t mode = S_IRUSR | S_IWUSR;
517 pair->dest_fd = open(pair->dest_name, flags, mode);
519 if (pair->dest_fd == -1) {
520 // Don't bother with error message if user requested
521 // us to exit anyway.
523 message_error("%s: %s", pair->dest_name,
526 free(pair->dest_name);
530 // If this really fails... well, we have a safe fallback.
531 if (fstat(pair->dest_fd, &pair->dest_st)) {
532 pair->dest_st.st_dev = 0;
534 pair->dest_st.st_ino = 0;
542 /// \brief Closes destination file of the file_pair structure
544 /// \param pair File whose dest_fd should be closed
545 /// \param success If false, the file will be removed from the disk.
547 /// \return Zero if closing succeeds. On error, -1 is returned and
548 /// error message printed.
550 io_close_dest(file_pair *pair, bool success)
552 if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
555 if (close(pair->dest_fd)) {
556 message_error(_("%s: Closing the file failed: %s"),
557 pair->dest_name, strerror(errno));
559 // Closing destination file failed, so we cannot trust its
560 // contents. Get rid of junk:
561 io_unlink(pair->dest_name, &pair->dest_st);
562 free(pair->dest_name);
566 // If the operation using this file wasn't successful, we git rid
569 io_unlink(pair->dest_name, &pair->dest_st);
571 free(pair->dest_name);
578 io_open(const char *src_name)
580 if (is_empty_filename(src_name))
583 // Since we have only one file open at a time, we can use
584 // a statically allocated structure.
585 static file_pair pair;
588 .src_name = src_name,
595 // Block the signals, for which we have a custom signal handler, so
596 // that we don't need to worry about EINTR.
599 file_pair *ret = NULL;
600 if (!io_open_src(&pair)) {
601 // io_open_src() may have unblocked the signals temporarily,
602 // and thus user_abort may have got set even if open()
604 if (user_abort || io_open_dest(&pair))
605 io_close_src(&pair, false);
617 io_close(file_pair *pair, bool success)
621 if (success && pair->dest_fd != STDOUT_FILENO)
624 // Close the destination first. If it fails, we must not remove
626 if (io_close_dest(pair, success))
629 // Close the source file, and unlink it if the operation using this
630 // file pair was successful and we haven't requested to keep the
632 io_close_src(pair, success);
641 io_read(file_pair *pair, uint8_t *buf, size_t size)
643 // We use small buffers here.
644 assert(size < SSIZE_MAX);
649 const ssize_t amount = read(pair->src_fd, buf, left);
652 pair->src_eof = true;
657 if (errno == EINTR) {
664 message_error(_("%s: Read error: %s"),
665 pair->src_name, strerror(errno));
667 // FIXME Is this needed?
668 pair->src_eof = true;
673 buf += (size_t)(amount);
674 left -= (size_t)(amount);
682 io_write(const file_pair *pair, const uint8_t *buf, size_t size)
684 assert(size < SSIZE_MAX);
687 const ssize_t amount = write(pair->dest_fd, buf, size);
689 if (errno == EINTR) {
696 // Handle broken pipe specially. gzip and bzip2
697 // don't print anything on SIGPIPE. In addition,
698 // gzip --quiet uses exit status 2 (warning) on
699 // broken pipe instead of whatever raise(SIGPIPE)
700 // would make it return. It is there to hide "Broken
701 // pipe" message on some old shells (probably old
704 // We don't do anything special with --quiet, which
705 // is what bzip2 does too. If we get SIGPIPE, we
706 // will handle it like other signals by setting
707 // user_abort, and get EPIPE here.
709 message_error(_("%s: Write error: %s"),
710 pair->dest_name, strerror(errno));
715 buf += (size_t)(amount);
716 size -= (size_t)(amount);