]> icculus.org git repositories - icculus/xz.git/blob - src/xz/io.c
Another utime() fix.
[icculus/xz.git] / src / xz / io.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       io.c
4 /// \brief      File opening, unlinking, and closing
5 //
6 //  Copyright (C) 2007 Lasse Collin
7 //
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.
12 //
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.
17 //
18 ///////////////////////////////////////////////////////////////////////////////
19
20 #include "private.h"
21
22 #include <fcntl.h>
23
24 #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
25 #       include <sys/time.h>
26 #elif defined(HAVE_UTIME)
27 #       include <utime.h>
28 #endif
29
30
31 /// \brief      Unlinks a file
32 ///
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).
37 static void
38 io_unlink(const char *name, const struct stat *known_st)
39 {
40         struct stat new_st;
41
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"),
46                                 name);
47         } else {
48                 // There's a race condition between lstat() and unlink()
49                 // but at least we have tried to avoid removing wrong file.
50                 if (unlink(name))
51                         message_error(_("%s: Cannot remove: %s"),
52                                         name, strerror(errno));
53         }
54
55         return;
56 }
57
58
59 /// \brief      Copies owner/group and permissions
60 ///
61 /// \todo       ACL and EA support
62 ///
63 static void
64 io_copy_attrs(const file_pair *pair)
65 {
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
69         // source file.
70
71         // Simple cache to avoid repeated calls to geteuid().
72         static enum {
73                 WARN_FCHOWN_UNKNOWN,
74                 WARN_FCHOWN_NO,
75                 WARN_FCHOWN_YES,
76         } warn_fchown = WARN_FCHOWN_UNKNOWN;
77
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;
86
87                 if (warn_fchown == WARN_FCHOWN_YES)
88                         message_warning(_("%s: Cannot set the file owner: %s"),
89                                         pair->dest_name, strerror(errno));
90         }
91
92         mode_t mode;
93
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
99                 // also vice versa.
100                 //
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;
108         } else {
109                 // Drop the setuid, setgid, and sticky bits.
110                 mode = pair->src_st.st_mode & 0777;
111         }
112
113         if (fchmod(pair->dest_fd, mode))
114                 message_warning(_("%s: Cannot set the file permissions: %s"),
115                                 pair->dest_name, strerror(errno));
116
117         // Copy the timestamps. We have several possible ways to do this, of
118         // which some are better in both security and precision.
119         //
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.
123         long atime_nsec;
124         long mtime_nsec;
125
126 #       if defined(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
127         // GNU and Solaris
128         atime_nsec = pair->src_st.st_atim.tv_nsec;
129         mtime_nsec = pair->src_st.st_mtim.tv_nsec;
130
131 #       elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
132         // BSD
133         atime_nsec = pair->src_st.st_atimespec.tv_nsec;
134         mtime_nsec = pair->src_st.st_mtimespec.tv_nsec;
135
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;
140
141 #       elif defined(HAVE_STRUCT_STAT_ST_UATIME)
142         // Tru64
143         atime_nsec = pair->src_st.st_uatime * 1000;
144         mtime_nsec = pair->src_st.st_umtime * 1000;
145
146 #       elif defined(HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC)
147         // UnixWare
148         atime_nsec = pair->src_st.st_atim.st__tim.tv_nsec;
149         mtime_nsec = pair->src_st.st_mtim.st__tim.tv_nsec;
150
151 #       else
152         // Safe fallback
153         atime_nsec = 0;
154         mtime_nsec = 0;
155 #       endif
156
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;
166
167         (void)futimens(pair->dest_fd, tv);
168
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;
176
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);
181 #       else
182         // Argh, no function to use a file descriptor to set the timestamp.
183         (void)utimes(pair->dest_name, tv);
184 #       endif
185
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,
193         };
194
195         // Avoid warnings.
196         (void)atime_nsec;
197         (void)mtime_nsec;
198
199         (void)utime(pair->dest_name, &buf);
200 #endif
201
202         return;
203 }
204
205
206 /// Opens the source file. Returns false on success, true on error.
207 static bool
208 io_open_src(file_pair *pair)
209 {
210         // There's nothing to open when reading from stdin.
211         if (pair->src_name == stdin_filename) {
212                 pair->src_fd = STDIN_FILENO;
213                 return false;
214         }
215
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;
219
220         // Flags for open()
221         int flags = O_RDONLY | O_NOCTTY;
222
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.
228         if (reg_files_only)
229                 flags |= O_NONBLOCK;
230
231 #ifdef O_NOFOLLOW
232         if (reg_files_only)
233                 flags |= O_NOFOLLOW;
234 #else
235         // Some POSIX-like systems lack O_NOFOLLOW (it's not required
236         // by POSIX). Check for symlinks with a separate lstat() on
237         // these systems.
238         if (reg_files_only) {
239                 struct stat st;
240                 if (lstat(pair->src_name, &st)) {
241                         message_error("%s: %s", pair->src_name,
242                                         strerror(errno));
243                         return true;
244
245                 } else if (S_ISLNK(st.st_mode)) {
246                         message_warning(_("%s: Is a symbolic link, "
247                                         "skipping"), pair->src_name);
248                         return true;
249                 }
250         }
251 #endif
252
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.
256         if (!reg_files_only)
257                 signals_unblock();
258
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.
262         do {
263                 pair->src_fd = open(pair->src_name, flags);
264         } while (pair->src_fd == -1 && errno == EINTR && !user_abort);
265
266         if (!reg_files_only)
267                 signals_block();
268
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
273                         // set user_abort.
274                         assert(user_abort);
275                         return true;
276                 }
277
278 #ifdef O_NOFOLLOW
279                 // Give an understandable error message in if reason
280                 // for failing was that the file was a symbolic link.
281                 //
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.
288                 //
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;
295
296 #       if defined(__FreeBSD__) || defined(__DragonFly__)
297                 if (errno == EMLINK)
298                         was_symlink = true;
299
300 #       elif defined(__digital__) && defined(__unix__)
301                 if (errno == ENOTSUP)
302                         was_symlink = true;
303
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
308                 // on it here.
309                 if (errno == EFTYPE)
310                         was_symlink = true;
311
312 #       else
313                 if (errno == ELOOP && reg_files_only) {
314                         const int saved_errno = errno;
315                         struct stat st;
316                         if (lstat(pair->src_name, &st) == 0
317                                         && S_ISLNK(st.st_mode))
318                                 was_symlink = true;
319
320                         errno = saved_errno;
321                 }
322 #       endif
323
324                 if (was_symlink)
325                         message_warning(_("%s: Is a symbolic link, "
326                                         "skipping"), pair->src_name);
327                 else
328 #endif
329                         // Something else than O_NOFOLLOW failing
330                         // (assuming that the race conditions didn't
331                         // confuse us).
332                         message_error("%s: %s", pair->src_name,
333                                         strerror(errno));
334
335                 return true;
336         }
337
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);
343                 if (flags == -1)
344                         goto error_msg;
345
346                 flags &= ~O_NONBLOCK;
347
348                 if (fcntl(pair->src_fd, F_SETFL, flags))
349                         goto error_msg;
350         }
351
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))
355                 goto error_msg;
356
357         if (S_ISDIR(pair->src_st.st_mode)) {
358                 message_warning(_("%s: Is a directory, skipping"),
359                                 pair->src_name);
360                 goto error;
361         }
362
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);
367                         goto error;
368                 }
369
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.
376                         //
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"),
382                                         pair->src_name);
383                         goto error;
384                 }
385
386                 if (pair->src_st.st_mode & S_ISVTX) {
387                         message_warning(_("%s: File has sticky bit "
388                                         "set, skipping"),
389                                         pair->src_name);
390                         goto error;
391                 }
392
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);
397                         goto error;
398                 }
399         }
400
401         return false;
402
403 error_msg:
404         message_error("%s: %s", pair->src_name, strerror(errno));
405 error:
406         (void)close(pair->src_fd);
407         return true;
408 }
409
410
411 /// \brief      Closes source file of the file_pair structure
412 ///
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.
416 static void
417 io_close_src(file_pair *pair, bool success)
418 {
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);
426
427                 (void)close(pair->src_fd);
428         }
429
430         return;
431 }
432
433
434 static bool
435 io_open_dest(file_pair *pair)
436 {
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;
441                 return false;
442         }
443
444         pair->dest_name = suffix_get_dest_name(pair->src_name);
445         if (pair->dest_name == NULL)
446                 return true;
447
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);
453                 return true;
454         }
455
456         if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
457                 message_error("%s: Cannot unlink: %s", pair->dest_name,
458                                 strerror(errno));
459                 free(pair->dest_name);
460                 return true;
461         }
462
463         // Open the file.
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);
467
468         if (pair->dest_fd == -1) {
469                 // Don't bother with error message if user requested
470                 // us to exit anyway.
471                 if (!user_abort)
472                         message_error("%s: %s", pair->dest_name,
473                                         strerror(errno));
474
475                 free(pair->dest_name);
476                 return true;
477         }
478
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;
483         }
484
485         return false;
486 }
487
488
489 /// \brief      Closes destination file of the file_pair structure
490 ///
491 /// \param      pair    File whose dest_fd should be closed
492 /// \param      success If false, the file will be removed from the disk.
493 ///
494 /// \return     Zero if closing succeeds. On error, -1 is returned and
495 ///             error message printed.
496 static int
497 io_close_dest(file_pair *pair, bool success)
498 {
499         if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
500                 return 0;
501
502         if (close(pair->dest_fd)) {
503                 message_error(_("%s: Closing the file failed: %s"),
504                                 pair->dest_name, strerror(errno));
505
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);
510                 return -1;
511         }
512
513         // If the operation using this file wasn't successful, we git rid
514         // of the junk file.
515         if (!success)
516                 io_unlink(pair->dest_name, &pair->dest_st);
517
518         free(pair->dest_name);
519
520         return 0;
521 }
522
523
524 extern file_pair *
525 io_open(const char *src_name)
526 {
527         if (is_empty_filename(src_name))
528                 return NULL;
529
530         // Since we have only one file open at a time, we can use
531         // a statically allocated structure.
532         static file_pair pair;
533
534         pair = (file_pair){
535                 .src_name = src_name,
536                 .dest_name = NULL,
537                 .src_fd = -1,
538                 .dest_fd = -1,
539                 .src_eof = false,
540         };
541
542         // Block the signals, for which we have a custom signal handler, so
543         // that we don't need to worry about EINTR.
544         signals_block();
545
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()
550                 // succeeded.
551                 if (user_abort || io_open_dest(&pair))
552                         io_close_src(&pair, false);
553                 else
554                         ret = &pair;
555         }
556
557         signals_unblock();
558
559         return ret;
560 }
561
562
563 extern void
564 io_close(file_pair *pair, bool success)
565 {
566         signals_block();
567
568         if (success && pair->dest_fd != STDOUT_FILENO)
569                 io_copy_attrs(pair);
570
571         // Close the destination first. If it fails, we must not remove
572         // the source file!
573         if (io_close_dest(pair, success))
574                 success = false;
575
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
578         // source file.
579         io_close_src(pair, success);
580
581         signals_unblock();
582
583         return;
584 }
585
586
587 extern size_t
588 io_read(file_pair *pair, uint8_t *buf, size_t size)
589 {
590         // We use small buffers here.
591         assert(size < SSIZE_MAX);
592
593         size_t left = size;
594
595         while (left > 0) {
596                 const ssize_t amount = read(pair->src_fd, buf, left);
597
598                 if (amount == 0) {
599                         pair->src_eof = true;
600                         break;
601                 }
602
603                 if (amount == -1) {
604                         if (errno == EINTR) {
605                                 if (user_abort)
606                                         return SIZE_MAX;
607
608                                 continue;
609                         }
610
611                         message_error(_("%s: Read error: %s"),
612                                         pair->src_name, strerror(errno));
613
614                         // FIXME Is this needed?
615                         pair->src_eof = true;
616
617                         return SIZE_MAX;
618                 }
619
620                 buf += (size_t)(amount);
621                 left -= (size_t)(amount);
622         }
623
624         return size - left;
625 }
626
627
628 extern bool
629 io_write(const file_pair *pair, const uint8_t *buf, size_t size)
630 {
631         assert(size < SSIZE_MAX);
632
633         while (size > 0) {
634                 const ssize_t amount = write(pair->dest_fd, buf, size);
635                 if (amount == -1) {
636                         if (errno == EINTR) {
637                                 if (user_abort)
638                                         return -1;
639
640                                 continue;
641                         }
642
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
649                         // GNU bash).
650                         //
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.
655                         if (errno != EPIPE)
656                                 message_error(_("%s: Write error: %s"),
657                                         pair->dest_name, strerror(errno));
658
659                         return true;
660                 }
661
662                 buf += (size_t)(amount);
663                 size -= (size_t)(amount);
664         }
665
666         return false;
667 }