]> icculus.org git repositories - icculus/xz.git/blob - src/xz/file_io.c
Create sparse files by default when decompressing into
[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 unlink: %s",
528                                         pair->dest_name, strerror(errno));
529                         free(pair->dest_name);
530                         return true;
531                 }
532
533                 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
534                         message_error("%s: Cannot unlink: %s",
535                                         pair->dest_name, strerror(errno));
536                         free(pair->dest_name);
537                         return true;
538                 }
539
540                 // Open the file.
541                 const int flags = O_WRONLY | O_BINARY | O_NOCTTY
542                                 | O_CREAT | O_EXCL;
543                 const mode_t mode = S_IRUSR | S_IWUSR;
544                 pair->dest_fd = open(pair->dest_name, flags, mode);
545
546                 if (pair->dest_fd == -1) {
547                         // Don't bother with error message if user requested
548                         // us to exit anyway.
549                         if (!user_abort)
550                                 message_error("%s: %s", pair->dest_name,
551                                                 strerror(errno));
552
553                         free(pair->dest_name);
554                         return true;
555                 }
556         }
557
558         // If this really fails... well, we have a safe fallback.
559         if (fstat(pair->dest_fd, &pair->dest_st)) {
560 #if defined(__VMS)
561                 pair->dest_st.st_ino[0] = 0;
562                 pair->dest_st.st_ino[1] = 0;
563                 pair->dest_st.st_ino[2] = 0;
564 #elif !defined(TUKLIB_DOSLIKE)
565                 pair->dest_st.st_dev = 0;
566                 pair->dest_st.st_ino = 0;
567 #endif
568 #ifndef TUKLIB_DOSLIKE
569         } else if (try_sparse && opt_mode == MODE_DECOMPRESS) {
570                 // When writing to standard output, we need to be extra
571                 // careful:
572                 //  - It may be connected to something else than
573                 //    a regular file.
574                 //  - We aren't necessarily writing to a new empty file
575                 //    or to the end of an existing file.
576                 //  - O_APPEND may be active.
577                 //
578                 // TODO: I'm keeping this disabled for DOS-like systems
579                 // for now. FAT doesn't support sparse files, but NTFS
580                 // does, so maybe this should be enabled on Windows after
581                 // some testing.
582                 if (pair->dest_fd == STDOUT_FILENO) {
583                         if (!S_ISREG(pair->dest_st.st_mode))
584                                 return false;
585
586                         const int flags = fcntl(STDOUT_FILENO, F_GETFL);
587                         if (flags == -1)
588                                 return false;
589
590                         if (flags & O_APPEND) {
591                                 // Creating a sparse file is not possible
592                                 // when O_APPEND is active (it's used by
593                                 // shell's >> redirection). As I understand
594                                 // it, it is safe to temporarily disable
595                                 // O_APPEND in xz, because if someone
596                                 // happened to write to the same file at the
597                                 // same time, results would be bad anyway
598                                 // (users shouldn't assume that xz uses any
599                                 // specific block size when writing data).
600                                 //
601                                 // The write position may be something else
602                                 // than the end of the file, so we must fix
603                                 // it to start writing at the end of the file
604                                 // to imitate O_APPEND.
605                                 if (lseek(STDOUT_FILENO, 0, SEEK_END) == -1)
606                                         return false;
607
608                                 if (fcntl(STDOUT_FILENO, F_SETFL,
609                                                 stdout_flags & ~O_APPEND))
610                                         return false;
611
612                                 // Remember the flags so that io_close_dest()
613                                 // can restore them.
614                                 stdout_flags = flags;
615
616                         } else if (lseek(STDOUT_FILENO, 0, SEEK_CUR)
617                                         != pair->dest_st.st_size) {
618                                 // Writing won't start exactly at the end
619                                 // of the file. We cannot use sparse output,
620                                 // because it would probably corrupt the file.
621                                 return false;
622                         }
623                 }
624
625                 pair->dest_try_sparse = true;
626 #endif
627         }
628
629         return false;
630 }
631
632
633 /// \brief      Closes destination file of the file_pair structure
634 ///
635 /// \param      pair    File whose dest_fd should be closed
636 /// \param      success If false, the file will be removed from the disk.
637 ///
638 /// \return     Zero if closing succeeds. On error, -1 is returned and
639 ///             error message printed.
640 static int
641 io_close_dest(file_pair *pair, bool success)
642 {
643         // If io_open_dest() has disabled O_APPEND, restore it here.
644         if (stdout_flags != 0) {
645                 assert(pair->dest_fd == STDOUT_FILENO);
646
647                 const int fail = fcntl(STDOUT_FILENO, F_SETFL, stdout_flags);
648                 stdout_flags = 0;
649
650                 if (fail) {
651                         message_error(_("Error restoring the O_APPEND flag "
652                                         "to standard output: %s"),
653                                         strerror(errno));
654                         return -1;
655                 }
656         }
657
658         if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
659                 return 0;
660
661         if (close(pair->dest_fd)) {
662                 message_error(_("%s: Closing the file failed: %s"),
663                                 pair->dest_name, strerror(errno));
664
665                 // Closing destination file failed, so we cannot trust its
666                 // contents. Get rid of junk:
667                 io_unlink(pair->dest_name, &pair->dest_st);
668                 free(pair->dest_name);
669                 return -1;
670         }
671
672         // If the operation using this file wasn't successful, we git rid
673         // of the junk file.
674         if (!success)
675                 io_unlink(pair->dest_name, &pair->dest_st);
676
677         free(pair->dest_name);
678
679         return 0;
680 }
681
682
683 extern file_pair *
684 io_open(const char *src_name)
685 {
686         if (is_empty_filename(src_name))
687                 return NULL;
688
689         // Since we have only one file open at a time, we can use
690         // a statically allocated structure.
691         static file_pair pair;
692
693         pair = (file_pair){
694                 .src_name = src_name,
695                 .dest_name = NULL,
696                 .src_fd = -1,
697                 .dest_fd = -1,
698                 .src_eof = false,
699                 .dest_try_sparse = false,
700                 .dest_pending_sparse = 0,
701         };
702
703         // Block the signals, for which we have a custom signal handler, so
704         // that we don't need to worry about EINTR.
705         signals_block();
706
707         file_pair *ret = NULL;
708         if (!io_open_src(&pair)) {
709                 // io_open_src() may have unblocked the signals temporarily,
710                 // and thus user_abort may have got set even if open()
711                 // succeeded.
712                 if (user_abort || io_open_dest(&pair))
713                         io_close_src(&pair, false);
714                 else
715                         ret = &pair;
716         }
717
718         signals_unblock();
719
720         return ret;
721 }
722
723
724 extern void
725 io_close(file_pair *pair, bool success)
726 {
727         // Take care of sparseness at the end of the output file.
728         if (success && pair->dest_try_sparse
729                         && pair->dest_pending_sparse > 0) {
730                 // Seek forward one byte less than the size of the pending
731                 // hole, then write one zero-byte. This way the file grows
732                 // to its correct size. An alternative would be to use
733                 // ftruncate() but that isn't portable enough (e.g. it
734                 // doesn't work with FAT on Linux; FAT isn't that important
735                 // since it doesn't support sparse files anyway, but we don't
736                 // want to create corrupt files on it).
737                 if (lseek(pair->dest_fd, pair->dest_pending_sparse - 1,
738                                 SEEK_CUR) == -1) {
739                         message_error(_("%s: Seeking failed when trying "
740                                         "to create a sparse file: %s"),
741                                         pair->dest_name, strerror(errno));
742                         success = false;
743                 } else {
744                         const uint8_t zero[1] = { '\0' };
745                         if (io_write_buf(pair, zero, 1))
746                                 success = false;
747                 }
748         }
749
750         signals_block();
751
752         if (success && pair->dest_fd != STDOUT_FILENO)
753                 io_copy_attrs(pair);
754
755         // Close the destination first. If it fails, we must not remove
756         // the source file!
757         if (io_close_dest(pair, success))
758                 success = false;
759
760         // Close the source file, and unlink it if the operation using this
761         // file pair was successful and we haven't requested to keep the
762         // source file.
763         io_close_src(pair, success);
764
765         signals_unblock();
766
767         return;
768 }
769
770
771 extern size_t
772 io_read(file_pair *pair, io_buf *buf_union, size_t size)
773 {
774         // We use small buffers here.
775         assert(size < SSIZE_MAX);
776
777         uint8_t *buf = buf_union->u8;
778         size_t left = size;
779
780         while (left > 0) {
781                 const ssize_t amount = read(pair->src_fd, buf, left);
782
783                 if (amount == 0) {
784                         pair->src_eof = true;
785                         break;
786                 }
787
788                 if (amount == -1) {
789                         if (errno == EINTR) {
790                                 if (user_abort)
791                                         return SIZE_MAX;
792
793                                 continue;
794                         }
795
796                         message_error(_("%s: Read error: %s"),
797                                         pair->src_name, strerror(errno));
798
799                         // FIXME Is this needed?
800                         pair->src_eof = true;
801
802                         return SIZE_MAX;
803                 }
804
805                 buf += (size_t)(amount);
806                 left -= (size_t)(amount);
807         }
808
809         return size - left;
810 }
811
812
813 static bool
814 is_sparse(const io_buf *buf)
815 {
816         assert(IO_BUFFER_SIZE % sizeof(uint64_t) == 0);
817
818         for (size_t i = 0; i < ARRAY_SIZE(buf->u64); ++i)
819                 if (buf->u64[i] != 0)
820                         return false;
821
822         return true;
823 }
824
825
826 static bool
827 io_write_buf(file_pair *pair, const uint8_t *buf, size_t size)
828 {
829         assert(size < SSIZE_MAX);
830
831         while (size > 0) {
832                 const ssize_t amount = write(pair->dest_fd, buf, size);
833                 if (amount == -1) {
834                         if (errno == EINTR) {
835                                 if (user_abort)
836                                         return -1;
837
838                                 continue;
839                         }
840
841                         // Handle broken pipe specially. gzip and bzip2
842                         // don't print anything on SIGPIPE. In addition,
843                         // gzip --quiet uses exit status 2 (warning) on
844                         // broken pipe instead of whatever raise(SIGPIPE)
845                         // would make it return. It is there to hide "Broken
846                         // pipe" message on some old shells (probably old
847                         // GNU bash).
848                         //
849                         // We don't do anything special with --quiet, which
850                         // is what bzip2 does too. If we get SIGPIPE, we
851                         // will handle it like other signals by setting
852                         // user_abort, and get EPIPE here.
853                         if (errno != EPIPE)
854                                 message_error(_("%s: Write error: %s"),
855                                         pair->dest_name, strerror(errno));
856
857                         return true;
858                 }
859
860                 buf += (size_t)(amount);
861                 size -= (size_t)(amount);
862         }
863
864         return false;
865 }
866
867
868 extern bool
869 io_write(file_pair *pair, const io_buf *buf, size_t size)
870 {
871         assert(size <= IO_BUFFER_SIZE);
872
873         if (pair->dest_try_sparse) {
874                 // Check if the block is sparse (contains only zeros). If it
875                 // sparse, we just store the amount and return. We will take
876                 // care of actually skipping over the hole when we hit the
877                 // next data block or close the file.
878                 //
879                 // Since io_close() requires that dest_pending_sparse > 0
880                 // if the file ends with sparse block, we must also return
881                 // if size == 0 to avoid doing the lseek().
882                 if (size == IO_BUFFER_SIZE) {
883                         if (is_sparse(buf)) {
884                                 pair->dest_pending_sparse += size;
885                                 return false;
886                         }
887                 } else if (size == 0) {
888                         return false;
889                 }
890
891                 // This is not a sparse block. If we have a pending hole,
892                 // skip it now.
893                 if (pair->dest_pending_sparse > 0) {
894                         if (lseek(pair->dest_fd, pair->dest_pending_sparse,
895                                         SEEK_CUR) == -1) {
896                                 message_error(_("%s: Seeking failed when "
897                                                 "trying to create a sparse "
898                                                 "file: %s"), pair->dest_name,
899                                                 strerror(errno));
900                                 return true;
901                         }
902
903                         pair->dest_pending_sparse = 0;
904                 }
905         }
906
907         return io_write_buf(pair, buf->u8, size);
908 }