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