]> icculus.org git repositories - icculus/xz.git/blob - src/xz/file_io.c
Improve displaying of the memory usage limit.
[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 /// If true, try to create sparse files when decompressing.
41 static bool try_sparse = true;
42
43 #ifndef TUKLIB_DOSLIKE
44 /// File status flags of standard output. This is used by io_open_dest()
45 /// and io_close_dest().
46 static int stdout_flags = 0;
47 #endif
48
49
50 static bool io_write_buf(file_pair *pair, const uint8_t *buf, size_t size);
51
52
53 extern void
54 io_init(void)
55 {
56         // Make sure that stdin, stdout, and and stderr are connected to
57         // a valid file descriptor. Exit immediatelly with exit code ERROR
58         // if we cannot make the file descriptors valid. Maybe we should
59         // print an error message, but our stderr could be screwed anyway.
60         tuklib_open_stdxxx(E_ERROR);
61
62 #ifndef TUKLIB_DOSLIKE
63         // If fchown() fails setting the owner, we warn about it only if
64         // we are root.
65         warn_fchown = geteuid() == 0;
66 #endif
67
68 #ifdef __DJGPP__
69         // Avoid doing useless things when statting files.
70         // This isn't important but doesn't hurt.
71         _djstat_flags = _STAT_INODE | _STAT_EXEC_EXT
72                         | _STAT_EXEC_MAGIC | _STAT_DIRSIZE;
73 #endif
74
75         return;
76 }
77
78
79 extern void
80 io_no_sparse(void)
81 {
82         try_sparse = false;
83         return;
84 }
85
86
87 /// \brief      Unlink a file
88 ///
89 /// This tries to verify that the file being unlinked really is the file that
90 /// we want to unlink by verifying device and inode numbers. There's still
91 /// a small unavoidable race, but this is much better than nothing (the file
92 /// could have been moved/replaced even hours earlier).
93 static void
94 io_unlink(const char *name, const struct stat *known_st)
95 {
96 #if defined(TUKLIB_DOSLIKE)
97         // On DOS-like systems, st_ino is meaningless, so don't bother
98         // testing it. Just silence a compiler warning.
99         (void)known_st;
100 #else
101         struct stat new_st;
102
103         if (lstat(name, &new_st)
104 #       ifdef __VMS
105                         // st_ino is an array, and we don't want to
106                         // compare st_dev at all.
107                         || memcmp(&new_st.st_ino, &known_st->st_ino,
108                                 sizeof(new_st.st_ino)) != 0
109 #       else
110                         // Typical POSIX-like system
111                         || new_st.st_dev != known_st->st_dev
112                         || new_st.st_ino != known_st->st_ino
113 #       endif
114                         )
115                 // TRANSLATORS: When compression or decompression finishes,
116                 // and xz is going to remove the source file, xz first checks
117                 // if the source file still exists, and if it does, does its
118                 // device and inode numbers match what xz saw when it opened
119                 // the source file. If these checks fail, this message is
120                 // shown, %s being the filename, and the file is not deleted.
121                 // The check for device and inode numbers is there, because
122                 // it is possible that the user has put a new file in place
123                 // of the original file, and in that case it obviously
124                 // shouldn't be removed.
125                 message_error(_("%s: File seems to have been moved, "
126                                 "not removing"), name);
127         else
128 #endif
129                 // There's a race condition between lstat() and unlink()
130                 // but at least we have tried to avoid removing wrong file.
131                 if (unlink(name))
132                         message_error(_("%s: Cannot remove: %s"),
133                                         name, strerror(errno));
134
135         return;
136 }
137
138
139 /// \brief      Copies owner/group and permissions
140 ///
141 /// \todo       ACL and EA support
142 ///
143 static void
144 io_copy_attrs(const file_pair *pair)
145 {
146         // Skip chown and chmod on Windows.
147 #ifndef TUKLIB_DOSLIKE
148         // This function is more tricky than you may think at first.
149         // Blindly copying permissions may permit users to access the
150         // destination file who didn't have permission to access the
151         // source file.
152
153         // Try changing the owner of the file. If we aren't root or the owner
154         // isn't already us, fchown() probably doesn't succeed. We warn
155         // about failing fchown() only if we are root.
156         if (fchown(pair->dest_fd, pair->src_st.st_uid, -1) && warn_fchown)
157                 message_warning(_("%s: Cannot set the file owner: %s"),
158                                 pair->dest_name, strerror(errno));
159
160         mode_t mode;
161
162         if (fchown(pair->dest_fd, -1, pair->src_st.st_gid)) {
163                 message_warning(_("%s: Cannot set the file group: %s"),
164                                 pair->dest_name, strerror(errno));
165                 // We can still safely copy some additional permissions:
166                 // `group' must be at least as strict as `other' and
167                 // also vice versa.
168                 //
169                 // NOTE: After this, the owner of the source file may
170                 // get additional permissions. This shouldn't be too bad,
171                 // because the owner would have had permission to chmod
172                 // the original file anyway.
173                 mode = ((pair->src_st.st_mode & 0070) >> 3)
174                                 & (pair->src_st.st_mode & 0007);
175                 mode = (pair->src_st.st_mode & 0700) | (mode << 3) | mode;
176         } else {
177                 // Drop the setuid, setgid, and sticky bits.
178                 mode = pair->src_st.st_mode & 0777;
179         }
180
181         if (fchmod(pair->dest_fd, mode))
182                 message_warning(_("%s: Cannot set the file permissions: %s"),
183                                 pair->dest_name, strerror(errno));
184 #endif
185
186         // Copy the timestamps. We have several possible ways to do this, of
187         // which some are better in both security and precision.
188         //
189         // First, get the nanosecond part of the timestamps. As of writing,
190         // it's not standardized by POSIX, and there are several names for
191         // the same thing in struct stat.
192         long atime_nsec;
193         long mtime_nsec;
194
195 #       if defined(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
196         // GNU and Solaris
197         atime_nsec = pair->src_st.st_atim.tv_nsec;
198         mtime_nsec = pair->src_st.st_mtim.tv_nsec;
199
200 #       elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
201         // BSD
202         atime_nsec = pair->src_st.st_atimespec.tv_nsec;
203         mtime_nsec = pair->src_st.st_mtimespec.tv_nsec;
204
205 #       elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC)
206         // GNU and BSD without extensions
207         atime_nsec = pair->src_st.st_atimensec;
208         mtime_nsec = pair->src_st.st_mtimensec;
209
210 #       elif defined(HAVE_STRUCT_STAT_ST_UATIME)
211         // Tru64
212         atime_nsec = pair->src_st.st_uatime * 1000;
213         mtime_nsec = pair->src_st.st_umtime * 1000;
214
215 #       elif defined(HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC)
216         // UnixWare
217         atime_nsec = pair->src_st.st_atim.st__tim.tv_nsec;
218         mtime_nsec = pair->src_st.st_mtim.st__tim.tv_nsec;
219
220 #       else
221         // Safe fallback
222         atime_nsec = 0;
223         mtime_nsec = 0;
224 #       endif
225
226         // Construct a structure to hold the timestamps and call appropriate
227         // function to set the timestamps.
228 #if defined(HAVE_FUTIMENS)
229         // Use nanosecond precision.
230         struct timespec tv[2];
231         tv[0].tv_sec = pair->src_st.st_atime;
232         tv[0].tv_nsec = atime_nsec;
233         tv[1].tv_sec = pair->src_st.st_mtime;
234         tv[1].tv_nsec = mtime_nsec;
235
236         (void)futimens(pair->dest_fd, tv);
237
238 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
239         // Use microsecond precision.
240         struct timeval tv[2];
241         tv[0].tv_sec = pair->src_st.st_atime;
242         tv[0].tv_usec = atime_nsec / 1000;
243         tv[1].tv_sec = pair->src_st.st_mtime;
244         tv[1].tv_usec = mtime_nsec / 1000;
245
246 #       if defined(HAVE_FUTIMES)
247         (void)futimes(pair->dest_fd, tv);
248 #       elif defined(HAVE_FUTIMESAT)
249         (void)futimesat(pair->dest_fd, NULL, tv);
250 #       else
251         // Argh, no function to use a file descriptor to set the timestamp.
252         (void)utimes(pair->dest_name, tv);
253 #       endif
254
255 #elif defined(HAVE_UTIME)
256         // Use one-second precision. utime() doesn't support using file
257         // descriptor either. Some systems have broken utime() prototype
258         // so don't make this const.
259         struct utimbuf buf = {
260                 .actime = pair->src_st.st_atime,
261                 .modtime = pair->src_st.st_mtime,
262         };
263
264         // Avoid warnings.
265         (void)atime_nsec;
266         (void)mtime_nsec;
267
268         (void)utime(pair->dest_name, &buf);
269 #endif
270
271         return;
272 }
273
274
275 /// Opens the source file. Returns false on success, true on error.
276 static bool
277 io_open_src_real(file_pair *pair)
278 {
279         // There's nothing to open when reading from stdin.
280         if (pair->src_name == stdin_filename) {
281                 pair->src_fd = STDIN_FILENO;
282 #ifdef TUKLIB_DOSLIKE
283                 setmode(STDIN_FILENO, O_BINARY);
284 #endif
285                 return false;
286         }
287
288         // Symlinks are not followed unless writing to stdout or --force
289         // was used.
290         const bool follow_symlinks = opt_stdout || opt_force;
291
292         // We accept only regular files if we are writing the output
293         // to disk too. bzip2 allows overriding this with --force but
294         // gzip and xz don't.
295         const bool reg_files_only = !opt_stdout;
296
297         // Flags for open()
298         int flags = O_RDONLY | O_BINARY | O_NOCTTY;
299
300 #ifndef TUKLIB_DOSLIKE
301         // If we accept only regular files, we need to be careful to avoid
302         // problems with special files like devices and FIFOs. O_NONBLOCK
303         // prevents blocking when opening such files. When we want to accept
304         // special files, we must not use O_NONBLOCK, or otherwise we won't
305         // block waiting e.g. FIFOs to become readable.
306         if (reg_files_only)
307                 flags |= O_NONBLOCK;
308 #endif
309
310 #if defined(O_NOFOLLOW)
311         if (!follow_symlinks)
312                 flags |= O_NOFOLLOW;
313 #elif !defined(TUKLIB_DOSLIKE)
314         // Some POSIX-like systems lack O_NOFOLLOW (it's not required
315         // by POSIX). Check for symlinks with a separate lstat() on
316         // these systems.
317         if (!follow_symlinks) {
318                 struct stat st;
319                 if (lstat(pair->src_name, &st)) {
320                         message_error("%s: %s", pair->src_name,
321                                         strerror(errno));
322                         return true;
323
324                 } else if (S_ISLNK(st.st_mode)) {
325                         message_warning(_("%s: Is a symbolic link, "
326                                         "skipping"), pair->src_name);
327                         return true;
328                 }
329         }
330 #else
331         // Avoid warnings.
332         (void)follow_symlinks;
333 #endif
334
335         // Try to open the file. If we are accepting non-regular files,
336         // unblock the caught signals so that open() can be interrupted
337         // if it blocks e.g. due to a FIFO file.
338         if (!reg_files_only)
339                 signals_unblock();
340
341         // Maybe this wouldn't need a loop, since all the signal handlers for
342         // which we don't use SA_RESTART set user_abort to true. But it
343         // doesn't hurt to have it just in case.
344         do {
345                 pair->src_fd = open(pair->src_name, flags);
346         } while (pair->src_fd == -1 && errno == EINTR && !user_abort);
347
348         if (!reg_files_only)
349                 signals_block();
350
351         if (pair->src_fd == -1) {
352                 // If we were interrupted, don't display any error message.
353                 if (errno == EINTR) {
354                         // All the signals that don't have SA_RESTART
355                         // set user_abort.
356                         assert(user_abort);
357                         return true;
358                 }
359
360 #ifdef O_NOFOLLOW
361                 // Give an understandable error message in if reason
362                 // for failing was that the file was a symbolic link.
363                 //
364                 // Note that at least Linux, OpenBSD, Solaris, and Darwin
365                 // use ELOOP to indicate if O_NOFOLLOW was the reason
366                 // that open() failed. Because there may be
367                 // directories in the pathname, ELOOP may occur also
368                 // because of a symlink loop in the directory part.
369                 // So ELOOP doesn't tell us what actually went wrong.
370                 //
371                 // FreeBSD associates EMLINK with O_NOFOLLOW and
372                 // Tru64 uses ENOTSUP. We use these directly here
373                 // and skip the lstat() call and the associated race.
374                 // I want to hear if there are other kernels that
375                 // fail with something else than ELOOP with O_NOFOLLOW.
376                 bool was_symlink = false;
377
378 #       if defined(__FreeBSD__) || defined(__DragonFly__)
379                 if (errno == EMLINK)
380                         was_symlink = true;
381
382 #       elif defined(__digital__) && defined(__unix__)
383                 if (errno == ENOTSUP)
384                         was_symlink = true;
385
386 #       elif defined(__NetBSD__)
387                 // FIXME? As of 2008-11-20, NetBSD doesn't document what
388                 // errno is used with O_NOFOLLOW. It seems to be EFTYPE,
389                 // but since it isn't documented, it may be wrong to rely
390                 // on it here.
391                 if (errno == EFTYPE)
392                         was_symlink = true;
393
394 #       else
395                 if (errno == ELOOP && !follow_symlinks) {
396                         const int saved_errno = errno;
397                         struct stat st;
398                         if (lstat(pair->src_name, &st) == 0
399                                         && S_ISLNK(st.st_mode))
400                                 was_symlink = true;
401
402                         errno = saved_errno;
403                 }
404 #       endif
405
406                 if (was_symlink)
407                         message_warning(_("%s: Is a symbolic link, "
408                                         "skipping"), pair->src_name);
409                 else
410 #endif
411                         // Something else than O_NOFOLLOW failing
412                         // (assuming that the race conditions didn't
413                         // confuse us).
414                         message_error("%s: %s", pair->src_name,
415                                         strerror(errno));
416
417                 return true;
418         }
419
420 #ifndef TUKLIB_DOSLIKE
421         // Drop O_NONBLOCK, which is used only when we are accepting only
422         // regular files. After the open() call, we want things to block
423         // instead of giving EAGAIN.
424         if (reg_files_only) {
425                 flags = fcntl(pair->src_fd, F_GETFL);
426                 if (flags == -1)
427                         goto error_msg;
428
429                 flags &= ~O_NONBLOCK;
430
431                 if (fcntl(pair->src_fd, F_SETFL, flags))
432                         goto error_msg;
433         }
434 #endif
435
436         // Stat the source file. We need the result also when we copy
437         // the permissions, and when unlinking.
438         if (fstat(pair->src_fd, &pair->src_st))
439                 goto error_msg;
440
441         if (S_ISDIR(pair->src_st.st_mode)) {
442                 message_warning(_("%s: Is a directory, skipping"),
443                                 pair->src_name);
444                 goto error;
445         }
446
447         if (reg_files_only) {
448                 if (!S_ISREG(pair->src_st.st_mode)) {
449                         message_warning(_("%s: Not a regular file, "
450                                         "skipping"), pair->src_name);
451                         goto error;
452                 }
453
454                 // These are meaningless on Windows.
455 #ifndef TUKLIB_DOSLIKE
456                 if (pair->src_st.st_mode & (S_ISUID | S_ISGID)) {
457                         // gzip rejects setuid and setgid files even
458                         // when --force was used. bzip2 doesn't check
459                         // for them, but calls fchown() after fchmod(),
460                         // and many systems automatically drop setuid
461                         // and setgid bits there.
462                         //
463                         // We accept setuid and setgid files if
464                         // --force was used. We drop these bits
465                         // explicitly in io_copy_attr().
466                         message_warning(_("%s: File has setuid or "
467                                         "setgid bit set, skipping"),
468                                         pair->src_name);
469                         goto error;
470                 }
471
472                 if (pair->src_st.st_mode & S_ISVTX) {
473                         message_warning(_("%s: File has sticky bit "
474                                         "set, skipping"),
475                                         pair->src_name);
476                         goto error;
477                 }
478
479                 if (pair->src_st.st_nlink > 1) {
480                         message_warning(_("%s: Input file has more "
481                                         "than one hard link, "
482                                         "skipping"), pair->src_name);
483                         goto error;
484                 }
485 #endif
486         }
487
488         return false;
489
490 error_msg:
491         message_error("%s: %s", pair->src_name, strerror(errno));
492 error:
493         (void)close(pair->src_fd);
494         return true;
495 }
496
497
498 extern file_pair *
499 io_open_src(const char *src_name)
500 {
501         if (is_empty_filename(src_name))
502                 return NULL;
503
504         // Since we have only one file open at a time, we can use
505         // a statically allocated structure.
506         static file_pair pair;
507
508         pair = (file_pair){
509                 .src_name = src_name,
510                 .dest_name = NULL,
511                 .src_fd = -1,
512                 .dest_fd = -1,
513                 .src_eof = false,
514                 .dest_try_sparse = false,
515                 .dest_pending_sparse = 0,
516         };
517
518         // Block the signals, for which we have a custom signal handler, so
519         // that we don't need to worry about EINTR.
520         signals_block();
521         const bool error = io_open_src_real(&pair);
522         signals_unblock();
523
524         return error ? NULL : &pair;
525 }
526
527
528 /// \brief      Closes source file of the file_pair structure
529 ///
530 /// \param      pair    File whose src_fd should be closed
531 /// \param      success If true, the file will be removed from the disk if
532 ///                     closing succeeds and --keep hasn't been used.
533 static void
534 io_close_src(file_pair *pair, bool success)
535 {
536         if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) {
537 #ifdef TUKLIB_DOSLIKE
538                 (void)close(pair->src_fd);
539 #endif
540
541                 // If we are going to unlink(), do it before closing the file.
542                 // This way there's no risk that someone replaces the file and
543                 // happens to get same inode number, which would make us
544                 // unlink() wrong file.
545                 //
546                 // NOTE: DOS-like systems are an exception to this, because
547                 // they don't allow unlinking files that are open. *sigh*
548                 if (success && !opt_keep_original)
549                         io_unlink(pair->src_name, &pair->src_st);
550
551 #ifndef TUKLIB_DOSLIKE
552                 (void)close(pair->src_fd);
553 #endif
554         }
555
556         return;
557 }
558
559
560 static bool
561 io_open_dest_real(file_pair *pair)
562 {
563         if (opt_stdout || pair->src_fd == STDIN_FILENO) {
564                 // We don't modify or free() this.
565                 pair->dest_name = (char *)"(stdout)";
566                 pair->dest_fd = STDOUT_FILENO;
567 #ifdef TUKLIB_DOSLIKE
568                 setmode(STDOUT_FILENO, O_BINARY);
569 #endif
570         } else {
571                 pair->dest_name = suffix_get_dest_name(pair->src_name);
572                 if (pair->dest_name == NULL)
573                         return true;
574
575                 // If --force was used, unlink the target file first.
576                 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
577                         message_error(_("%s: Cannot remove: %s"),
578                                         pair->dest_name, strerror(errno));
579                         free(pair->dest_name);
580                         return true;
581                 }
582
583                 // Open the file.
584                 const int flags = O_WRONLY | O_BINARY | O_NOCTTY
585                                 | O_CREAT | O_EXCL;
586                 const mode_t mode = S_IRUSR | S_IWUSR;
587                 pair->dest_fd = open(pair->dest_name, flags, mode);
588
589                 if (pair->dest_fd == -1) {
590                         message_error("%s: %s", pair->dest_name,
591                                         strerror(errno));
592                         free(pair->dest_name);
593                         return true;
594                 }
595         }
596
597         // If this really fails... well, we have a safe fallback.
598         if (fstat(pair->dest_fd, &pair->dest_st)) {
599 #if defined(__VMS)
600                 pair->dest_st.st_ino[0] = 0;
601                 pair->dest_st.st_ino[1] = 0;
602                 pair->dest_st.st_ino[2] = 0;
603 #elif !defined(TUKLIB_DOSLIKE)
604                 pair->dest_st.st_dev = 0;
605                 pair->dest_st.st_ino = 0;
606 #endif
607 #ifndef TUKLIB_DOSLIKE
608         } else if (try_sparse && opt_mode == MODE_DECOMPRESS) {
609                 // When writing to standard output, we need to be extra
610                 // careful:
611                 //  - It may be connected to something else than
612                 //    a regular file.
613                 //  - We aren't necessarily writing to a new empty file
614                 //    or to the end of an existing file.
615                 //  - O_APPEND may be active.
616                 //
617                 // TODO: I'm keeping this disabled for DOS-like systems
618                 // for now. FAT doesn't support sparse files, but NTFS
619                 // does, so maybe this should be enabled on Windows after
620                 // some testing.
621                 if (pair->dest_fd == STDOUT_FILENO) {
622                         if (!S_ISREG(pair->dest_st.st_mode))
623                                 return false;
624
625                         const int flags = fcntl(STDOUT_FILENO, F_GETFL);
626                         if (flags == -1)
627                                 return false;
628
629                         if (flags & O_APPEND) {
630                                 // Creating a sparse file is not possible
631                                 // when O_APPEND is active (it's used by
632                                 // shell's >> redirection). As I understand
633                                 // it, it is safe to temporarily disable
634                                 // O_APPEND in xz, because if someone
635                                 // happened to write to the same file at the
636                                 // same time, results would be bad anyway
637                                 // (users shouldn't assume that xz uses any
638                                 // specific block size when writing data).
639                                 //
640                                 // The write position may be something else
641                                 // than the end of the file, so we must fix
642                                 // it to start writing at the end of the file
643                                 // to imitate O_APPEND.
644                                 if (lseek(STDOUT_FILENO, 0, SEEK_END) == -1)
645                                         return false;
646
647                                 if (fcntl(STDOUT_FILENO, F_SETFL,
648                                                 stdout_flags & ~O_APPEND))
649                                         return false;
650
651                                 // Remember the flags so that io_close_dest()
652                                 // can restore them.
653                                 stdout_flags = flags;
654
655                         } else if (lseek(STDOUT_FILENO, 0, SEEK_CUR)
656                                         != pair->dest_st.st_size) {
657                                 // Writing won't start exactly at the end
658                                 // of the file. We cannot use sparse output,
659                                 // because it would probably corrupt the file.
660                                 return false;
661                         }
662                 }
663
664                 pair->dest_try_sparse = true;
665 #endif
666         }
667
668         return false;
669 }
670
671
672 extern bool
673 io_open_dest(file_pair *pair)
674 {
675         signals_block();
676         const bool ret = io_open_dest_real(pair);
677         signals_unblock();
678         return ret;
679 }
680
681
682 /// \brief      Closes destination file of the file_pair structure
683 ///
684 /// \param      pair    File whose dest_fd should be closed
685 /// \param      success If false, the file will be removed from the disk.
686 ///
687 /// \return     Zero if closing succeeds. On error, -1 is returned and
688 ///             error message printed.
689 static bool
690 io_close_dest(file_pair *pair, bool success)
691 {
692 #ifndef TUKLIB_DOSLIKE
693         // If io_open_dest() has disabled O_APPEND, restore it here.
694         if (stdout_flags != 0) {
695                 assert(pair->dest_fd == STDOUT_FILENO);
696
697                 const int fail = fcntl(STDOUT_FILENO, F_SETFL, stdout_flags);
698                 stdout_flags = 0;
699
700                 if (fail) {
701                         message_error(_("Error restoring the O_APPEND flag "
702                                         "to standard output: %s"),
703                                         strerror(errno));
704                         return true;
705                 }
706         }
707 #endif
708
709         if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
710                 return false;
711
712         if (close(pair->dest_fd)) {
713                 message_error(_("%s: Closing the file failed: %s"),
714                                 pair->dest_name, strerror(errno));
715
716                 // Closing destination file failed, so we cannot trust its
717                 // contents. Get rid of junk:
718                 io_unlink(pair->dest_name, &pair->dest_st);
719                 free(pair->dest_name);
720                 return true;
721         }
722
723         // If the operation using this file wasn't successful, we git rid
724         // of the junk file.
725         if (!success)
726                 io_unlink(pair->dest_name, &pair->dest_st);
727
728         free(pair->dest_name);
729
730         return false;
731 }
732
733
734 extern void
735 io_close(file_pair *pair, bool success)
736 {
737         // Take care of sparseness at the end of the output file.
738         if (success && pair->dest_try_sparse
739                         && pair->dest_pending_sparse > 0) {
740                 // Seek forward one byte less than the size of the pending
741                 // hole, then write one zero-byte. This way the file grows
742                 // to its correct size. An alternative would be to use
743                 // ftruncate() but that isn't portable enough (e.g. it
744                 // doesn't work with FAT on Linux; FAT isn't that important
745                 // since it doesn't support sparse files anyway, but we don't
746                 // want to create corrupt files on it).
747                 if (lseek(pair->dest_fd, pair->dest_pending_sparse - 1,
748                                 SEEK_CUR) == -1) {
749                         message_error(_("%s: Seeking failed when trying "
750                                         "to create a sparse file: %s"),
751                                         pair->dest_name, strerror(errno));
752                         success = false;
753                 } else {
754                         const uint8_t zero[1] = { '\0' };
755                         if (io_write_buf(pair, zero, 1))
756                                 success = false;
757                 }
758         }
759
760         signals_block();
761
762         // Copy the file attributes. We need to skip this if destination
763         // file isn't open or it is standard output.
764         if (success && pair->dest_fd != -1 && pair->dest_fd != STDOUT_FILENO)
765                 io_copy_attrs(pair);
766
767         // Close the destination first. If it fails, we must not remove
768         // the source file!
769         if (io_close_dest(pair, success))
770                 success = false;
771
772         // Close the source file, and unlink it if the operation using this
773         // file pair was successful and we haven't requested to keep the
774         // source file.
775         io_close_src(pair, success);
776
777         signals_unblock();
778
779         return;
780 }
781
782
783 extern size_t
784 io_read(file_pair *pair, io_buf *buf_union, size_t size)
785 {
786         // We use small buffers here.
787         assert(size < SSIZE_MAX);
788
789         uint8_t *buf = buf_union->u8;
790         size_t left = size;
791
792         while (left > 0) {
793                 const ssize_t amount = read(pair->src_fd, buf, left);
794
795                 if (amount == 0) {
796                         pair->src_eof = true;
797                         break;
798                 }
799
800                 if (amount == -1) {
801                         if (errno == EINTR) {
802                                 if (user_abort)
803                                         return SIZE_MAX;
804
805                                 continue;
806                         }
807
808                         message_error(_("%s: Read error: %s"),
809                                         pair->src_name, strerror(errno));
810
811                         // FIXME Is this needed?
812                         pair->src_eof = true;
813
814                         return SIZE_MAX;
815                 }
816
817                 buf += (size_t)(amount);
818                 left -= (size_t)(amount);
819         }
820
821         return size - left;
822 }
823
824
825 extern bool
826 io_pread(file_pair *pair, io_buf *buf, size_t size, off_t pos)
827 {
828         // Using lseek() and read() is more portable than pread() and
829         // for us it is as good as real pread().
830         if (lseek(pair->src_fd, pos, SEEK_SET) != pos) {
831                 message_error(_("%s: Error seeking the file: %s"),
832                                 pair->src_name, strerror(errno));
833                 return true;
834         }
835
836         const size_t amount = io_read(pair, buf, size);
837         if (amount == SIZE_MAX)
838                 return true;
839
840         if (amount != size) {
841                 message_error(_("%s: Unexpected end of file"),
842                                 pair->src_name);
843                 return true;
844         }
845
846         return false;
847 }
848
849
850 static bool
851 is_sparse(const io_buf *buf)
852 {
853         assert(IO_BUFFER_SIZE % sizeof(uint64_t) == 0);
854
855         for (size_t i = 0; i < ARRAY_SIZE(buf->u64); ++i)
856                 if (buf->u64[i] != 0)
857                         return false;
858
859         return true;
860 }
861
862
863 static bool
864 io_write_buf(file_pair *pair, const uint8_t *buf, size_t size)
865 {
866         assert(size < SSIZE_MAX);
867
868         while (size > 0) {
869                 const ssize_t amount = write(pair->dest_fd, buf, size);
870                 if (amount == -1) {
871                         if (errno == EINTR) {
872                                 if (user_abort)
873                                         return -1;
874
875                                 continue;
876                         }
877
878                         // Handle broken pipe specially. gzip and bzip2
879                         // don't print anything on SIGPIPE. In addition,
880                         // gzip --quiet uses exit status 2 (warning) on
881                         // broken pipe instead of whatever raise(SIGPIPE)
882                         // would make it return. It is there to hide "Broken
883                         // pipe" message on some old shells (probably old
884                         // GNU bash).
885                         //
886                         // We don't do anything special with --quiet, which
887                         // is what bzip2 does too. If we get SIGPIPE, we
888                         // will handle it like other signals by setting
889                         // user_abort, and get EPIPE here.
890                         if (errno != EPIPE)
891                                 message_error(_("%s: Write error: %s"),
892                                         pair->dest_name, strerror(errno));
893
894                         return true;
895                 }
896
897                 buf += (size_t)(amount);
898                 size -= (size_t)(amount);
899         }
900
901         return false;
902 }
903
904
905 extern bool
906 io_write(file_pair *pair, const io_buf *buf, size_t size)
907 {
908         assert(size <= IO_BUFFER_SIZE);
909
910         if (pair->dest_try_sparse) {
911                 // Check if the block is sparse (contains only zeros). If it
912                 // sparse, we just store the amount and return. We will take
913                 // care of actually skipping over the hole when we hit the
914                 // next data block or close the file.
915                 //
916                 // Since io_close() requires that dest_pending_sparse > 0
917                 // if the file ends with sparse block, we must also return
918                 // if size == 0 to avoid doing the lseek().
919                 if (size == IO_BUFFER_SIZE) {
920                         if (is_sparse(buf)) {
921                                 pair->dest_pending_sparse += size;
922                                 return false;
923                         }
924                 } else if (size == 0) {
925                         return false;
926                 }
927
928                 // This is not a sparse block. If we have a pending hole,
929                 // skip it now.
930                 if (pair->dest_pending_sparse > 0) {
931                         if (lseek(pair->dest_fd, pair->dest_pending_sparse,
932                                         SEEK_CUR) == -1) {
933                                 message_error(_("%s: Seeking failed when "
934                                                 "trying to create a sparse "
935                                                 "file: %s"), pair->dest_name,
936                                                 strerror(errno));
937                                 return true;
938                         }
939
940                         pair->dest_pending_sparse = 0;
941                 }
942         }
943
944         return io_write_buf(pair, buf->u8, size);
945 }