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