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