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