]> icculus.org git repositories - icculus/xz.git/blob - src/xz/io.c
Various code cleanups the the xz command line tool.
[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 #ifndef O_BINARY
31 #       define O_BINARY 0
32 #endif
33
34 #ifndef O_NOCTTY
35 #       define O_NOCTTY 0
36 #endif
37
38 #ifndef _WIN32
39 #       include "open_stdxxx.h"
40 static bool warn_fchown;
41 #endif
42
43
44 extern void
45 io_init(void)
46 {
47 #ifndef _WIN32
48         // Make sure that stdin, stdout, and and stderr are connected to
49         // a valid file descriptor. Exit immediatelly with exit code ERROR
50         // if we cannot make the file descriptors valid. Maybe we should
51         // print an error message, but our stderr could be screwed anyway.
52         open_stdxxx(E_ERROR);
53
54         // If fchown() fails setting the owner, we warn about it only if
55         // we are root.
56         warn_fchown = geteuid() == 0;
57 #endif
58
59         return;
60 }
61
62
63 /// \brief      Unlinks a file
64 ///
65 /// This tries to verify that the file being unlinked really is the file that
66 /// we want to unlink by verifying device and inode numbers. There's still
67 /// a small unavoidable race, but this is much better than nothing (the file
68 /// could have been moved/replaced even hours earlier).
69 static void
70 io_unlink(const char *name, const struct stat *known_st)
71 {
72         // On Windows, st_ino is meaningless, so don't bother testing it.
73 #ifndef _WIN32
74         struct stat new_st;
75
76         if (lstat(name, &new_st)
77                         || new_st.st_dev != known_st->st_dev
78                         || new_st.st_ino != known_st->st_ino)
79                 message_error(_("%s: File seems to be moved, not removing"),
80                                 name);
81         else
82 #endif
83                 // There's a race condition between lstat() and unlink()
84                 // but at least we have tried to avoid removing wrong file.
85                 if (unlink(name))
86                         message_error(_("%s: Cannot remove: %s"),
87                                         name, strerror(errno));
88
89         return;
90 }
91
92
93 /// \brief      Copies owner/group and permissions
94 ///
95 /// \todo       ACL and EA support
96 ///
97 static void
98 io_copy_attrs(const file_pair *pair)
99 {
100         // Skip chown and chmod on Windows.
101 #ifndef _WIN32
102         // This function is more tricky than you may think at first.
103         // Blindly copying permissions may permit users to access the
104         // destination file who didn't have permission to access the
105         // source file.
106
107         // Try changing the owner of the file. If we aren't root or the owner
108         // isn't already us, fchown() probably doesn't succeed. We warn
109         // about failing fchown() only if we are root.
110         if (fchown(pair->dest_fd, pair->src_st.st_uid, -1) && warn_fchown)
111                 message_warning(_("%s: Cannot set the file owner: %s"),
112                                 pair->dest_name, strerror(errno));
113
114         mode_t mode;
115
116         if (fchown(pair->dest_fd, -1, pair->src_st.st_gid)) {
117                 message_warning(_("%s: Cannot set the file group: %s"),
118                                 pair->dest_name, strerror(errno));
119                 // We can still safely copy some additional permissions:
120                 // `group' must be at least as strict as `other' and
121                 // also vice versa.
122                 //
123                 // NOTE: After this, the owner of the source file may
124                 // get additional permissions. This shouldn't be too bad,
125                 // because the owner would have had permission to chmod
126                 // the original file anyway.
127                 mode = ((pair->src_st.st_mode & 0070) >> 3)
128                                 & (pair->src_st.st_mode & 0007);
129                 mode = (pair->src_st.st_mode & 0700) | (mode << 3) | mode;
130         } else {
131                 // Drop the setuid, setgid, and sticky bits.
132                 mode = pair->src_st.st_mode & 0777;
133         }
134
135         if (fchmod(pair->dest_fd, mode))
136                 message_warning(_("%s: Cannot set the file permissions: %s"),
137                                 pair->dest_name, strerror(errno));
138 #endif
139
140         // Copy the timestamps. We have several possible ways to do this, of
141         // which some are better in both security and precision.
142         //
143         // First, get the nanosecond part of the timestamps. As of writing,
144         // it's not standardized by POSIX, and there are several names for
145         // the same thing in struct stat.
146         long atime_nsec;
147         long mtime_nsec;
148
149 #       if defined(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
150         // GNU and Solaris
151         atime_nsec = pair->src_st.st_atim.tv_nsec;
152         mtime_nsec = pair->src_st.st_mtim.tv_nsec;
153
154 #       elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
155         // BSD
156         atime_nsec = pair->src_st.st_atimespec.tv_nsec;
157         mtime_nsec = pair->src_st.st_mtimespec.tv_nsec;
158
159 #       elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC)
160         // GNU and BSD without extensions
161         atime_nsec = pair->src_st.st_atimensec;
162         mtime_nsec = pair->src_st.st_mtimensec;
163
164 #       elif defined(HAVE_STRUCT_STAT_ST_UATIME)
165         // Tru64
166         atime_nsec = pair->src_st.st_uatime * 1000;
167         mtime_nsec = pair->src_st.st_umtime * 1000;
168
169 #       elif defined(HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC)
170         // UnixWare
171         atime_nsec = pair->src_st.st_atim.st__tim.tv_nsec;
172         mtime_nsec = pair->src_st.st_mtim.st__tim.tv_nsec;
173
174 #       else
175         // Safe fallback
176         atime_nsec = 0;
177         mtime_nsec = 0;
178 #       endif
179
180         // Construct a structure to hold the timestamps and call appropriate
181         // function to set the timestamps.
182 #if defined(HAVE_FUTIMENS)
183         // Use nanosecond precision.
184         struct timespec tv[2];
185         tv[0].tv_sec = pair->src_st.st_atime;
186         tv[0].tv_nsec = atime_nsec;
187         tv[1].tv_sec = pair->src_st.st_mtime;
188         tv[1].tv_nsec = mtime_nsec;
189
190         (void)futimens(pair->dest_fd, tv);
191
192 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
193         // Use microsecond precision.
194         struct timeval tv[2];
195         tv[0].tv_sec = pair->src_st.st_atime;
196         tv[0].tv_usec = atime_nsec / 1000;
197         tv[1].tv_sec = pair->src_st.st_mtime;
198         tv[1].tv_usec = mtime_nsec / 1000;
199
200 #       if defined(HAVE_FUTIMES)
201         (void)futimes(pair->dest_fd, tv);
202 #       elif defined(HAVE_FUTIMESAT)
203         (void)futimesat(pair->dest_fd, NULL, tv);
204 #       else
205         // Argh, no function to use a file descriptor to set the timestamp.
206         (void)utimes(pair->dest_name, tv);
207 #       endif
208
209 #elif defined(HAVE_UTIME)
210         // Use one-second precision. utime() doesn't support using file
211         // descriptor either. Some systems have broken utime() prototype
212         // so don't make this const.
213         struct utimbuf buf = {
214                 .actime = pair->src_st.st_atime,
215                 .modtime = pair->src_st.st_mtime,
216         };
217
218         // Avoid warnings.
219         (void)atime_nsec;
220         (void)mtime_nsec;
221
222         (void)utime(pair->dest_name, &buf);
223 #endif
224
225         return;
226 }
227
228
229 /// Opens the source file. Returns false on success, true on error.
230 static bool
231 io_open_src(file_pair *pair)
232 {
233         // There's nothing to open when reading from stdin.
234         if (pair->src_name == stdin_filename) {
235                 pair->src_fd = STDIN_FILENO;
236 #ifdef _WIN32
237                 setmode(STDIN_FILENO, O_BINARY);
238 #endif
239                 return false;
240         }
241
242         // We accept only regular files if we are writing the output
243         // to disk too, and if --force was not given.
244         const bool reg_files_only = !opt_stdout && !opt_force;
245
246         // Flags for open()
247         int flags = O_RDONLY | O_BINARY | O_NOCTTY;
248
249 #ifndef _WIN32
250         // If we accept only regular files, we need to be careful to avoid
251         // problems with special files like devices and FIFOs. O_NONBLOCK
252         // prevents blocking when opening such files. When we want to accept
253         // special files, we must not use O_NONBLOCK, or otherwise we won't
254         // block waiting e.g. FIFOs to become readable.
255         if (reg_files_only)
256                 flags |= O_NONBLOCK;
257 #endif
258
259 #if defined(O_NOFOLLOW)
260         if (reg_files_only)
261                 flags |= O_NOFOLLOW;
262 #elif !defined(_WIN32)
263         // Some POSIX-like systems lack O_NOFOLLOW (it's not required
264         // by POSIX). Check for symlinks with a separate lstat() on
265         // these systems.
266         if (reg_files_only) {
267                 struct stat st;
268                 if (lstat(pair->src_name, &st)) {
269                         message_error("%s: %s", pair->src_name,
270                                         strerror(errno));
271                         return true;
272
273                 } else if (S_ISLNK(st.st_mode)) {
274                         message_warning(_("%s: Is a symbolic link, "
275                                         "skipping"), pair->src_name);
276                         return true;
277                 }
278         }
279 #endif
280
281         // Try to open the file. If we are accepting non-regular files,
282         // unblock the caught signals so that open() can be interrupted
283         // if it blocks e.g. due to a FIFO file.
284         if (!reg_files_only)
285                 signals_unblock();
286
287         // Maybe this wouldn't need a loop, since all the signal handlers for
288         // which we don't use SA_RESTART set user_abort to true. But it
289         // doesn't hurt to have it just in case.
290         do {
291                 pair->src_fd = open(pair->src_name, flags);
292         } while (pair->src_fd == -1 && errno == EINTR && !user_abort);
293
294         if (!reg_files_only)
295                 signals_block();
296
297         if (pair->src_fd == -1) {
298                 // If we were interrupted, don't display any error message.
299                 if (errno == EINTR) {
300                         // All the signals that don't have SA_RESTART
301                         // set user_abort.
302                         assert(user_abort);
303                         return true;
304                 }
305
306 #ifdef O_NOFOLLOW
307                 // Give an understandable error message in if reason
308                 // for failing was that the file was a symbolic link.
309                 //
310                 // Note that at least Linux, OpenBSD, Solaris, and Darwin
311                 // use ELOOP to indicate if O_NOFOLLOW was the reason
312                 // that open() failed. Because there may be
313                 // directories in the pathname, ELOOP may occur also
314                 // because of a symlink loop in the directory part.
315                 // So ELOOP doesn't tell us what actually went wrong.
316                 //
317                 // FreeBSD associates EMLINK with O_NOFOLLOW and
318                 // Tru64 uses ENOTSUP. We use these directly here
319                 // and skip the lstat() call and the associated race.
320                 // I want to hear if there are other kernels that
321                 // fail with something else than ELOOP with O_NOFOLLOW.
322                 bool was_symlink = false;
323
324 #       if defined(__FreeBSD__) || defined(__DragonFly__)
325                 if (errno == EMLINK)
326                         was_symlink = true;
327
328 #       elif defined(__digital__) && defined(__unix__)
329                 if (errno == ENOTSUP)
330                         was_symlink = true;
331
332 #       elif defined(__NetBSD__)
333                 // FIXME? As of 2008-11-20, NetBSD doesn't document what
334                 // errno is used with O_NOFOLLOW. It seems to be EFTYPE,
335                 // but since it isn't documented, it may be wrong to rely
336                 // on it here.
337                 if (errno == EFTYPE)
338                         was_symlink = true;
339
340 #       else
341                 if (errno == ELOOP && reg_files_only) {
342                         const int saved_errno = errno;
343                         struct stat st;
344                         if (lstat(pair->src_name, &st) == 0
345                                         && S_ISLNK(st.st_mode))
346                                 was_symlink = true;
347
348                         errno = saved_errno;
349                 }
350 #       endif
351
352                 if (was_symlink)
353                         message_warning(_("%s: Is a symbolic link, "
354                                         "skipping"), pair->src_name);
355                 else
356 #endif
357                         // Something else than O_NOFOLLOW failing
358                         // (assuming that the race conditions didn't
359                         // confuse us).
360                         message_error("%s: %s", pair->src_name,
361                                         strerror(errno));
362
363                 return true;
364         }
365
366 #ifndef _WIN32
367         // Drop O_NONBLOCK, which is used only when we are accepting only
368         // regular files. After the open() call, we want things to block
369         // instead of giving EAGAIN.
370         if (reg_files_only) {
371                 flags = fcntl(pair->src_fd, F_GETFL);
372                 if (flags == -1)
373                         goto error_msg;
374
375                 flags &= ~O_NONBLOCK;
376
377                 if (fcntl(pair->src_fd, F_SETFL, flags))
378                         goto error_msg;
379         }
380 #endif
381
382         // Stat the source file. We need the result also when we copy
383         // the permissions, and when unlinking.
384         if (fstat(pair->src_fd, &pair->src_st))
385                 goto error_msg;
386
387         if (S_ISDIR(pair->src_st.st_mode)) {
388                 message_warning(_("%s: Is a directory, skipping"),
389                                 pair->src_name);
390                 goto error;
391         }
392
393         if (reg_files_only) {
394                 if (!S_ISREG(pair->src_st.st_mode)) {
395                         message_warning(_("%s: Not a regular file, "
396                                         "skipping"), pair->src_name);
397                         goto error;
398                 }
399
400                 // These are meaningless on Windows.
401 #ifndef _WIN32
402                 if (pair->src_st.st_mode & (S_ISUID | S_ISGID)) {
403                         // gzip rejects setuid and setgid files even
404                         // when --force was used. bzip2 doesn't check
405                         // for them, but calls fchown() after fchmod(),
406                         // and many systems automatically drop setuid
407                         // and setgid bits there.
408                         //
409                         // We accept setuid and setgid files if
410                         // --force was used. We drop these bits
411                         // explicitly in io_copy_attr().
412                         message_warning(_("%s: File has setuid or "
413                                         "setgid bit set, skipping"),
414                                         pair->src_name);
415                         goto error;
416                 }
417
418                 if (pair->src_st.st_mode & S_ISVTX) {
419                         message_warning(_("%s: File has sticky bit "
420                                         "set, skipping"),
421                                         pair->src_name);
422                         goto error;
423                 }
424
425                 if (pair->src_st.st_nlink > 1) {
426                         message_warning(_("%s: Input file has more "
427                                         "than one hard link, "
428                                         "skipping"), pair->src_name);
429                         goto error;
430                 }
431 #endif
432         }
433
434         return false;
435
436 error_msg:
437         message_error("%s: %s", pair->src_name, strerror(errno));
438 error:
439         (void)close(pair->src_fd);
440         return true;
441 }
442
443
444 /// \brief      Closes source file of the file_pair structure
445 ///
446 /// \param      pair    File whose src_fd should be closed
447 /// \param      success If true, the file will be removed from the disk if
448 ///                     closing succeeds and --keep hasn't been used.
449 static void
450 io_close_src(file_pair *pair, bool success)
451 {
452         if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) {
453 #ifdef _WIN32
454                 (void)close(pair->src_fd);
455 #endif
456
457                 // If we are going to unlink(), do it before closing the file.
458                 // This way there's no risk that someone replaces the file and
459                 // happens to get same inode number, which would make us
460                 // unlink() wrong file.
461                 //
462                 // NOTE: Windows is an exception to this, because it doesn't
463                 // allow unlinking files that are open. *sigh*
464                 if (success && !opt_keep_original)
465                         io_unlink(pair->src_name, &pair->src_st);
466
467 #ifndef _WIN32
468                 (void)close(pair->src_fd);
469 #endif
470         }
471
472         return;
473 }
474
475
476 static bool
477 io_open_dest(file_pair *pair)
478 {
479         if (opt_stdout || pair->src_fd == STDIN_FILENO) {
480                 // We don't modify or free() this.
481                 pair->dest_name = (char *)"(stdout)";
482                 pair->dest_fd = STDOUT_FILENO;
483 #ifdef _WIN32
484                 setmode(STDOUT_FILENO, O_BINARY);
485 #endif
486                 return false;
487         }
488
489         pair->dest_name = suffix_get_dest_name(pair->src_name);
490         if (pair->dest_name == NULL)
491                 return true;
492
493         // If --force was used, unlink the target file first.
494         if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
495                 message_error("%s: Cannot unlink: %s",
496                                 pair->dest_name, strerror(errno));
497                 free(pair->dest_name);
498                 return true;
499         }
500
501         if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
502                 message_error("%s: Cannot unlink: %s", pair->dest_name,
503                                 strerror(errno));
504                 free(pair->dest_name);
505                 return true;
506         }
507
508         // Open the file.
509         const int flags = O_WRONLY | O_BINARY | O_NOCTTY | O_CREAT | O_EXCL;
510         const mode_t mode = S_IRUSR | S_IWUSR;
511         pair->dest_fd = open(pair->dest_name, flags, mode);
512
513         if (pair->dest_fd == -1) {
514                 // Don't bother with error message if user requested
515                 // us to exit anyway.
516                 if (!user_abort)
517                         message_error("%s: %s", pair->dest_name,
518                                         strerror(errno));
519
520                 free(pair->dest_name);
521                 return true;
522         }
523
524         // If this really fails... well, we have a safe fallback.
525         if (fstat(pair->dest_fd, &pair->dest_st)) {
526                 pair->dest_st.st_dev = 0;
527                 pair->dest_st.st_ino = 0;
528         }
529
530         return false;
531 }
532
533
534 /// \brief      Closes destination file of the file_pair structure
535 ///
536 /// \param      pair    File whose dest_fd should be closed
537 /// \param      success If false, the file will be removed from the disk.
538 ///
539 /// \return     Zero if closing succeeds. On error, -1 is returned and
540 ///             error message printed.
541 static int
542 io_close_dest(file_pair *pair, bool success)
543 {
544         if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
545                 return 0;
546
547         if (close(pair->dest_fd)) {
548                 message_error(_("%s: Closing the file failed: %s"),
549                                 pair->dest_name, strerror(errno));
550
551                 // Closing destination file failed, so we cannot trust its
552                 // contents. Get rid of junk:
553                 io_unlink(pair->dest_name, &pair->dest_st);
554                 free(pair->dest_name);
555                 return -1;
556         }
557
558         // If the operation using this file wasn't successful, we git rid
559         // of the junk file.
560         if (!success)
561                 io_unlink(pair->dest_name, &pair->dest_st);
562
563         free(pair->dest_name);
564
565         return 0;
566 }
567
568
569 extern file_pair *
570 io_open(const char *src_name)
571 {
572         if (is_empty_filename(src_name))
573                 return NULL;
574
575         // Since we have only one file open at a time, we can use
576         // a statically allocated structure.
577         static file_pair pair;
578
579         pair = (file_pair){
580                 .src_name = src_name,
581                 .dest_name = NULL,
582                 .src_fd = -1,
583                 .dest_fd = -1,
584                 .src_eof = false,
585         };
586
587         // Block the signals, for which we have a custom signal handler, so
588         // that we don't need to worry about EINTR.
589         signals_block();
590
591         file_pair *ret = NULL;
592         if (!io_open_src(&pair)) {
593                 // io_open_src() may have unblocked the signals temporarily,
594                 // and thus user_abort may have got set even if open()
595                 // succeeded.
596                 if (user_abort || io_open_dest(&pair))
597                         io_close_src(&pair, false);
598                 else
599                         ret = &pair;
600         }
601
602         signals_unblock();
603
604         return ret;
605 }
606
607
608 extern void
609 io_close(file_pair *pair, bool success)
610 {
611         signals_block();
612
613         if (success && pair->dest_fd != STDOUT_FILENO)
614                 io_copy_attrs(pair);
615
616         // Close the destination first. If it fails, we must not remove
617         // the source file!
618         if (io_close_dest(pair, success))
619                 success = false;
620
621         // Close the source file, and unlink it if the operation using this
622         // file pair was successful and we haven't requested to keep the
623         // source file.
624         io_close_src(pair, success);
625
626         signals_unblock();
627
628         return;
629 }
630
631
632 extern size_t
633 io_read(file_pair *pair, uint8_t *buf, size_t size)
634 {
635         // We use small buffers here.
636         assert(size < SSIZE_MAX);
637
638         size_t left = size;
639
640         while (left > 0) {
641                 const ssize_t amount = read(pair->src_fd, buf, left);
642
643                 if (amount == 0) {
644                         pair->src_eof = true;
645                         break;
646                 }
647
648                 if (amount == -1) {
649                         if (errno == EINTR) {
650                                 if (user_abort)
651                                         return SIZE_MAX;
652
653                                 continue;
654                         }
655
656                         message_error(_("%s: Read error: %s"),
657                                         pair->src_name, strerror(errno));
658
659                         // FIXME Is this needed?
660                         pair->src_eof = true;
661
662                         return SIZE_MAX;
663                 }
664
665                 buf += (size_t)(amount);
666                 left -= (size_t)(amount);
667         }
668
669         return size - left;
670 }
671
672
673 extern bool
674 io_write(const file_pair *pair, const uint8_t *buf, size_t size)
675 {
676         assert(size < SSIZE_MAX);
677
678         while (size > 0) {
679                 const ssize_t amount = write(pair->dest_fd, buf, size);
680                 if (amount == -1) {
681                         if (errno == EINTR) {
682                                 if (user_abort)
683                                         return -1;
684
685                                 continue;
686                         }
687
688                         // Handle broken pipe specially. gzip and bzip2
689                         // don't print anything on SIGPIPE. In addition,
690                         // gzip --quiet uses exit status 2 (warning) on
691                         // broken pipe instead of whatever raise(SIGPIPE)
692                         // would make it return. It is there to hide "Broken
693                         // pipe" message on some old shells (probably old
694                         // GNU bash).
695                         //
696                         // We don't do anything special with --quiet, which
697                         // is what bzip2 does too. If we get SIGPIPE, we
698                         // will handle it like other signals by setting
699                         // user_abort, and get EPIPE here.
700                         if (errno != EPIPE)
701                                 message_error(_("%s: Write error: %s"),
702                                         pair->dest_name, strerror(errno));
703
704                         return true;
705                 }
706
707                 buf += (size_t)(amount);
708                 size -= (size_t)(amount);
709         }
710
711         return false;
712 }