]> icculus.org git repositories - icculus/xz.git/blob - src/xz/file_io.c
Various changes.
[icculus/xz.git] / src / xz / file_io.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       file_io.c
4 /// \brief      File opening, unlinking, and closing
5 //
6 //  Author:     Lasse Collin
7 //
8 //  This file has been put into the public domain.
9 //  You can do whatever you want with this file.
10 //
11 ///////////////////////////////////////////////////////////////////////////////
12
13 #include "private.h"
14
15 #include <fcntl.h>
16
17 #ifdef TUKLIB_DOSLIKE
18 #       include <io.h>
19 #else
20 static bool warn_fchown;
21 #endif
22
23 #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
24 #       include <sys/time.h>
25 #elif defined(HAVE_UTIME)
26 #       include <utime.h>
27 #endif
28
29 #include "tuklib_open_stdxxx.h"
30
31 #ifndef O_BINARY
32 #       define O_BINARY 0
33 #endif
34
35 #ifndef O_NOCTTY
36 #       define O_NOCTTY 0
37 #endif
38
39
40 extern void
41 io_init(void)
42 {
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);
48
49 #ifndef TUKLIB_DOSLIKE
50         // If fchown() fails setting the owner, we warn about it only if
51         // we are root.
52         warn_fchown = geteuid() == 0;
53 #endif
54
55 #ifdef __DJGPP__
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;
60 #endif
61
62         return;
63 }
64
65
66 /// \brief      Unlink a file
67 ///
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).
72 static void
73 io_unlink(const char *name, const struct stat *known_st)
74 {
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.
78         (void)known_st;
79 #else
80         struct stat new_st;
81
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"),
86                                 name);
87         else
88 #endif
89                 // There's a race condition between lstat() and unlink()
90                 // but at least we have tried to avoid removing wrong file.
91                 if (unlink(name))
92                         message_error(_("%s: Cannot remove: %s"),
93                                         name, strerror(errno));
94
95         return;
96 }
97
98
99 /// \brief      Copies owner/group and permissions
100 ///
101 /// \todo       ACL and EA support
102 ///
103 static void
104 io_copy_attrs(const file_pair *pair)
105 {
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
111         // source file.
112
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));
119
120         mode_t mode;
121
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
127                 // also vice versa.
128                 //
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;
136         } else {
137                 // Drop the setuid, setgid, and sticky bits.
138                 mode = pair->src_st.st_mode & 0777;
139         }
140
141         if (fchmod(pair->dest_fd, mode))
142                 message_warning(_("%s: Cannot set the file permissions: %s"),
143                                 pair->dest_name, strerror(errno));
144 #endif
145
146         // Copy the timestamps. We have several possible ways to do this, of
147         // which some are better in both security and precision.
148         //
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.
152         long atime_nsec;
153         long mtime_nsec;
154
155 #       if defined(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
156         // GNU and Solaris
157         atime_nsec = pair->src_st.st_atim.tv_nsec;
158         mtime_nsec = pair->src_st.st_mtim.tv_nsec;
159
160 #       elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
161         // BSD
162         atime_nsec = pair->src_st.st_atimespec.tv_nsec;
163         mtime_nsec = pair->src_st.st_mtimespec.tv_nsec;
164
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;
169
170 #       elif defined(HAVE_STRUCT_STAT_ST_UATIME)
171         // Tru64
172         atime_nsec = pair->src_st.st_uatime * 1000;
173         mtime_nsec = pair->src_st.st_umtime * 1000;
174
175 #       elif defined(HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC)
176         // UnixWare
177         atime_nsec = pair->src_st.st_atim.st__tim.tv_nsec;
178         mtime_nsec = pair->src_st.st_mtim.st__tim.tv_nsec;
179
180 #       else
181         // Safe fallback
182         atime_nsec = 0;
183         mtime_nsec = 0;
184 #       endif
185
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;
195
196         (void)futimens(pair->dest_fd, tv);
197
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;
205
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);
210 #       else
211         // Argh, no function to use a file descriptor to set the timestamp.
212         (void)utimes(pair->dest_name, tv);
213 #       endif
214
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,
222         };
223
224         // Avoid warnings.
225         (void)atime_nsec;
226         (void)mtime_nsec;
227
228         (void)utime(pair->dest_name, &buf);
229 #endif
230
231         return;
232 }
233
234
235 /// Opens the source file. Returns false on success, true on error.
236 static bool
237 io_open_src(file_pair *pair)
238 {
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);
244 #endif
245                 return false;
246         }
247
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;
251
252         // Flags for open()
253         int flags = O_RDONLY | O_BINARY | O_NOCTTY;
254
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.
261         if (reg_files_only)
262                 flags |= O_NONBLOCK;
263 #endif
264
265 #if defined(O_NOFOLLOW)
266         if (reg_files_only)
267                 flags |= 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
271         // these systems.
272         if (reg_files_only) {
273                 struct stat st;
274                 if (lstat(pair->src_name, &st)) {
275                         message_error("%s: %s", pair->src_name,
276                                         strerror(errno));
277                         return true;
278
279                 } else if (S_ISLNK(st.st_mode)) {
280                         message_warning(_("%s: Is a symbolic link, "
281                                         "skipping"), pair->src_name);
282                         return true;
283                 }
284         }
285 #endif
286
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.
290         if (!reg_files_only)
291                 signals_unblock();
292
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.
296         do {
297                 pair->src_fd = open(pair->src_name, flags);
298         } while (pair->src_fd == -1 && errno == EINTR && !user_abort);
299
300         if (!reg_files_only)
301                 signals_block();
302
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
307                         // set user_abort.
308                         assert(user_abort);
309                         return true;
310                 }
311
312 #ifdef O_NOFOLLOW
313                 // Give an understandable error message in if reason
314                 // for failing was that the file was a symbolic link.
315                 //
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.
322                 //
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;
329
330 #       if defined(__FreeBSD__) || defined(__DragonFly__)
331                 if (errno == EMLINK)
332                         was_symlink = true;
333
334 #       elif defined(__digital__) && defined(__unix__)
335                 if (errno == ENOTSUP)
336                         was_symlink = true;
337
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
342                 // on it here.
343                 if (errno == EFTYPE)
344                         was_symlink = true;
345
346 #       else
347                 if (errno == ELOOP && reg_files_only) {
348                         const int saved_errno = errno;
349                         struct stat st;
350                         if (lstat(pair->src_name, &st) == 0
351                                         && S_ISLNK(st.st_mode))
352                                 was_symlink = true;
353
354                         errno = saved_errno;
355                 }
356 #       endif
357
358                 if (was_symlink)
359                         message_warning(_("%s: Is a symbolic link, "
360                                         "skipping"), pair->src_name);
361                 else
362 #endif
363                         // Something else than O_NOFOLLOW failing
364                         // (assuming that the race conditions didn't
365                         // confuse us).
366                         message_error("%s: %s", pair->src_name,
367                                         strerror(errno));
368
369                 return true;
370         }
371
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);
378                 if (flags == -1)
379                         goto error_msg;
380
381                 flags &= ~O_NONBLOCK;
382
383                 if (fcntl(pair->src_fd, F_SETFL, flags))
384                         goto error_msg;
385         }
386 #endif
387
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))
391                 goto error_msg;
392
393         if (S_ISDIR(pair->src_st.st_mode)) {
394                 message_warning(_("%s: Is a directory, skipping"),
395                                 pair->src_name);
396                 goto error;
397         }
398
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);
403                         goto error;
404                 }
405
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.
414                         //
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"),
420                                         pair->src_name);
421                         goto error;
422                 }
423
424                 if (pair->src_st.st_mode & S_ISVTX) {
425                         message_warning(_("%s: File has sticky bit "
426                                         "set, skipping"),
427                                         pair->src_name);
428                         goto error;
429                 }
430
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);
435                         goto error;
436                 }
437 #endif
438         }
439
440         return false;
441
442 error_msg:
443         message_error("%s: %s", pair->src_name, strerror(errno));
444 error:
445         (void)close(pair->src_fd);
446         return true;
447 }
448
449
450 /// \brief      Closes source file of the file_pair structure
451 ///
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.
455 static void
456 io_close_src(file_pair *pair, bool success)
457 {
458         if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) {
459 #ifdef TUKLIB_DOSLIKE
460                 (void)close(pair->src_fd);
461 #endif
462
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.
467                 //
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);
472
473 #ifndef TUKLIB_DOSLIKE
474                 (void)close(pair->src_fd);
475 #endif
476         }
477
478         return;
479 }
480
481
482 static bool
483 io_open_dest(file_pair *pair)
484 {
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);
491 #endif
492                 return false;
493         }
494
495         pair->dest_name = suffix_get_dest_name(pair->src_name);
496         if (pair->dest_name == NULL)
497                 return true;
498
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);
504                 return true;
505         }
506
507         if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
508                 message_error("%s: Cannot unlink: %s", pair->dest_name,
509                                 strerror(errno));
510                 free(pair->dest_name);
511                 return true;
512         }
513
514         // Open the file.
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);
518
519         if (pair->dest_fd == -1) {
520                 // Don't bother with error message if user requested
521                 // us to exit anyway.
522                 if (!user_abort)
523                         message_error("%s: %s", pair->dest_name,
524                                         strerror(errno));
525
526                 free(pair->dest_name);
527                 return true;
528         }
529
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;
533 #ifndef __VMS
534                 pair->dest_st.st_ino = 0;
535 #endif
536         }
537
538         return false;
539 }
540
541
542 /// \brief      Closes destination file of the file_pair structure
543 ///
544 /// \param      pair    File whose dest_fd should be closed
545 /// \param      success If false, the file will be removed from the disk.
546 ///
547 /// \return     Zero if closing succeeds. On error, -1 is returned and
548 ///             error message printed.
549 static int
550 io_close_dest(file_pair *pair, bool success)
551 {
552         if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
553                 return 0;
554
555         if (close(pair->dest_fd)) {
556                 message_error(_("%s: Closing the file failed: %s"),
557                                 pair->dest_name, strerror(errno));
558
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);
563                 return -1;
564         }
565
566         // If the operation using this file wasn't successful, we git rid
567         // of the junk file.
568         if (!success)
569                 io_unlink(pair->dest_name, &pair->dest_st);
570
571         free(pair->dest_name);
572
573         return 0;
574 }
575
576
577 extern file_pair *
578 io_open(const char *src_name)
579 {
580         if (is_empty_filename(src_name))
581                 return NULL;
582
583         // Since we have only one file open at a time, we can use
584         // a statically allocated structure.
585         static file_pair pair;
586
587         pair = (file_pair){
588                 .src_name = src_name,
589                 .dest_name = NULL,
590                 .src_fd = -1,
591                 .dest_fd = -1,
592                 .src_eof = false,
593         };
594
595         // Block the signals, for which we have a custom signal handler, so
596         // that we don't need to worry about EINTR.
597         signals_block();
598
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()
603                 // succeeded.
604                 if (user_abort || io_open_dest(&pair))
605                         io_close_src(&pair, false);
606                 else
607                         ret = &pair;
608         }
609
610         signals_unblock();
611
612         return ret;
613 }
614
615
616 extern void
617 io_close(file_pair *pair, bool success)
618 {
619         signals_block();
620
621         if (success && pair->dest_fd != STDOUT_FILENO)
622                 io_copy_attrs(pair);
623
624         // Close the destination first. If it fails, we must not remove
625         // the source file!
626         if (io_close_dest(pair, success))
627                 success = false;
628
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
631         // source file.
632         io_close_src(pair, success);
633
634         signals_unblock();
635
636         return;
637 }
638
639
640 extern size_t
641 io_read(file_pair *pair, uint8_t *buf, size_t size)
642 {
643         // We use small buffers here.
644         assert(size < SSIZE_MAX);
645
646         size_t left = size;
647
648         while (left > 0) {
649                 const ssize_t amount = read(pair->src_fd, buf, left);
650
651                 if (amount == 0) {
652                         pair->src_eof = true;
653                         break;
654                 }
655
656                 if (amount == -1) {
657                         if (errno == EINTR) {
658                                 if (user_abort)
659                                         return SIZE_MAX;
660
661                                 continue;
662                         }
663
664                         message_error(_("%s: Read error: %s"),
665                                         pair->src_name, strerror(errno));
666
667                         // FIXME Is this needed?
668                         pair->src_eof = true;
669
670                         return SIZE_MAX;
671                 }
672
673                 buf += (size_t)(amount);
674                 left -= (size_t)(amount);
675         }
676
677         return size - left;
678 }
679
680
681 extern bool
682 io_write(const file_pair *pair, const uint8_t *buf, size_t size)
683 {
684         assert(size < SSIZE_MAX);
685
686         while (size > 0) {
687                 const ssize_t amount = write(pair->dest_fd, buf, size);
688                 if (amount == -1) {
689                         if (errno == EINTR) {
690                                 if (user_abort)
691                                         return -1;
692
693                                 continue;
694                         }
695
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
702                         // GNU bash).
703                         //
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.
708                         if (errno != EPIPE)
709                                 message_error(_("%s: Write error: %s"),
710                                         pair->dest_name, strerror(errno));
711
712                         return true;
713                 }
714
715                 buf += (size_t)(amount);
716                 size -= (size_t)(amount);
717         }
718
719         return false;
720 }